setStatusCode() public method

Sets the response status code.
public setStatusCode ( integer $code, mixed $text = null ) : Response
$code integer HTTP status code
$text mixed HTTP status text If the status text is null it will be automatically populated for the known status codes and left empty otherwise.
return Response
Exemplo n.º 1
0
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     if ('prod' == $this->kernel->getEnvironment()) {
         // exception object
         $exception = $event->getException();
         $navService = $this->container->get('ssone.cms.navigation');
         $logger = $this->container->get('logger');
         $logger->error($exception->getMessage());
         $host = $navService->host;
         // new Response object
         $response = new Response();
         // set response content
         $response->setContent($this->templating->render('SSoneCMSThemeBundle:' . $navService->domainTemplate, array('navigation' => $navService->templateNavigationMap, 'pageClass' => "notfound404", 'pageTitle' => "Not found 404", 'metaDescription' => $navService->metaDescription, 'content' => array("attributes" => array("template" => "404/" . $host . ".html.twig")), 'modules' => "", 'multiLanguageLinks' => "", 'exception' => $exception)));
         // HttpExceptionInterface is a special type of exception
         // that holds status code and header details
         if ($exception instanceof HttpExceptionInterface) {
             $response->setStatusCode($exception->getStatusCode());
             $response->headers->replace($exception->getHeaders());
         } else {
             $response->setStatusCode(500);
         }
         // set the new $response object to the $event
         $event->setResponse($response);
     }
 }
 /**
  * @View()
  */
 public function putCategoryAction($id, Request $request)
 {
     $this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
     $em = $this->getDoctrine()->getManager();
     $response = new Response();
     $data = $request->request->all();
     if ($id === "null") {
         $category = new Category();
     } else {
         $category = $em->getRepository('AppBundle\\Entity\\Asset\\Category')->find($id);
     }
     $form = $this->createForm(CategoryType::class, $category, ['allow_extra_fields' => true]);
     try {
         $form->submit($data);
         if ($form->isValid()) {
             $category = $form->getData();
             $em->persist($category);
             $em->flush();
             $response->setStatusCode($request->getMethod() === 'POST' ? 201 : 204);
             $response->headers->set('Location', $this->generateUrl('app_admin_api_categories_get_category', array('id' => $category->getId()), true));
         } else {
             return $form;
         }
     } catch (Exception $e) {
         $response->setStatusCode(400);
         $response->setContent(json_encode(['message' => 'errors', 'errors' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
     }
     return $response;
 }
Exemplo n.º 3
0
    /**
     * Handle invalidation, including Http PURGE requests.
     * All non-allowed PURGE requests will receive an HTTP 405
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param boolean $catch
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function invalidate( Request $request, $catch = false )
    {
        if ( $request->getMethod() !== 'PURGE' && $request->getMethod() !== 'BAN' )
        {
            return parent::invalidate( $request, $catch );
        }

        // Reject all non-authorized clients
        if ( !$this->isInternalRequestAllowed( $request ) )
        {
            return new Response( '', 405 );
        }

        $response = new Response();
        $store = $this->getStore();
        if ( $store instanceof RequestAwarePurger )
        {
            $result = $store->purgeByRequest( $request );
        }
        else
        {
            $result = $store->purge( $request->getUri() );
        }

        if ( $result === true )
        {
            $response->setStatusCode( 200, 'Purged' );
        }
        else
        {
            $response->setStatusCode( 404, 'Not purged' );
        }

        return $response;
    }
Exemplo n.º 4
0
 /**
  * Handle a request for a file
  *
  * @param Request $request HTTP request
  * @return Response
  */
 public function getResponse(Request $request)
 {
     $response = new Response();
     $response->prepare($request);
     $path = implode('/', $request->getUrlSegments());
     if (!preg_match('~serve-file/e(\\d+)/l(\\d+)/d([ia])/c([01])/([a-zA-Z0-9\\-_]+)/(.*)$~', $path, $m)) {
         return $response->setStatusCode(400)->setContent('Malformatted request URL');
     }
     list(, $expires, $last_updated, $disposition, $use_cookie, $mac, $path_from_dataroot) = $m;
     if ($expires && $expires < time()) {
         return $response->setStatusCode(403)->setContent('URL has expired');
     }
     $hmac_data = array('expires' => (int) $expires, 'last_updated' => (int) $last_updated, 'disposition' => $disposition, 'path' => $path_from_dataroot, 'use_cookie' => (int) $use_cookie);
     if ((bool) $use_cookie) {
         $hmac_data['cookie'] = $this->getCookieValue($request);
     }
     ksort($hmac_data);
     $hmac = $this->crypto->getHmac($hmac_data);
     if (!$hmac->matchesToken($mac)) {
         return $response->setStatusCode(403)->setContent('HMAC mistmatch');
     }
     $dataroot = $this->config->getDataPath();
     $filenameonfilestore = "{$dataroot}{$path_from_dataroot}";
     if (!is_readable($filenameonfilestore)) {
         return $response->setStatusCode(404)->setContent('File not found');
     }
     $actual_last_updated = filemtime($filenameonfilestore);
     if ($actual_last_updated != $last_updated) {
         return $response->setStatusCode(403)->setContent('URL has expired');
     }
     $if_none_match = $request->headers->get('if_none_match');
     if (!empty($if_none_match)) {
         // strip mod_deflate suffixes
         $request->headers->set('if_none_match', str_replace('-gzip', '', $if_none_match));
     }
     $etag = '"' . $actual_last_updated . '"';
     $response->setPublic()->setEtag($etag);
     if ($response->isNotModified($request)) {
         return $response;
     }
     $public = $use_cookie ? false : true;
     $content_disposition = $disposition == 'i' ? 'inline' : 'attachment';
     $headers = ['Content-Type' => (new MimeTypeDetector())->getType($filenameonfilestore)];
     $response = new BinaryFileResponse($filenameonfilestore, 200, $headers, $public, $content_disposition);
     $sendfile_type = $this->config->getVolatile('X-Sendfile-Type');
     if ($sendfile_type) {
         $request->headers->set('X-Sendfile-Type', $sendfile_type);
         $mapping = (string) $this->config->getVolatile('X-Accel-Mapping');
         $request->headers->set('X-Accel-Mapping', $mapping);
         $response->trustXSendfileTypeHeader();
     }
     $response->prepare($request);
     if (empty($expires)) {
         $expires = strtotime('+1 year');
     }
     $expires_dt = (new DateTime())->setTimestamp($expires);
     $response->setExpires($expires_dt);
     $response->setEtag($etag);
     return $response;
 }
Exemplo n.º 5
0
 /**
  *  RPC url action
  *
  * @param $bundle
  * @param $service
  * @param $method
  * @param Request $request
  *
  * @Route("/{bundle}/{service}/{method}" , defaults={"_format": "json"})
  * @Method("POST")
  *
  * @return Response
  */
 public function rpcAction($bundle, $service, $method, Request $request)
 {
     $response = new Response();
     $translator = $this->get('translator');
     try {
         $prefix = 'Hazu.Service';
         $serviceObject = $this->get("{$prefix}.{$bundle}.{$service}");
         if (true === method_exists($serviceObject, $method)) {
             $params = json_decode($request->getContent(), true);
             if (null === $params) {
                 throw new \Exception('$params não é um JSON valido');
             }
             $rService = $serviceObject->{$method}($params);
         } else {
             throw new \Exception($translator->trans('Metodo não encontrado'));
         }
     } catch (ServiceNotFoundException $e) {
         $rService = new HazuException($e->getMessage());
         $response->setStatusCode(500);
     } catch (\Exception $e) {
         $rService = new HazuException($e->getMessage());
         $response->setStatusCode(500);
     } finally {
         $serializer = SerializerBuilder::create()->build();
         $rJson = $serializer->serialize($rService, 'json', SerializationContext::create()->enableMaxDepthChecks());
         $response->headers->set('x-hazu-type', gettype($rService));
         if (gettype($rService) == 'object') {
             $response->headers->set('x-hazu-class', get_class($rService));
         }
         $response->setContent($rJson);
     }
     return $response;
 }
Exemplo n.º 6
0
 /**
  * Handle a request for a file
  *
  * @param Request $request HTTP request
  * @return Response
  */
 public function getResponse($request)
 {
     $response = new Response();
     $response->prepare($request);
     $path = implode('/', $request->getUrlSegments());
     if (!preg_match('~download-file/g(\\d+)$~', $path, $m)) {
         return $response->setStatusCode(400)->setContent('Malformatted request URL');
     }
     $this->application->start();
     $guid = (int) $m[1];
     $file = get_entity($guid);
     if (!$file instanceof ElggFile) {
         return $response->setStatusCode(404)->setContent("File with guid {$guid} does not exist");
     }
     $filenameonfilestore = $file->getFilenameOnFilestore();
     if (!is_readable($filenameonfilestore)) {
         return $response->setStatusCode(404)->setContent('File not found');
     }
     $last_updated = filemtime($filenameonfilestore);
     $etag = '"' . $last_updated . '"';
     $response->setPublic()->setEtag($etag);
     if ($response->isNotModified($request)) {
         return $response;
     }
     $response = new BinaryFileResponse($filenameonfilestore, 200, array(), false, 'attachment');
     $response->prepare($request);
     $expires = strtotime('+1 year');
     $expires_dt = (new DateTime())->setTimestamp($expires);
     $response->setExpires($expires_dt);
     $response->setEtag($etag);
     return $response;
 }
Exemplo n.º 7
0
 /**
  * Sets the given status code in the corresponding header.
  *
  * Note that headers are generally not overwritten!
  *
  * @param int $statusCode
  */
 public function setStatus($statusCode)
 {
     if ($this->statusCode === null) {
         $this->statusCode = $statusCode;
         $this->response->setStatusCode($statusCode);
     }
 }
Exemplo n.º 8
0
 public function show()
 {
     $assetic = $this->getServices()->get($this->getServices()->getProperty('asseticServiceName', 'assetic'));
     $response = new Response();
     $response->setExpires(new \DateTime());
     if (empty($this->asset) || strpos($this->asset, '/') === false) {
         $response->setStatusCode(400);
         return $response;
     }
     list(, $formulaName, ) = explode('/', $this->asset);
     // asset not found
     if (empty($formulaName) || !$assetic->getAssetManager()->has($formulaName)) {
         $response->setStatusCode(404);
         return $response;
     }
     $formula = $assetic->getAssetManager()->getFormula($formulaName);
     if ($formula[0] instanceof AssetInterface) {
         $asset = $formula[0];
     } else {
         $asset = $assetic->getFactory()->createAsset($formula[0], $formula[1], $formula[2]);
     }
     if (null !== ($lastModified = $asset->getLastModified())) {
         $date = new \DateTime();
         $date->setTimestamp($lastModified);
         $response->setLastModified($date);
     }
     $formula['last_modified'] = $lastModified;
     $response->setETag(md5($asset->getContent()));
     $this->defineContentType($response);
     if ($response->isNotModified($this->getContext()->getRequest())) {
         return $response;
     }
     $response->setContent($this->cacheAsset($asset)->dump());
     return $response;
 }
Exemplo n.º 9
0
 public function createAction()
 {
     $response = new Response();
     $response->headers->set('Content-type', 'application/json');
     if ($this->get('session')->get('user') === null) {
         $response->setStatusCode(401);
         $response->setContent(json_encode(array('response' => Response::$statusTexts[401])));
         return $response;
     }
     $data = $this->getRequest()->request->all();
     if (empty($data)) {
         $data = json_decode($this->getRequest()->getContent(), true);
     }
     $this->handleUpload($data);
     $userRepo = $this->getDoctrine()->getRepository('Emicro\\Bundles\\CoreBundle\\Entity\\User');
     $canvasRepo = $this->getDoctrine()->getRepository('Emicro\\Bundles\\CoreBundle\\Entity\\Canvas');
     $user = $this->get('session')->get('user');
     $canvasRepo->setUser($userRepo->find($user->getId()));
     if (isset($data['id'])) {
         $canvas = $canvasRepo->update($data, $data['id']);
         $response->setStatusCode(200);
     } else {
         $canvas = $canvasRepo->insert($data);
         $response->setStatusCode(201);
     }
     $serializer = new JsonSerializer();
     $response->setContent($serializer->serialize($canvas));
     return $response;
 }
Exemplo n.º 10
0
 /**
  * Chunk the request into parts as
  * desired by the request range header.
  *
  * @param Response      $response
  * @param FileInterface $file
  */
 protected function chunk(Response $response, FileInterface $file)
 {
     $size = $chunkStart = $file->getSize();
     $end = $chunkEnd = $size;
     $response->headers->set('Content-length', $size);
     $response->headers->set('Content-Range', "bytes 0-{$end}/{$size}");
     if (!($range = array_get($_SERVER, 'HTTP_RANGE'))) {
         return;
     }
     list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
     if (strpos($range, ',') !== false) {
         $response->setStatusCode(416, 'Requested Range Not Satisfiable');
         $response->headers->set('Content-Range', "bytes 0-{$end}/{$size}");
     }
     if ($range == '-') {
         $chunkStart = $size - substr($range, 1);
     } else {
         $range = explode('-', $range);
         $chunkStart = $range[0];
         $chunkEnd = isset($range[1]) && is_numeric($range[1]) ? $range[1] : $size;
     }
     $chunkEnd = $chunkEnd > $end ? $end : $chunkEnd;
     if ($chunkStart > $chunkEnd || $chunkStart > $size || $chunkEnd >= $size) {
         $response->setStatusCode(416, 'Requested Range Not Satisfiable');
         $response->headers->set('Content-Range', "bytes 0-{$end}/{$size}");
     }
 }
 /**
  * Renders the defined {@see ExceptionListener::$errorTemplate}, which has been defined via YAML
  * settings, on exception.
  *
  * Note, that the function is only called, if the *debug value* is set or *error pages* are
  * enabled via Parameter *stvd.error_page.enabled*.
  *
  * @param GetResponseForExceptionEvent $event
  */
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     // don't do anything if it's not the master request
     if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
         return;
     }
     // You get the exception object from the received event
     $exception = $event->getException();
     // Customize your response object to display the exception details
     $response = new Response();
     // set response content
     $response->setContent($this->templating->render($this->errorTemplate, array('exception' => $exception)));
     // HttpExceptionInterface is a special type of exception that
     // holds status code and header details
     if ($exception instanceof HttpExceptionInterface) {
         $response->setStatusCode($exception->getStatusCode());
         $response->headers->replace($exception->getHeaders());
     } else {
         // If the exception's status code is not valid, set it to *500*. If it's valid, the
         // status code will be transferred to the response.
         if ($exception->getCode()) {
             $response->setStatusCode($exception->getCode());
         } else {
             $response->setStatusCode(500);
         }
     }
     // Send the modified response object to the event
     $event->setResponse($response);
 }
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     // You get the exception object from the received event
     $exception = $event->getException();
     if (!$exception instanceof ValidationException) {
         return;
     }
     // Customize your response object to display the exception details
     $response = new Response();
     $validationErrors = $exception->getErrorList();
     $errorArray = array();
     foreach ($validationErrors as $error) {
         $errorArray[$error->getPropertyPath()] = $error->getMessage();
     }
     //TODO permettre de paramétrer le format de renvoi des erreurs
     $errorMessage = json_encode($errorArray);
     //$this->serializer->serialize($validationErrors, 'json');
     $response->setContent($errorMessage);
     // HttpExceptionInterface is a special type of exception that
     // holds status code and header details
     if ($exception instanceof HttpExceptionInterface) {
         $response->setStatusCode($exception->getStatusCode());
         $response->headers->replace($exception->getHeaders());
     } else {
         $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
     }
     // Send the modified response object to the event
     $event->setResponse($response);
 }
Exemplo n.º 13
0
 public function saveImagenAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $response = new Response();
     try {
         $image = $request->get("image");
         if (!$image) {
             $response->setContent(json_decode(array("error" => ">No hay imagen seleccionada.")));
             $response->setStatusCode(Response::HTTP_NOT_FOUND);
             return $response;
         }
         $user = $this->getUser();
         $user->setPicture($image);
         $em->persist($user);
         $em->flush();
         $this->get('session')->getFlashBag()->add('success', 'Se actualizo la imagen de perfil');
         $response->setContent(json_encode(array("success" => "Imagen actualizada.")));
         $response->setStatusCode(Response::HTTP_OK);
         return $response;
     } catch (\Exception $exc) {
         $response->setContent(json_encode(array("error" => "Error al intentar guardar la imagen, intente con una mas pequeña o acerque mas la imagen")));
         $response->setStatusCode(Response::HTTP_NOT_FOUND);
         return $response;
     }
 }
 /**
  * Returns Response in JSON Format, given value has to be some encodeable Stuff (most likely an array ;) )
  * @param $value
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function handleResponse($value)
 {
     $this->throwNotFound($value);
     $this->response->setStatusCode(200);
     $this->response->setContent(json_encode($value));
     $this->response->headers->set('Content-Type', 'application/json');
     return $this->response;
 }
 public function testFullRedirectNotProducedInDevEnv()
 {
     $listener = $this->getListener(true);
     $this->response->headers->add(array('location' => self::TEST_URL));
     $this->response->setStatusCode(503);
     $this->templating->expects($this->never())->method('renderResponse');
     $this->event->expects($this->once())->method('setResponse');
     $listener->onResponse($this->event);
 }
Exemplo n.º 16
0
 public function show($params)
 {
     $slug = $params['slug'];
     try {
         $data['content'] = $this->pageReader->readBySlug($slug);
     } catch (PageNotFoundException $e) {
         $this->response->setStatusCode(404);
         return $this->response->setContent('404 - Page not found');
     }
     $html = $this->twig->render('page.twig', $data);
     return $this->response->setContent($html);
 }
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     $excp = $event->getException();
     $response = new Response();
     $response->setContent('Oops! Something has gone wrong...');
     if ($excp instanceof HttpExceptionInterface) {
         $response->setStatusCode($excp->getStatusCode());
         $response->headers->replace($excp->getHeaders());
     } else {
         $response->setStatusCode(500);
     }
     $event->setResponse($response);
 }
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     $exception = $event->getException();
     $message = 'Error: ' . $exception->getMessage() . ', code: ' . $exception->getCode();
     $response = new Response();
     $response->setContent($message);
     if ($exception instanceof HttpExceptionInterface) {
         $response->setStatusCode($exception->getStatusCode());
         $response->headers->replace($exception->getHeaders());
     } else {
         $response->setStatusCode(500);
     }
 }
Exemplo n.º 19
0
 protected function sendResponse($payload = NULL)
 {
     $this->res->setExpiration(FALSE);
     if (is_null($payload)) {
         $this->res->setStatusCode(204);
     } else {
         $this->res->setCharset('utf8');
         $this->res->headers->set('Content-Type', 'application/json');
         $content = json_encode($payload, JSON_PRETTY_PRINT);
         $this->res->setContent($content);
     }
     $this->res->send();
 }
Exemplo n.º 20
0
 /**
  * {@inheritDoc}
  */
 protected function invalidate(Request $request, $catch = false)
 {
     if ('PURGE' !== $request->getMethod()) {
         return parent::invalidate($request, $catch);
     }
     $response = new Response();
     if ($this->getStore()->purge($request->getUri())) {
         $response->setStatusCode(200, 'Purged');
     } else {
         $response->setStatusCode(200, 'Not purged');
     }
     return $response;
 }
Exemplo n.º 21
0
 /**
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function getResponse()
 {
     $response = new Response();
     try {
         $response->headers->set('Content-Type', 'application/json');
         $response->setContent($this->run());
         $response->setStatusCode(200);
     } catch (Exception $e) {
         $response->setContent($e->getMessage());
         $response->setStatusCode($e->getCode());
     }
     return $response;
 }
Exemplo n.º 22
0
 /**
  * @param Request $request
  * @param $id
  * @return Response
  */
 public function removeAction(Request $request, $id)
 {
     $userManager = $this->get("fos_user.user_manager");
     $user = $userManager->findUserBy(array("id" => $id));
     $response = new Response();
     if ($user != null) {
         $userManager->deleteUser($user);
         $response->setStatusCode(200);
     } else {
         $response->setStatusCode(404);
     }
     return $response;
 }
 /**
  * Manage kernel exception
  * @param GetResponseForExceptionEvent $event
  *
  * @return GetResponseForExceptionEvent
  */
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     $exception = $event->getException();
     $response = new Response();
     if ($exception instanceof HttpExceptionInterface) {
         $response->setStatusCode($exception->getStatusCode());
         $response->headers->replace($exception->getHeaders());
     } else {
         $response->setStatusCode(500);
     }
     $content = $this->templating->render('PimEnrichBundle:Error:base.html.twig', ['exception' => $exception, 'status_code' => $response->getStatusCode()]);
     $response->setContent($content);
     $event->setResponse($response);
 }
Exemplo n.º 24
0
 /**
  * @Route("/", name="hello_homepage")
  * @Method({"GET"})
  */
 public function indexAction(Request $request)
 {
     $name = $request->query->get('name', null);
     $response = new Response();
     if (null !== $name) {
         $response->setContent(sprintf('<h1>Bonjour %s</h1>', $name));
         $response->setStatusCode(200);
     } else {
         $response->setContent('<h1>Page non trouvée</h1>');
         $response->setStatusCode(404);
     }
     $response->headers->set('Content-Type', 'text/html');
     return $response;
 }
Exemplo n.º 25
0
 /**
  * @param Request $request
  * @param Response $response
  * @param string $resource
  * @param \Closure $callback
  * @return Response
  */
 public function handle(Request $request, Response $response, $resource, $callback)
 {
     $accept = $this->negotiator->getBest($request->headers->get('Accept'));
     $format = $this->negotiator->getFormat($accept->getValue());
     if ($format == 'html') {
         $format = 'json';
     }
     $response->headers->set('Content-Type', $accept->getValue());
     try {
         $manager = $this->managerFactory->create($resource);
         $context = new DeserializationContext();
         $context->enableMaxDepthChecks();
         $object = null;
         $content = $request->getContent();
         if (!empty($content)) {
             $object = $this->serializer->create($request->isMethod('patch') ? 'doctrine' : 'default')->deserialize($request->getContent(), $manager->getClass(), $format, $context);
         }
         $data = $this->envelopeFactory->create($callback($manager, $object))->export();
     } catch (InvalidException $e) {
         $response->setStatusCode(400);
         $data = array("code" => 400, "message" => $e->getMessage(), "errors" => $e->getErrors());
     } catch (NotFoundException $e) {
         $response->setStatusCode(404);
         $data = array("code" => 404, "message" => $e->getMessage());
     } catch (UnsupportedMethodException $e) {
         $response->setStatusCode(405);
         $data = array("code" => 405, "message" => $e->getMessage());
     } catch (HttpException $e) {
         $response->setStatusCode($e->getStatusCode());
         $data = array("code" => $e->getStatusCode(), "message" => $e->getMessage());
     } catch (\Exception $e) {
         $this->logger->critical($e);
         $response->setStatusCode(500);
         $data = array("code" => 500, "message" => $e->getMessage());
     }
     $groups = array('Default', 'lemon_rest', 'lemon_rest_' . $resource, 'lemon_rest_' . $resource . '_' . strtolower($request->getMethod()));
     if (is_object($data)) {
         $groups[] = 'lemon_rest_' . $resource . '_view';
     } else {
         $groups[] = 'lemon_rest_' . $resource . '_list';
     }
     $context = SerializationContext::create()->enableMaxDepthChecks();
     $context->setGroups($groups);
     if ($accept->hasParameter('version')) {
         $context->setVersion($accept->getParameter('version'));
     }
     $output = $this->serializer->create('default')->serialize($data, $format, $context);
     $response->setContent($output);
     return $response;
 }
Exemplo n.º 26
0
 /**
  * Handle a request for a file
  *
  * @param Request $request HTTP request
  * @return Response
  */
 public function getResponse($request)
 {
     $response = new Response();
     $response->prepare($request);
     $path = implode('/', $request->getUrlSegments());
     if (!preg_match('~serve-file/e(\\d+)/l(\\d+)/d([ia])/c([01])/([a-zA-Z0-9\\-_]+)/(.*)$~', $path, $m)) {
         return $response->setStatusCode(400)->setContent('Malformatted request URL');
     }
     list(, $expires, $last_updated, $disposition, $use_cookie, $mac, $path_from_dataroot) = $m;
     if ($expires && $expires < time()) {
         return $response->setStatusCode(403)->setContent('URL has expired');
     }
     $etag = '"' . $last_updated . '"';
     $response->setPublic()->setEtag($etag);
     if ($response->isNotModified($request)) {
         return $response;
     }
     // @todo: change to minimal boot without plugins
     $this->application->bootCore();
     $hmac_data = array('expires' => (int) $expires, 'last_updated' => (int) $last_updated, 'disposition' => $disposition, 'path' => $path_from_dataroot, 'use_cookie' => (int) $use_cookie);
     if ((bool) $use_cookie) {
         $hmac_data['cookie'] = _elgg_services()->session->getId();
     }
     ksort($hmac_data);
     $hmac = elgg_build_hmac($hmac_data);
     if (!$hmac->matchesToken($mac)) {
         return $response->setStatusCode(403)->setContent('HMAC mistmatch');
     }
     $dataroot = _elgg_services()->config->getDataPath();
     $filenameonfilestore = "{$dataroot}{$path_from_dataroot}";
     if (!is_readable($filenameonfilestore)) {
         return $response->setStatusCode(404)->setContent('File not found');
     }
     $actual_last_updated = filemtime($filenameonfilestore);
     if ($actual_last_updated != $last_updated) {
         return $response->setStatusCode(403)->setContent('URL has expired');
     }
     $public = $use_cookie ? false : true;
     $content_disposition = $disposition == 'i' ? 'inline' : 'attachment';
     $response = new BinaryFileResponse($filenameonfilestore, 200, array(), $public, $content_disposition);
     $response->prepare($request);
     if (empty($expires)) {
         $expires = strtotime('+1 year');
     }
     $expires_dt = (new DateTime())->setTimestamp($expires);
     $response->setExpires($expires_dt);
     $response->setEtag($etag);
     return $response;
 }
Exemplo n.º 27
0
 /**
  * Displays an Error 503 (Service unavailable) page.
  *
  * @return \Symfony\Component\HttpFoundation\Response
  *   Returns the response with a special header.
  */
 public function updateError()
 {
     $response = new Response();
     $response->setStatusCode(503);
     $response->headers->set('Status', '503 Service unavailable');
     return $response;
 }
Exemplo n.º 28
0
 /**
  * Checks if a node's type requires a redirect.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The event to process.
  */
 public function purlCheckNodeContext(GetResponseEvent $event, $eventName, EventDispatcherInterface $dispatcher_interface)
 {
     $route_options = $this->routeMatch->getRouteObject()->getOptions();
     $isAdminRoute = array_key_exists('_admin_route', $route_options) && $route_options['_admin_route'];
     if (!$isAdminRoute && ($matched = $this->matchedModifiers->getMatched() && ($entity = $this->routeMatch->getParameter('node')))) {
         $node_type = $this->entityStorage->load($entity->bundle());
         $purl_settings = $node_type->getThirdPartySettings('purl');
         if (!isset($purl_settings['keep_context']) || !$purl_settings['keep_context']) {
             $url = \Drupal\Core\Url::fromRoute($this->routeMatch->getRouteName(), $this->routeMatch->getRawParameters()->all(), ['host' => Settings::get('purl_base_domain'), 'absolute' => TRUE]);
             try {
                 $redirect_response = new TrustedRedirectResponse($url->toString());
                 $redirect_response->getCacheableMetadata()->setCacheMaxAge(0);
                 $modifiers = $event->getRequest()->attributes->get('purl.matched_modifiers', []);
                 $new_event = new ExitedContextEvent($event->getRequest(), $redirect_response, $this->routeMatch, $modifiers);
                 $dispatcher_interface->dispatch(PurlEvents::EXITED_CONTEXT, $new_event);
                 $event->setResponse($new_event->getResponse());
                 return;
             } catch (RedirectLoopException $e) {
                 \Drupal::logger('redirect')->warning($e->getMessage());
                 $response = new Response();
                 $response->setStatusCode(503);
                 $response->setContent('Service unavailable');
                 $event->setResponse($response);
                 return;
             }
         }
     }
 }
 /**
  * @param Request $request
  *
  * @return Response
  */
 public function loadAction(Request $request)
 {
     $startDate = new \DateTime($request->get('start'));
     $endDate = new \DateTime($request->get('end'));
     $response = new Response();
     $response->headers->set('Content-Type', 'application/json');
     try {
         $content = $this->get('anca_rebeca_full_calendar.service.calendar')->getData($startDate, $endDate);
         $response->setContent($content);
         $response->setStatusCode(Response::HTTP_OK);
     } catch (\Exception $exception) {
         $response->setContent([]);
         $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
     }
     return $response;
 }
 /**
  * Generates a test feed and simulates last-modified and etags.
  *
  * @param $use_last_modified
  *   Set TRUE to send a last modified header.
  * @param $use_etag
  *   Set TRUE to send an etag.
  * @param Request $request
  *   Information about the current HTTP request.
  *
  * @return \Symfony\Component\HttpFoundation\Response
  *   A feed that forces cache validation.
  */
 public function testFeed($use_last_modified, $use_etag, Request $request)
 {
     $response = new Response();
     $last_modified = strtotime('Sun, 19 Nov 1978 05:00:00 GMT');
     $etag = Crypt::hashBase64($last_modified);
     $if_modified_since = strtotime($request->server->get('HTTP_IF_MODIFIED_SINCE'));
     $if_none_match = stripslashes($request->server->get('HTTP_IF_NONE_MATCH'));
     // Send appropriate response. We respond with a 304 not modified on either
     // etag or on last modified.
     if ($use_last_modified) {
         $response->headers->set('Last-Modified', gmdate(DateTimePlus::RFC7231, $last_modified));
     }
     if ($use_etag) {
         $response->headers->set('ETag', $etag);
     }
     // Return 304 not modified if either last modified or etag match.
     if ($last_modified == $if_modified_since || $etag == $if_none_match) {
         $response->setStatusCode(304);
         return $response;
     }
     // The following headers force validation of cache.
     $response->headers->set('Expires', 'Sun, 19 Nov 1978 05:00:00 GMT');
     $response->headers->set('Cache-Control', 'must-revalidate');
     $response->headers->set('Content-Type', 'application/rss+xml; charset=utf-8');
     // Read actual feed from file.
     $file_name = drupal_get_path('module', 'aggregator_test') . '/aggregator_test_rss091.xml';
     $handle = fopen($file_name, 'r');
     $feed = fread($handle, filesize($file_name));
     fclose($handle);
     $response->setContent($feed);
     return $response;
 }