Example #1
0
function handle_exception($e)
{
    $template = App\Config::get('debug') ? 'debug' : '5xx';
    $view = new App\Template($template, compact('e'));
    $response = new Symfony\Component\HttpFoundation\Response($view->fetch(), Symfony\Component\HttpFoundation\Response::HTTP_INTERNAL_SERVER_ERROR);
    $response->send();
}
Example #2
0
 public function indexAction(Request $request)
 {
     $this->get('monolog.logger.tapatalk')->debug('############################');
     $this->get('monolog.logger.tapatalk')->debug('Current User:'******'symbb.core.user.manager')->getCurrentUser()->getUsername());
     $this->get('monolog.logger.tapatalk')->debug("Has Session: " . $request->hasPreviousSession());
     foreach ($request->headers as $name => $param) {
         $this->get('monolog.logger.tapatalk')->debug("Request Header (" . $name . "): " . implode(", ", $param));
     }
     $server = new \Zend\XmlRpc\Server();
     $server->setReturnResponse(true);
     $server->setClass($this->get('symbb.extension.tapatalk.manager.call'));
     $responseZend = $server->handle();
     // error case
     if ($responseZend instanceof \Zend\XmlRpc\Fault) {
         $sfResponse = new \Symfony\Component\HttpFoundation\Response();
         $sfResponse->headers->set('Content-Type', 'text/xml; charset=UTF-8');
         $sfResponse->setContent($responseZend->saveXml());
     } else {
         $sfResponse = $responseZend->getReturnValue();
     }
     $sfResponse = $this->addResponseHeader($sfResponse);
     foreach ($sfResponse->headers as $name => $param) {
         $this->get('monolog.logger.tapatalk')->debug("Response Header (" . $name . "): " . implode(", ", $param));
     }
     return $sfResponse;
 }
Example #3
0
 /**
  * Start a big file download on Laravel Framework 4.0 / 4.1
  * Source (originally for Laravel 3.*) : http://stackoverflow.com/questions/15942497/why-dont-large-files-download-easily-in-laravel
  * @param  string $path    Path to the big file
  * @param  string $name    Name of the file (used in Content-disposition header)
  * @param  array  $headers Some extra headers
  */
 public function sendFile($path, $name = null, array $headers = array())
 {
     if (is_null($name)) {
         $name = basename($path);
     }
     $file = new \Symfony\Component\HttpFoundation\File\File($path);
     $mime = $file->getMimeType();
     // Prepare the headers
     $headers = array_merge(array('Content-Description' => 'File Transfer', 'Content-Type' => $mime, 'Content-Transfer-Encoding' => 'binary', 'Expires' => 0, 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Pragma' => 'public', 'Content-Length' => \File::size($path), 'Content-Disposition' => 'attachment; filename=' . $name), $headers);
     $response = new \Symfony\Component\HttpFoundation\Response('', 200, $headers);
     // If there's a session we should save it now
     if (\Config::get('session.driver') !== '') {
         \Session::save();
     }
     session_write_close();
     if (ob_get_length()) {
         ob_end_clean();
     }
     $response->sendHeaders();
     // Read the file
     if ($file = fopen($path, 'rb')) {
         while (!feof($file) and connection_status() == 0) {
             print fread($file, 1024 * 8);
             flush();
         }
         fclose($file);
     }
     // Finish off, like Laravel would
     \Event::fire('laravel.done', array($response));
     $response->send();
 }
Example #4
0
 /**
  * error 404 page. useful when: page not found, content not found.
  * 
  * @return string
  */
 public function indexAction()
 {
     $response = new \Symfony\Component\HttpFoundation\Response();
     $response->setStatusCode(404);
     $response->setcontent($this->Theme->render('errors/templates/e404/index'));
     return $response;
 }
Example #5
0
 protected function restResult($obj, $status = 200)
 {
     $response = new \Symfony\Component\HttpFoundation\Response();
     $classParser = $this->container->get("rest.internal_class_parser");
     $content = $classParser->serializeObject($obj);
     $response->setContent($content["result"]);
     $response->headers->add(array("content-type" => $content["type"]));
     $response->setStatusCode($status);
     return $response;
 }
 public function generateTrackAction($id)
 {
     $entity = $this->getDoctrine()->getRepository('IUTCatalogBundle:Enregistrement')->find($id);
     $content = $entity->getExtrait();
     $track = stream_get_contents($content);
     $track = pack("H*", $track);
     $response = new \Symfony\Component\HttpFoundation\Response();
     $response->headers->set('Content-type', 'audio/mpeg');
     $response->headers->set('Content-Transfer-Encoding', 'binary');
     $response->setContent($track);
     return $response;
 }
 /**
  * @Route("ajax_persona", name="ajax_persona")
  */
 public function ajaxPersonaAction(\Symfony\Component\HttpFoundation\Request $request)
 {
     $value = $request->get('term');
     $em = $this->getEm();
     $members = $em->getRepository('YacareBaseBundle:Persona')->createQueryBuilder('o')->where('o.NombreVisible = :nombrevisible')->setParameter('nombrevisible', $value)->getQuery()->getResult();
     $json = array();
     foreach ($members as $member) {
         $json[] = array('label' => $member->getNombreVisible(), 'value' => $member->getId());
     }
     $response = new \Symfony\Component\HttpFoundation\Response();
     $response->setContent(json_encode($json));
     return $response;
 }
Example #8
0
 /**
  * @Route("/download/{id}", name="ac_media_bundle_file_download")
  */
 public function downloadAction(\AC\MediaBundle\Entity\File $file)
 {
     ini_set('memory_limit', '-1');
     $doc = $this->container->getParameter('app_root_files');
     $doc .= \AC\MediaBundle\Services\EvenementService::generateUrl($file->getEvenement());
     $doc .= $file->getName();
     $response = new \Symfony\Component\HttpFoundation\Response();
     $response->setContent(file_get_contents($doc));
     $response->headers->set('Content-Type', 'audio');
     // modification du content-type pour forcer le téléchargement (sinon le navigateur internet essaie d'afficher le document)
     $response->headers->set('Content-disposition', 'filename=' . $file->getName());
     return $response;
 }
 private function downloadResponse($service)
 {
     $result = $service->execute();
     $csvFile = $result['file'];
     $filename = $result['filename'];
     $response = new \Symfony\Component\HttpFoundation\Response();
     $response->setStatusCode(200);
     $response->setContent(file_get_contents($csvFile));
     $response->headers->set('Content-Type', 'application/stream');
     $response->headers->set('Content-length', filesize($csvFile));
     $response->headers->set('Content-Disposition', sprintf('attachment;filename="%s"', $filename));
     $response->send();
     return $response;
 }
 /**
  * Dispatch a CalendarEvent and return a JSON Response of any events returned.
  * 
  * @param Request $request
  * @return Response
  */
 public function loadCalendarAction(Request $request)
 {
     $startDatetime = \DateTime::createFromFormat('Y-m-d', $request->get('start'));
     $endDatetime = \DateTime::createFromFormat('Y-m-d', $request->get('end'));
     $events = $this->container->get('event_dispatcher')->dispatch(CalendarEvent::CONFIGURE, new CalendarEvent($startDatetime, $endDatetime, $request))->getEvents();
     $response = new \Symfony\Component\HttpFoundation\Response();
     $response->headers->set('Content-Type', 'application/json');
     $return_events = array();
     foreach ($events as $event) {
         $return_events[] = $event->toArray();
     }
     $response->setContent(json_encode($return_events));
     return $response;
 }
 public function onKernelResponse(FilterResponseEvent $event)
 {
     if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
         // don't do anything if it's not the master request
         return;
     }
     if (false === strpos($event->getRequest()->getRequestUri(), 'login')) {
         if ($event->getRequest()->isXmlHttpRequest() && $event->getResponse()->getStatusCode() == "302") {
             $event->getResponse()->setStatusCode(401);
             $response = new \Symfony\Component\HttpFoundation\Response();
             $response->setStatusCode(401);
             $event->setResponse($response);
         }
     }
 }
Example #12
0
 protected function getResponse($value, $type, $login = false)
 {
     $valueObject = \Zend\XmlRpc\AbstractValue::getXmlRpcValue($value, $type);
     $content = '<?xml version="1.0" encoding="UTF-8"?><methodResponse><params><param>' . $valueObject->saveXml() . '</param></params></methodResponse>';
     $this->debug("XML: " . $content);
     $response = new \Symfony\Component\HttpFoundation\Response();
     $response->headers->set('Content-Type', 'text/xml');
     $response->setContent($content);
     $response->setPrivate();
     $response->setMaxAge(100);
     $user = $this->userManager->getCurrentUser();
     if ($user->getSymbbType() === 'user') {
         $response->headers->set('Mobiquo_is_login', "true");
     } else {
         $response->headers->set('Mobiquo_is_login', false);
     }
     return $response;
 }
 public function eventDroppedAction(Request $request)
 {
     $userId = $request->get('id');
     $startDatetime = \DateTime::createFromFormat('D M d Y H:i:s e+', $request->get('date'));
     $endDatetime = clone $startDatetime;
     $endDatetime->add(new \DateInterval('PT4H'));
     $installationId = $request->get('installationId');
     $addEvent = new AddEvent($startDatetime, $endDatetime, $userId, $installationId);
     $event = $this->container->get('event_dispatcher')->dispatch(AddEvent::CONFIGURE, $addEvent);
     $eventData = new \stdClass();
     $eventData->title = $event->getTitle();
     $eventData->id = $event->getEventId();
     $eventData->start = $addEvent->getStartDatetime()->getTimestamp();
     $eventData->end = $addEvent->getEndDatetime()->getTimestamp();
     $eventData->allDay = false;
     $response = new \Symfony\Component\HttpFoundation\Response();
     $response->headers->set('Content-Type', 'application/json');
     $response->setContent(json_encode($eventData));
     return $response;
 }
 public function replaceAction(Request $request)
 {
     $dataPath = rtrim($this->container->getParameter('fferriere_spreadsheets_replacement.data_path'), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
     $form = $this->createFormBuilder()->add('file', 'file', array('label' => 'Fichier :'))->add('submit', 'submit', array('label' => 'Valider'))->getForm();
     $form->handleRequest($request);
     if ($form->isValid()) {
         if (!is_dir($dataPath)) {
             mkdir($dataPath, 0770, true);
         }
         $newFileName = date('Y-m-d-His') . '.csv';
         $form['file']->getData()->move($dataPath, $newFileName);
         $filepath = $dataPath . $newFileName;
         $replacer = $this->container->get('fferriere_spreadsheets_replacement.replacer');
         if (!$replacer instanceof \Fferriere\SpreadsheetsReplacement\Replacer\CsvReplacer) {
             throw new Exception('$replacer is not an instance of Fferriere\\SpreadsheetsReplacement\\Replacer\\CsvReplacer');
         }
         $sheet = $replacer->getSheet();
         if ($sheet instanceof \Fferriere\SpreadsheetsReplacement\Sheet\CsvSheet) {
             $sheet->setReadFilePath($filepath);
         }
         $hydrator = $this->container->get('fferriere_spreadsheets_replacement.hydrator');
         if (!$hydrator instanceof \Fferriere\SpreadsheetsReplacement\Hydrator\HydratorInterface) {
             throw new Exception('$hydrator is not an instance of Fferriere\\SpreadsheetsReplacement\\Hydrator\\HydratorInterface');
         }
         $params = (include $this->container->getParameter('fferriere_spreadsheets_replacement.replacement_pattern_path'));
         $columns = $hydrator->hydrate($params);
         $sheet->addColumns($columns);
         $newFilepath = $replacer->replaceFile();
         $filename = basename($newFilepath);
         $response = new \Symfony\Component\HttpFoundation\Response();
         $response->setStatusCode(200);
         $response->headers->set('Content-Type', 'text/csv');
         $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
         $response->headers->set('Content-Length', filesize($newFilepath));
         $response->setContent(file_get_contents($newFilepath));
         return $response;
     }
     return $this->render('FferriereSpreadsheetsReplacementBundle:Default:replace.html.twig', array('form' => $form->createView()));
 }
Example #15
0
 /**
  * {@inheritdoc}
  */
 public function sendbank(OrderInterface $order)
 {
     $params = array('order' => $order->getReference(), 'bank' => $this->getCode(), 'check' => $this->generateUrlCheck($order));
     $fields = array('cmd' => '_xclick', 'charset' => 'utf-8', 'business' => $this->getOption('account'), 'cert_id' => $this->getOption('cert_id'), 'no_shipping' => '1', 'lc' => 'EN', 'no_note' => '1', 'invoice' => $order->getReference(), 'amount' => $order->getTotalInc(), 'currency_code' => $order->getCurrency(), 'item_name' => 'Order ' . $order->getReference(), 'bn' => 'Sonata/1.0', 'first_name' => $order->getBillingName(), 'last_name' => '', 'address1' => $order->getBillingAddress1(), 'address2' => $order->getBillingAddress2(), 'city' => $order->getBillingCity(), 'zip' => $order->getBillingPostcode(), 'country' => $order->getBillingCountryCode(), 'custom' => $this->generateUrlCheck($order), 'notify_url' => $this->router->generate($this->getOption('url_callback'), $params, UrlGeneratorInterface::ABSOLUTE_URL), 'cancel_return' => $this->router->generate($this->getOption('url_return_ko'), $params, UrlGeneratorInterface::ABSOLUTE_URL), 'return' => $this->router->generate($this->getOption('url_return_ok'), $params, UrlGeneratorInterface::ABSOLUTE_URL));
     if ($this->getOption('debug', false)) {
         $html = '<html><body>' . "\n";
     } else {
         $html = '<html><body onload="document.getElementById(\'submit_button\').disabled = \'disabled\'; document.getElementById(\'formPaiement\').submit();">' . "\n";
     }
     $method = $this->getOption('method', 'encrypt');
     $html .= sprintf('<form action="%s" method="%s" id="formPaiement" >' . "\n", $this->getOption('url_action'), 'POST');
     $html .= '<input type="hidden" name="cmd" value="_s-xclick">' . "\n";
     $html .= sprintf('<input type="hidden" name="encrypted" value="%s" />', call_user_func(array($this, $method), $fields));
     $html .= '<p>' . $this->translator->trans('process_to_paiement_bank_page', array(), 'PaymentBundle') . '</p>';
     $html .= '<input type="submit" id="submit_button" value="' . $this->translator->trans('process_to_paiement_btn', array(), 'PaymentBundle') . '" />';
     $html .= '</form>';
     $html .= '</body></html>';
     if ($this->getOption('debug', false)) {
         echo "<!-- Encrypted Array : \n" . print_r($fields, 1) . '-->';
     }
     $response = new \Symfony\Component\HttpFoundation\Response($html, 200, array('Content-Type' => 'text/html'));
     $response->setPrivate(true);
     return $response;
 }
Example #16
0
 /**
  *
  */
 function getHttpResponse()
 {
     $output = ['jsonrpc' => $this->jsonrpcVersion, 'id' => isset($this->jsonRequest['id']) ? $this->jsonRequest['id'] : -9999];
     if (!is_null($this->result)) {
         $this->http_status = 200;
         $output['result'] = $this->result;
     } else {
         if (!is_null($this->error)) {
             $output['error'] = $this->error;
         }
     }
     $httpResponse = new \Symfony\Component\HttpFoundation\Response();
     if ($this->http_status === 0) {
         echo 'WTF';
     }
     $httpResponse->setStatusCode($this->http_status);
     $res = json_encode($output);
     if ($res === false) {
         $httpResponse->setContent([" content was not jason-able "]);
     } else {
         $httpResponse->setContent($res);
     }
     return $httpResponse;
 }
Example #17
0
<?php

require_once 'bootstrap.php';
$Request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
$App->setRequest($Request);
$routes = (require_once DIR_PROJECT . '/config/route.php');
$Router = new TelegramBot\Utils\Router($routes, $App);
$Response = new \Symfony\Component\HttpFoundation\Response();
try {
    $Route = $Router->findAction($Request);
    $Response->setContent($Router->resolve());
} catch (\TelegramBot\Exception\ExceptionNotFound $e) {
    $Response->setStatusCode(404);
} catch (\Exception $e) {
    $Response->setStatusCode(500);
}
$Response->send();
Example #18
0
function main()
{
    $request = Request::createFromGlobals();
    Http::Init();
    //Get routes and match with incomming url
    $context = new Routing\RequestContext();
    $context->fromRequest($request);
    $routes = Edu8\Route::getRoutes(__DIR__ . '/../routes/');
    $matcher = new Routing\Matcher\UrlMatcher($routes, $context);
    try {
        $request->attributes->add($matcher->match($request->getPathInfo()));
        $file_root = $request->attributes->get('file_root');
        $slug = $request->attributes->get('slug');
    } catch (\Exception $e) {
        $file_root = rtrim($request->getPathInfo(), '/');
        $slug = '';
        //$request->attributes->get('slug');
    }
    $twig_vars = Http::GetSession();
    if (empty($twig_vars['request'])) {
        $twig_vars['request'] = $request->request->all();
    } else {
        $twig_vars['request'] = array_merge($twig_vars['request'], $request->request->all());
    }
    $twig_vars['request']['pathname'] = $request->getPathInfo();
    if ($request->files->has('file')) {
        $twig_vars['request']['file'] = $request->files->get('file')->getPathname();
    }
    Http::SetSession($twig_vars);
    if (isset($twig_vars['auth']) && $file_root === '/login') {
        Http::Redirect('/');
    }
    if (!isset($twig_vars['auth']) && $file_root !== '/login') {
        Http::Redirect('/login');
    }
    //Merge session and post variables
    try {
        if (isset($_SERVER['HTTP_REFERER'])) {
            //Get routes and match with refer url
            $routes2 = Edu8\Route::getRoutes(__DIR__ . '/../callbacks/');
            $matcher2 = new Routing\Matcher\UrlMatcher($routes2, $context);
            $try = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_PATH);
            $attribs = $matcher2->match($try);
            //Dispatch post() from appropriate file
            if (is_file($attribs['php_file'])) {
                include $attribs['php_file'];
                post($twig_vars);
            }
        }
    } catch (Routing\Exception\ResourceNotFoundException $e) {
    }
    //Dispatch build() from appropriate file
    if (is_file($request->attributes->get('php_file'))) {
        include $request->attributes->get('php_file');
        build($twig_vars);
    }
    Http::SetSession($twig_vars);
    if (strpos($twig_vars['request']['pathname'], 'admin') && $twig_vars['student']['is_professor'] != 1) {
        Http::Redirect('/');
    }
    //Render twig with varables assembled in build()
    $loader = new Twig_Loader_Filesystem(__DIR__ . '/../templates');
    $twig = new Twig_Environment($loader);
    $response = new Symfony\Component\HttpFoundation\Response($twig->render($file_root . $slug . '.html.twig', $twig_vars));
    $response->send();
    unset($twig_vars['message_dlg']);
}
 protected function getResponseService()
 {
     $instance = new \Symfony\Component\HttpFoundation\Response();
     $instance->setCharset('UTF-8');
     return $instance;
 }
Example #20
0
 /**
  * Uses the application to build a response object based on the current state of the request class
  *
  * @return void
  * @author Dan Cox
  */
 public function respond()
 {
     $this->response = $this->application->react();
     // Create the crawler for any html assertions
     $this->crawler = new Crawler($this->response->getContent());
 }
Example #21
0
    return new \Models\ActionModel($app['pdo']);
};
$app['lateness'] = function () use($app) {
    return new \Services\LatenessService($app['userModel'], $app['actionModel'], $app['monolog']);
};
$app->post('/', function (Request $request) use($app) {
    $app['monolog']->addDebug(sprintf('Command from user : %s', $request->get('text')));
    $commandArgs = explode(' ', $request->get('text'));
    $method = $commandArgs[0];
    if (method_exists($app['lateness'], $method)) {
        $text = $app['lateness']->{$method}($commandArgs);
    } else {
        $text = $app['lateness']->help();
    }
    $content = array("text" => $text, "mrkdwn" => true);
    $response = new \Symfony\Component\HttpFoundation\Response();
    $response->headers->set('Content-Type', 'application/json');
    $response->setStatusCode(200);
    $response->setContent(json_encode($content));
    return $response;
});
$app->run();
#878787
/*
  $attachments = new \stdClass;
  $attachments->text = "Partly cloudy today and tomorrow";
  $content = array(
      "text" =>  $app['request']->get('user_name'),
      "attachments" => [$attachments]
  );
*/
Example #22
0
 /**
  * Cleans or flushes output buffers up to target level.
  *
  * Resulting level can be greater than target level if a non-removable buffer has been encountered.
  *
  * @param int  $targetLevel The target output buffering level
  * @param bool $flush       Whether to flush or clean the buffers
  */
 public static function closeOutputBuffers($targetLevel, $flush)
 {
     return Symfony\Component\HttpFoundation\Response::closeOutputBuffers($targetLevel, $flush);
 }
Example #23
0
<?php

require 'vendor/autoload.php';
$response = new \Symfony\Component\HttpFoundation\Response('Oops', 400);
$response->send();
 function download_nuxeo_document()
 {
     $request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
     $validation = \Symfony\Component\Validator\Validation::createValidator();
     $nxsession = $this->getClient();
     if ($request->query->has('nx_doc_id')) {
         $doc_id = $request->query->get('nx_doc_id');
         $violations = $validation->validate($doc_id, array(new \Symfony\Component\Validator\Constraints\Uuid()));
         if (0 === count($violations)) {
             $doc = $nxsession->newRequest("Document.Fetch")->set('params', 'value', $doc_id)->setSchema($schema = 'dublincore,file')->sendRequest()->getDocument(0);
             try {
                 $file_content = $nxsession->newRequest("Blob.Get")->set('input', 'doc:' . $doc_id)->sendRequest();
                 $file_info = new AttributesBag($doc->getProperty('file:content'));
                 $response = new \Symfony\Component\HttpFoundation\Response($file_content);
                 $response->setLastModified(new DateTime($doc->getProperty('dc:modified')));
                 $response->headers->add(array('Content-Disposition' => $response->headers->makeDisposition(\Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT, $doc->getProperty('file:filename')), 'Content-Length' => $file_info->offsetGet('length'), 'Content-Type' => $file_info->offsetGet('mime-type', 'application/octet-stream')));
             } catch (Exception $e) {
                 $response = new \Symfony\Component\HttpFoundation\Response($e->getMessage());
             }
             $response->send();
             exit;
         }
     }
 }
 /**
  * export all local author to csv
  * @param Request $request []
  * @author Nash Lesigon <*****@*****.**>
  * @return Response
  */
 public function exportToCsvAction(Request $request)
 {
     $exportToCsvService = $this->get("buggl_mail.export_local_author_to_csv");
     $result = $exportToCsvService->execute();
     $csvFile = $result['file'];
     $filename = $result['filename'];
     $response = new \Symfony\Component\HttpFoundation\Response();
     $response->setStatusCode(200);
     $response->setContent(file_get_contents($csvFile));
     $response->headers->set('Content-Type', 'application/stream');
     $response->headers->set('Content-length', filesize($csvFile));
     $response->headers->set('Content-Disposition', sprintf('attachment;filename="%s"', $filename));
     $response->send();
     return $response;
 }
Example #26
0
<?php

$SERVER = $app['request']->server->all();
$username = isset($SERVER['PHP_AUTH_USER']) ? $SERVER['PHP_AUTH_USER'] : false;
$password = isset($SERVER['PHP_AUTH_PW']) ? $SERVER['PHP_AUTH_PW'] : false;
if ($username == 'mink-user' && $password == 'mink-password') {
    echo 'is authenticated';
} else {
    $resp = new \Symfony\Component\HttpFoundation\Response();
    $resp->setStatusCode(401);
    $resp->headers->set('WWW-Authenticate', 'Basic realm="Mink Testing Area"');
    echo 'is not authenticated';
}
Example #27
0
 private function sendResponse(Response $response)
 {
     $sendable_response = new \Symfony\Component\HttpFoundation\Response($this->serializer->serialize($response->getData()), $response->getStatusCode(), $response->getHeaders());
     $sendable_response->send();
 }
Example #28
0
File: elgglib.php Project: n8b/VMN
/**
 * Intercepts, logs, and displays uncaught exceptions.
 *
 * To use a viewtype other than failsafe, create the views:
 *  <viewtype>/messages/exceptions/admin_exception
 *  <viewtype>/messages/exceptions/exception
 * See the json viewtype for an example.
 *
 * @warning This function should never be called directly.
 *
 * @see http://www.php.net/set-exception-handler
 *
 * @param Exception $exception The exception being handled
 *
 * @return void
 * @access private
 */
function _elgg_php_exception_handler($exception)
{
    $timestamp = time();
    error_log("Exception #{$timestamp}: {$exception}");
    // Wipe any existing output buffer
    ob_end_clean();
    // make sure the error isn't cached
    header("Cache-Control: no-cache, must-revalidate", true);
    header('Expires: Fri, 05 Feb 1982 00:00:00 -0500', true);
    // we don't want the 'pagesetup', 'system' event to fire
    global $CONFIG;
    $CONFIG->pagesetupdone = true;
    try {
        // allow custom scripts to trigger on exception
        // $CONFIG->exception_include can be set locally in settings.php
        // value should be a system path to a file to include
        if (!empty($CONFIG->exception_include) && is_file($CONFIG->exception_include)) {
            ob_start();
            include $CONFIG->exception_include;
            $exception_output = ob_get_clean();
            // if content is returned from the custom handler we will output
            // that instead of our default failsafe view
            if (!empty($exception_output)) {
                echo $exception_output;
                exit;
            }
        }
        if (elgg_is_xhr()) {
            elgg_set_viewtype('json');
            $response = new \Symfony\Component\HttpFoundation\JsonResponse(null, 500);
        } else {
            elgg_set_viewtype('failsafe');
            $response = new \Symfony\Component\HttpFoundation\Response('', 500);
        }
        if (elgg_is_admin_logged_in()) {
            $body = elgg_view("messages/exceptions/admin_exception", array('object' => $exception, 'ts' => $timestamp));
        } else {
            $body = elgg_view("messages/exceptions/exception", array('object' => $exception, 'ts' => $timestamp));
        }
        $response->setContent(elgg_view_page(elgg_echo('exception:title'), $body));
        $response->send();
    } catch (Exception $e) {
        $timestamp = time();
        $message = $e->getMessage();
        echo "Fatal error in exception handler. Check log for Exception #{$timestamp}";
        error_log("Exception #{$timestamp} : fatal error in exception handler : {$message}");
    }
}
Example #29
0
 /**
  * setup i18n URI and detect the language in URI.
  */
 public function i18nUri()
 {
     if ($this->Profiler != null) {
         $this->Profiler->Console->timeload('Initialize the language locale uri.', __FILE__, __LINE__);
         $this->Profiler->Console->memoryUsage('Initialize the language locale uri.', __FILE__, __LINE__ - 1);
     }
     $configdb = new \System\Core\Models\ConfigDb($this->Silexapp['Db']);
     if ($configdb->getConfigValue('site_lang_method', 'uri') == 'cookie') {
         // if detect language method is using cookie.
         $language_cookie_name = $_SERVER['HTTP_HOST'] . '_CMS_LANGUAGE_LOCALE_URI';
         $request = new \Symfony\Component\HttpFoundation\Request($_GET, $_POST, [], $_COOKIE);
         if ($request->cookies->has($language_cookie_name)) {
             $this->language_locale_uri = $request->cookies->get($language_cookie_name);
         } else {
             $LangDb = new \System\Core\Models\LanguagesDb($this->Silexapp['Db']);
             $this->language_locale_uri = $LangDb->getDefaultLanguageUri();
             $cookie = new \Symfony\Component\HttpFoundation\Cookie($language_cookie_name, $LangDb->getDefaultLanguageUri(), time() + 60 * 60 * 24 * 30, '/', null, isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? true : false);
             $response = new \Symfony\Component\HttpFoundation\Response();
             $response->headers->setCookie($cookie);
             $response->send();
         }
         unset($configdb, $cookie, $LangDb, $language_cookie_name, $request, $response);
     } else {
         // if detect language method is using URI.
         $uri = new \System\Libraries\Uri();
         $uris_arr = $uri->getUriSegments(true);
         // get language locale uri from REQUEST_URI. this does not check the exists language yet.
         if (isset($uris_arr[1])) {
             $language_locale_uri = $uris_arr[1];
         } else {
             $language_locale_uri = $uris_arr[count($uris_arr) - 1];
         }
         // check that language locale uri is in language list or not. non-match or empty language locale uri will be use default language locale uri.
         $LangDb = new \System\Core\Models\LanguagesDb($this->Silexapp['Db']);
         $this->language_locale_uri = $LangDb->getLanguageUri($language_locale_uri);
         // check and detect language redirect.
         if ($this->language_locale_uri != $language_locale_uri) {
             // if checked language locale URI is not match the detected one. example: th != page, en-US != fr-FR where page, or fr-FR is not exists in language db.
             // set language locale uri to global variable $_SERVER.
             $_SERVER['CMS_LANGUAGE_LOCALE_URI'] = $this->language_locale_uri;
             if ($configdb->getConfigValue('site_lang_uri_default_visible', '1') == '1') {
                 // if settings was set to force show language URI, redirect to new url with language prefixed.
                 $uris_arr[0] = $this->language_locale_uri;
                 $new_uri = implode('/', $uris_arr);
                 unset($configdb, $LangDb, $language_locale_uri, $uris_arr);
                 // redirect from EX. http://domain.tld/myapp/index.php to http://domain.tld/myapp/index.php/th, http://domain.tld/myapp/index.php/page/subpage -> http://domain.tld/index.php/th/page/subpage
                 header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
                 header('Cache-Control: post-check=0, pre-check=0', false);
                 header('Pragma: no-cache');
                 header('HTTP/1.1 301 Moved Permanently');
                 header('Location: ' . $uri->createUrl($new_uri, 'auto', false));
                 exit;
             }
         } else {
             // if checked language locale URI is match detected one.
             // set language locale uri to global variable $_SERVER.
             $_SERVER['CMS_LANGUAGE_LOCALE_URI'] = $language_locale_uri;
             if ($configdb->getConfigValue('site_lang_uri_default_visible', '1') == '0') {
                 // if default language is set to not visible, redirect to the URL where it has no language locale URI.
                 $default_language_locale_uri = $LangDb->getDefaultLanguageUri();
                 if ($language_locale_uri == $default_language_locale_uri) {
                     // if detected language locale uri is default. example: default is 'th'; url is http://domain.tld/myapp/index.php/th/page/subpage; this language locale uri is default language!
                     unset($_SERVER['CMS_LANGUAGE_LOCALE_URI']);
                     $uris_arr = $uri->getUriSegments(true);
                     if (isset($uris_arr[1]) && $uris_arr[1] != null) {
                         unset($uris_arr[1]);
                     }
                     $new_uri = implode('/', $uris_arr);
                     unset($configdb, $LangDb, $language_locale_uri, $uris_arr);
                     // redirect from IE. http://domain.tld/myapp/index.php/th to http://domain.tld/myapp/index.php where th is default language.
                     header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
                     header('Cache-Control: post-check=0, pre-check=0', false);
                     header('Pragma: no-cache');
                     header('HTTP/1.1 301 Moved Permanently');
                     header('Location: ' . $uri->createUrl($new_uri, 'auto', false));
                     exit;
                 }
             }
         }
         // endif check and detect language redirect.
         // re-setting request uri key. --------------------------------------------------------------
         // in case that the url contain language locale uri. for example: uri is http://domain.tld/myapp/index.php/th/page/subpage; the original REQUEST_URI will be /myapp/index.php/th/page/subpage
         // with this re-setting request uri key, the modified REQUEST_URI will be /myapp/index.php/page/subpage. so the routes can works properly.
         $index_file = $uri->getIndexFile();
         $uris_arr = $uri->getUriSegments(true);
         if (isset($uris_arr[1]) && $uris_arr[1] == $this->language_locale_uri) {
             unset($uris_arr[1]);
         }
         $uri_string = implode('/', $uris_arr);
         $_SERVER['REQUEST_URI'] = $uri->getBaseUri() . ($index_file != null ? '/' . $index_file : '') . $uri_string;
         unset($configdb, $default_language_locale_uri, $index_file, $language_locale_uri, $uri, $uris_arr, $uri_string);
     }
     // endif; site_lang_method
     // set share variable via Silex\Application.
     $this->Silexapp['language_locale_uri'] = $this->language_locale_uri;
     $this->Silexapp->register(new \Silex\Provider\TranslationServiceProvider(), ['locale' => $LangDb->getLanguageData($this->language_locale_uri), 'locale_fallbacks' => [$LangDb->getLanguageData('')]]);
     putenv('LC_ALL=' . $this->language_locale_uri);
     setlocale(LC_ALL, explode(',', str_replace(', ', ',', $LangDb->getLanguageData($this->language_locale_uri))));
     // start to working with php-gettext.
     $this->Silexapp['Language'] = $this->Silexapp->share(function () {
         return new \System\Libraries\Language($this->language_locale_uri);
     });
     unset($LangDb);
     if ($this->Profiler != null) {
         $this->Profiler->Console->timeload('Finished the language locale uri.', __FILE__, __LINE__);
         $this->Profiler->Console->memoryUsage('Finished the language locale uri.', __FILE__, __LINE__ - 1);
     }
 }
Example #30
-20
 /**
  * @Route("/dodaj_zdarzenie", name="dodaj_zdarzenie", options={"expose"=true})
  * @param Request $request
  * @return Response
  */
 public function dodajZdarzenieAction(Request $request)
 {
     $time_zone = new \DateTimeZone('UTC');
     $time_zone->getName();
     $dane = new Zdarzenia();
     $start = new \DateTime($request->get('start'));
     //$start->createFromFormat('ATOM', $request->get('start'),$time_zone);
     $end = new \DateTime($request->get('end'));
     //$end->createFromFormat('ATOM', $request->get('end'),$time_zone);
     $dane->setTitle($request->get('title'));
     $dane->setDescription($request->get('description'));
     $dane->setLocation($request->get('location'));
     $dane->setContact($request->get('contact'));
     $dane->setUrl($request->get('url'));
     $dane->setStart($start);
     $dane->setEnd($end);
     $dane->setAlldayevent($request->get('alldayevent'));
     $em = $this->getDoctrine()->getManager();
     $em->persist($dane);
     $em->flush();
     $response = new \Symfony\Component\HttpFoundation\Response();
     $response->headers->set('Content-Type', 'application/json');
     $response->setContent(json_encode($dane));
     return $response;
 }