isNotModified() public method

If the Response is not modified, it sets the status code to 304 and removes the actual content by calling the setNotModified() method.
public isNotModified ( Request $request ) : boolean
$request Request A Request instance
return boolean true if the Response validators match the Request, false otherwise
Exemplo n.º 1
0
 public function intercept(MethodInvocation $invocation)
 {
     /*
      * First let's make sure we can even bother caching this
      * if we can't then just return the controller response
      */
     if (!$this->decider->decide()) {
         return $invocation->proceed();
     }
     /* @var $controller ResourceController */
     $controller = $invocation->object;
     /* @var $request Request */
     $request = $invocation->arguments[0];
     // Current Resource
     $resource = $controller->findOr404($request);
     // Cache Options
     $options = $request->attributes->get('_sylius', []);
     $cacheOptions = array_key_exists('cache', $options) ? $options['cache'] : [];
     // Build the actual cache options since we'll need to use it twice
     $this->parser->process($cacheOptions, $resource);
     // Create a preliminary response to see if it is already cached
     $cachedResponse = new Response();
     $cachedResponse->setCache($cacheOptions);
     if ($cachedResponse->isNotModified($request)) {
         return $cachedResponse;
     }
     // If not we take the response back from the controller and modify it again
     $controllerResponse = $invocation->proceed();
     $controllerResponse->setCache($cacheOptions);
     return $controllerResponse;
 }
Exemplo n.º 2
0
 function handle(Request $request, $type = HttpFoundation::MASTER_REQUEST, $catch = true)
 {
     $pathinfo = $request->getPathInfo();
     if (preg_match('{^/_pipe/(.+)$}', $pathinfo, $matches)) {
         $path = $matches[1];
         if (!$path or !($asset = $this->env->find($path, array('bundled' => true)))) {
             $this->log->error("pipe: Asset '{$path}' not found");
             return new Response('Not Found', 404);
         }
         $lastModified = new \DateTime();
         $lastModified->setTimestamp($asset->getLastModified());
         $response = new Response();
         $response->setPublic();
         $response->setLastModified($lastModified);
         if ($response->isNotModified($request)) {
             $this->log->info("pipe: 302 {$path}");
             return $response;
         }
         $start = microtime(true);
         $response->setContent($asset->getBody());
         $this->log->info(sprintf('pipe: Rendered "%s" in %d seconds', $path, microtime(true) - $start));
         $response->headers->set('Content-Type', $asset->getContentType());
         $response->prepare($request);
         return $response;
     }
     return $this->app->handle($request, $type, $catch);
 }
Exemplo n.º 3
0
 public function onKernelController(FilterControllerEvent $event)
 {
     $controller = $event->getController();
     $request = $event->getRequest();
     $annotation = $this->findAnnotation($controller);
     if (!$annotation) {
         return;
     }
     $lastTouched = $annotation->calculateLastModified($this->metaQueryFactory);
     if (!$lastTouched) {
         return;
     }
     $this->lastTouchedResults[$request] = $lastTouched;
     /*
      * Für kernel.debug = 1 senden wir niemals
      * 304-Responses, anstatt den Kernel auszuführen:
      *
      * Das Ergebnis hängt auch von vielen Dingen außerhalb
      * wfd_meta ab (z. B. template-Code), die wir hier nicht
      * berücksichtigen können.
      */
     if ($this->debug) {
         return;
     }
     $response = new Response();
     $response->setLastModified($lastTouched);
     if ($response->isNotModified($request)) {
         $event->setController(function () use($response) {
             return $response;
         });
     }
 }
 public function resultatAction(Request $request, AbstractTerritoire $territoire)
 {
     $response = new Response();
     $response->setLastModified($this->get('repository.cache_info')->getLastModified($territoire));
     $response->setPublic();
     if ($response->isNotModified($request)) {
         return $response;
     }
     $allEcheances = $this->get('repository.echeance')->getAll();
     $form = $this->createForm(new EcheanceChoiceType($allEcheances), array(), array('method' => 'GET'));
     $form->handleRequest($request);
     if ($form->isSubmitted() && $form->isValid() && ($data = $form->getData())) {
         $reference = $data['comparaison'] ? $data['comparaison']->getNom() : null;
         $echeances = $data['echeances'];
         if (!in_array($reference, $echeances->toArray(), true)) {
             $reference = null;
         }
     } else {
         $echeances = array_filter($allEcheances, function ($element) {
             return $element->getType() !== Echeance::MUNICIPALES;
         });
         $reference = null;
         $form->get('echeances')->setData(new ArrayCollection($echeances));
     }
     $results = $this->getResults($territoire, $echeances);
     return $this->render('resultat.html.twig', array('form' => $form->createView(), 'resultats' => $results, 'territoire' => $territoire->getNom(), 'reference' => $reference), $response);
 }
Exemplo n.º 5
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.º 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
 /**
  * @param Request $request
  * @param $storageKey
  *
  * @return Response
  */
 protected function createFileResponse(Request $request, $storageKey)
 {
     $response = new Response();
     $parts = explode('/', $storageKey);
     $file = $this->getFile($parts[0]);
     if (!$file) {
         return $response->setContent('File not found.')->setStatusCode(Response::HTTP_NOT_FOUND);
     }
     if ($request->get('dl') !== null) {
         $filename = $file->getFilename();
         if (count($parts) > 1) {
             $filename = $parts[count($parts) - 1];
         }
         $filenameFallback = filter_var($filename, FILTER_SANITIZE_URL);
         if ($filenameFallback != $filename) {
             $guesser = ExtensionGuesser::getInstance();
             $extension = filter_var($guesser->guess($file->getMimeType()) ?: $file->getExtension(), FILTER_SANITIZE_URL);
             $filenameFallback = $file->getStorageKey() . ($extension ? '.' . $extension : '');
         }
         $response->headers->set('Content-Disposition', $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename, $filenameFallback));
     } else {
         $response->setCache(array('etag' => $file->getStorageKey(), 'last_modified' => $file->getCreatedAt()));
         if ($response->isNotModified($request)) {
             return $response;
         }
     }
     $response->setContent($file->getContents());
     $response->headers->set('Content-type', $file->getMimeType());
     $response->headers->set('Content-length', $file->getSize());
     return $response;
 }
Exemplo n.º 8
0
 /**
  * View a single content page
  *
  * This Controller action is being routed to from either our custom ContentRouter,
  * or the ExceptionController.
  * @see Opifer\SiteBundle\Router\ContentRouter
  *
  * @param Request          $request
  * @param ContentInterface $content
  * @param int              $statusCode
  *
  * @return Response
  *
  * @throws \Exception
  */
 public function viewAction(Request $request, ContentInterface $content, $statusCode = 200)
 {
     $version = $request->query->get('_version');
     $debug = $this->getParameter('kernel.debug');
     $contentDate = $content->getUpdatedAt();
     $templateDate = $content->getTemplate()->getUpdatedAt();
     $date = $contentDate > $templateDate ? $contentDate : $templateDate;
     $response = new Response();
     $response->setLastModified($date);
     $response->setPublic();
     if (null === $version && false == $debug && $response->isNotModified($request)) {
         // return the 304 Response immediately
         return $response;
     }
     $version = $request->query->get('_version');
     /** @var Environment $environment */
     $environment = $this->get('opifer.content.block_environment');
     $environment->setObject($content);
     $response->setStatusCode($statusCode);
     if (null !== $version && $this->isGranted('ROLE_ADMIN')) {
         $environment->setDraft(true);
     }
     $environment->load();
     return $this->render($environment->getView(), $environment->getViewParameters(), $response);
 }
Exemplo n.º 9
0
 private function getResponse(Request $request, $name, array $files, $content_type)
 {
     if (!isset($files[$name])) {
         return new Response('Not Found', 404, array('Content-Type' => 'text/plain'));
     }
     $file = $files[$name];
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge(self::EXPIRED_TIME);
     $response->setSharedMaxAge(self::EXPIRED_TIME);
     $response->headers->set('Content-Type', $content_type);
     // set a custom Cache-Control directive
     $response->headers->addCacheControlDirective('must-revalidate', true);
     $date = new \DateTime();
     $date->setTimestamp(strtotime($this->container->getParameter('sf.version')));
     $response->setETag($date->getTimestamp());
     $response->setLastModified($date);
     if ($response->isNotModified($request)) {
         return $response;
     }
     if (!file_exists($file)) {
         throw new \Exception(sprintf("file `%s`, `%s` not exists", $name, $file));
     }
     $response->setContent(file_get_contents($file));
     return $response;
 }
Exemplo n.º 10
0
 public function get_post()
 {
     if (!$this->check_board()) {
         return $this->response->setData(['error' => _i('No board was selected.')])->setStatusCode(422);
     }
     $num = $this->getQuery('num');
     if (!$num) {
         return $this->response->setData(['error' => _i('The "num" parameter is missing.')])->setStatusCode(422);
     }
     if (!Board::isValidPostNumber($num)) {
         return $this->response->setData(['error' => _i('The value for "num" is invalid.')])->setStatusCode(422);
     }
     try {
         $board = Board::forge($this->getContext())->getPost($num)->setRadix($this->radix);
         $comment = current($board->getComments());
         $this->apify($comment);
         $last_modified = $comment->comment->timestamp_expired ?: $comment->comment->timestamp;
         $this->setLastModified($last_modified);
         if (!$this->response->isNotModified($this->request)) {
             $this->response->setData($comment);
         }
     } catch (\Foolz\Foolslide\Model\BoardPostNotFoundException $e) {
         return $this->response->setData(['error' => _i('Post not found.')]);
     } catch (\Foolz\Foolslide\Model\BoardException $e) {
         return $this->response->setData(['error' => $e->getMessage()])->setStatusCode(500);
     }
     return $this->response;
 }
Exemplo n.º 11
0
 /**
  * Handles HTTP validation headers.
  */
 public function onKernelController(FilterControllerEvent $event)
 {
     $request = $event->getRequest();
     if (!($configuration = $request->attributes->get('_cache'))) {
         return;
     }
     $response = new Response();
     $lastModifiedDate = '';
     if ($configuration->getLastModified()) {
         $lastModifiedDate = $this->getExpressionLanguage()->evaluate($configuration->getLastModified(), $request->attributes->all());
         $response->setLastModified($lastModifiedDate);
     }
     $etag = '';
     if ($configuration->getETag()) {
         $etag = hash('sha256', $this->getExpressionLanguage()->evaluate($configuration->getETag(), $request->attributes->all()));
         $response->setETag($etag);
     }
     if ($response->isNotModified($request)) {
         $event->setController(function () use($response) {
             return $response;
         });
     } else {
         if ($etag) {
             $this->etags[$request] = $etag;
         }
         if ($lastModifiedDate) {
             $this->lastModifiedDates[$request] = $lastModifiedDate;
         }
     }
 }
Exemplo n.º 12
0
 public function indexAction()
 {
     $response = new Response();
     $response->setPublic();
     if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
         $response->setETag(md5((string) $this->getUser()->getType()));
         switch ($this->getUser()->getType()) {
             case 'publisher':
                 $homepage = 'Publisher';
                 break;
             case 'advertiser':
                 $homepage = 'Advertiser';
                 break;
         }
         $response->setMaxAge(60 * 30);
     } else {
         $response->setETag(md5('public'));
         $homepage = 'Public';
         $response->setMaxAge(60 * 60 * 10);
     }
     $response->headers->set('Vary', 'Cookie');
     // $response->headers->addCacheControlDirective('must-revalidate', true);
     if ($response->isNotModified($this->getRequest())) {
         return $response;
     }
     return $this->render('VifeedFrontendBundle:' . $homepage . ':homepage.html.twig', [], $response);
 }
Exemplo n.º 13
0
Arquivo: Server.php Projeto: chh/pipe
 function handle(HttpFoundation\Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
 {
     $path = ltrim($request->getPathInfo(), '/');
     $asset = $this->environment->find($path, array("bundled" => true));
     $debug = $request->query->get("debug", false);
     $cache = !$request->query->get("nocache", false);
     if (!$asset or $path == '') {
         return $this->renderNotFound($request);
     }
     if ($debug) {
         $this->environment->bundleProcessors->clear();
     }
     $lastModified = new \DateTime();
     $lastModified->setTimestamp($asset->getLastModified());
     $response = new HttpFoundation\Response();
     $response->setPublic();
     $response->setLastModified($lastModified);
     if ($cache and $response->isNotModified($request)) {
         return $response;
     }
     $response->setContent($asset->getBody());
     $response->headers->set('Content-Type', $asset->getContentType());
     $response->prepare($request);
     return $response;
 }
Exemplo n.º 14
0
 public function hasCachedResponse(Request $request, DateTime $lastWriteTime)
 {
     $response = new Response();
     $response->setLastModified($lastWriteTime);
     if ($response->isNotModified($request)) {
         return $response;
     }
     return false;
 }
Exemplo n.º 15
0
 public function renderAction(Request $request, $ulClass = null)
 {
     $lastUpdated = $this->getPageRepository()->getLastUpdated();
     $response = new Response();
     $response->setLastModified($lastUpdated)->setPublic();
     if ($response->isNotModified($request)) {
         return $response;
     }
     return $this->render('@SymEdit/Menu/render.html.twig', ['ulClass' => $ulClass], $response);
 }
Exemplo n.º 16
0
 private function checkUpdatedAt(Request $request, \DateTime $updatedAt)
 {
     $response = new Response();
     $response->setLastModified($updatedAt);
     if (!$response->isNotModified($request)) {
         //is newer, need to generate a new response and cannot use the old one
         $response = null;
     }
     return $response;
 }
Exemplo n.º 17
0
 public function getETag(Request $request, $res, $_format = 'json')
 {
     $response = new Response($res);
     $response->setETag(md5($response->getContent()));
     $response->setPublic();
     // make sure the response is public/cacheable
     $response->headers->set('Content-Type', $this->getContentType($_format));
     $response->isNotModified($request);
     return $response;
 }
 /**
  * @Route(
  *      "/submit-ticket/{id}",
  *      name="diamante_embedded_form_submit",
  *      requirements={"id"="[-\d\w]+"},
  * )
  */
 public function formAction(EmbeddedForm $formEntity)
 {
     $response = new Response();
     $response->setPublic();
     //$response->setEtag($formEntity->getId() . $formEntity->getUpdatedAt()->format(\DateTime::ISO8601));
     if ($response->isNotModified($this->getRequest())) {
         return $response;
     }
     $command = new EmbeddedTicketCommand();
     $formManager = $this->get('oro_embedded_form.manager');
     $form = $formManager->createForm($formEntity->getFormType());
     if (in_array($this->getRequest()->getMethod(), ['POST', 'PUT'])) {
         $data = $this->getRequest()->get('diamante_embedded_form');
         //Initialize Reporter
         $diamanteUserRepository = $this->get('diamante.user.repository');
         $diamanteUser = $diamanteUserRepository->findUserByEmail($data['emailAddress']);
         if (is_null($diamanteUser)) {
             $diamanteUser = $this->get('diamante.user_factory')->create($data['emailAddress'], $data['firstName'], $data['lastName']);
             $diamanteUserRepository->store($diamanteUser);
         }
         $reporterId = $diamanteUser->getId();
         $reporter = new User($reporterId, User::TYPE_DIAMANTE);
         //Set Command for embedded form
         $command->reporter = $reporter;
         $command->priority = Priority::PRIORITY_MEDIUM;
         $command->source = Source::WEB;
         $command->status = Status::NEW_ONE;
         $command->branch = $formEntity->getBranch();
         $command->subject = $data['subject'];
         $command->description = $data['description'];
         if ($formEntity->getBranch() && $formEntity->getBranch()->getDefaultAssignee()) {
             $assignee = $formEntity->getBranch()->getDefaultAssignee();
         } else {
             $assignee = null;
         }
         $command->assignee = $assignee;
         $form->handleRequest($this->getRequest());
         if ($form->isValid()) {
             $command->branch = $formEntity->getBranch()->getId();
             $this->get('diamante.ticket.service')->createTicket($command);
             return $this->redirect($this->generateUrl('oro_embedded_form_success', ['id' => $formEntity->getId()]));
         }
     }
     $formView = $form->createView();
     $formView->children['attachmentsInput']->vars = array_replace($formView->children['attachmentsInput']->vars, array('full_name' => 'diamante_embedded_form[attachmentsInput][]'));
     // TODO: Next code should be refactored.
     // TODO: Should be changed due to new EmbeddedFormBundle requirements
     $formResponse = $this->render('DiamanteEmbeddedFormBundle::embeddedForm.html.twig', ['form' => $formView, 'formEntity' => $formEntity]);
     $layoutManager = $this->get('oro_embedded_form.embed_form_layout_manager');
     $layoutContent = $layoutManager->getLayout($formEntity, $form)->render();
     $replaceString = '<div id="page">';
     $response->setContent(str_replace($replaceString, $replaceString . $formResponse->getContent(), $layoutContent));
     return $response;
 }
Exemplo n.º 19
0
 public function getResponse($name, array $options = array())
 {
     $service = $this->getAssetService();
     $response = new Response('', 200, array('Content-Type' => $service->getContentType($name)));
     $response->setLastModified($service->getLastModified($name));
     $response->setPublic();
     if (!array_key_exists('request', $options) || !$response->isNotModified($options['request'])) {
         $response->setContent($service->getContent($name));
     }
     return $response;
 }
Exemplo n.º 20
0
 public function execute(Request $request, Config $config, WorkingFolder $workingFolder, ResizedImageRepository $resizedImageRepository, CacheManager $cache)
 {
     $fileName = (string) $request->query->get('fileName');
     list($requestedWidth, $requestedHeight) = Image::parseSize((string) $request->get('size'));
     $downloadedFile = new DownloadedFile($fileName, $this->app);
     $downloadedFile->isValid();
     if (!Image::isSupportedExtension(pathinfo($fileName, PATHINFO_EXTENSION), $config->get('thumbnails.bmpSupported'))) {
         throw new InvalidExtensionException('Unsupported image type or not image file');
     }
     Utils::removeSessionCacheHeaders();
     $response = new Response();
     $response->setPublic();
     $response->setEtag(dechex($downloadedFile->getTimestamp()) . "-" . dechex($downloadedFile->getSize()));
     $lastModificationDate = new \DateTime();
     $lastModificationDate->setTimestamp($downloadedFile->getTimestamp());
     $response->setLastModified($lastModificationDate);
     if ($response->isNotModified($request)) {
         return $response;
     }
     $imagePreviewCacheExpires = (int) $config->get('cache.imagePreview');
     if ($imagePreviewCacheExpires > 0) {
         $response->setMaxAge($imagePreviewCacheExpires);
         $expireTime = new \DateTime();
         $expireTime->modify('+' . $imagePreviewCacheExpires . 'seconds');
         $response->setExpires($expireTime);
     }
     $cachedInfoPath = Path::combine($workingFolder->getResourceType()->getName(), $workingFolder->getClientCurrentFolder(), $fileName);
     $cachedInfo = $cache->get($cachedInfoPath);
     $resultImage = null;
     // Try to reuse existing resized image
     if ($cachedInfo && isset($cachedInfo['width']) && isset($cachedInfo['height'])) {
         // Fix received aspect ratio
         $size = Image::calculateAspectRatio($requestedWidth, $requestedHeight, $cachedInfo['width'], $cachedInfo['height']);
         $resizedImage = $resizedImageRepository->getResizedImageBySize($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $size['width'], $size['height']);
         if ($resizedImage) {
             $resultImage = Image::create($resizedImage->getImageData());
         }
     }
     // Fallback - get and resize the original image
     if (null === $resultImage) {
         $resultImage = Image::create($downloadedFile->getContents(), $config->get('thumbnails.bmpSupported'));
         $cache->set($cachedInfoPath, $resultImage->getInfo());
         $resultImage->resize($requestedWidth, $requestedHeight);
     }
     $mimeType = $resultImage->getMimeType();
     if (in_array($mimeType, array('image/bmp', 'image/x-ms-bmp'))) {
         $mimeType = 'image/jpeg';
         // Image::getData() by default converts resized images to JPG
     }
     $response->headers->set('Content-Type', $mimeType . '; name="' . $downloadedFile->getFileName() . '"');
     $response->setContent($resultImage->getData());
     return $response;
 }
Exemplo n.º 21
0
 /**
  * Display a text by its id
  *
  * @param Request $request
  * @param integer $textId
  *
  * @return Response
  */
 public function displayTextByIdAction(Request $request, $textId)
 {
     $textLastUpdate = $this->textRepository->findLastUpdate(null, null, $textId);
     $response = new Response();
     $response->setPublic();
     $response->setEtag($textId . $textLastUpdate);
     if ($response->isNotModified($request)) {
         return $response;
     }
     $text = $this->textRepository->findOneBy(array('id' => $textId, 'active' => true));
     return $this->render('UnifikSystemBundle:Frontend/Text:displayTexts.html.twig', ['texts' => is_null($text) ? null : array($text), 'textId' => $textId], $response);
 }
Exemplo n.º 22
0
 /**
  * @Route("/submit/{id}", name="oro_embedded_form_submit", requirements={"id"="[-\d\w]+"})
  */
 public function formAction(EmbeddedForm $formEntity, Request $request)
 {
     $response = new Response();
     $response->setPublic();
     $response->setEtag($formEntity->getId() . $formEntity->getUpdatedAt()->format(\DateTime::ISO8601));
     if ($response->isNotModified($request)) {
         return $response;
     }
     /** @var EntityManager $em */
     $em = $this->get('doctrine.orm.entity_manager');
     /** @var EmbeddedFormManager $formManager */
     $formManager = $this->get('oro_embedded_form.manager');
     $form = $formManager->createForm($formEntity->getFormType());
     if (in_array($request->getMethod(), ['POST', 'PUT'])) {
         $dataClass = $form->getConfig()->getOption('data_class');
         if (isset($dataClass) && class_exists($dataClass)) {
             $ref = new \ReflectionClass($dataClass);
             $constructor = $ref->getConstructor();
             $data = $constructor && $constructor->getNumberOfRequiredParameters() ? $ref->newInstanceWithoutConstructor() : $ref->newInstance();
             $form->setData($data);
         } else {
             $data = [];
         }
         $event = new EmbeddedFormSubmitBeforeEvent($data, $formEntity);
         $eventDispatcher = $this->get('event_dispatcher');
         $eventDispatcher->dispatch(EmbeddedFormSubmitBeforeEvent::EVENT_NAME, $event);
         $form->submit($request);
         $event = new EmbeddedFormSubmitAfterEvent($data, $formEntity, $form);
         $eventDispatcher->dispatch(EmbeddedFormSubmitAfterEvent::EVENT_NAME, $event);
     }
     if ($form->isValid()) {
         $entity = $form->getData();
         /**
          * Set owner ID (current organization) to concrete form entity
          */
         $entityClass = ClassUtils::getClass($entity);
         $config = $this->get('oro_entity_config.provider.ownership');
         $entityConfig = $config->getConfig($entityClass);
         $formEntityConfig = $config->getConfig($formEntity);
         if ($entityConfig->get('owner_type') === OwnershipType::OWNER_TYPE_ORGANIZATION) {
             $accessor = PropertyAccess::createPropertyAccessor();
             $accessor->setValue($entity, $entityConfig->get('owner_field_name'), $accessor->getValue($formEntity, $formEntityConfig->get('owner_field_name')));
         }
         $em->persist($entity);
         $em->flush();
         return $this->redirect($this->generateUrl('oro_embedded_form_success', ['id' => $formEntity->getId()]));
     }
     /** @var EmbedFormLayoutManager $layoutManager */
     $layoutManager = $this->get('oro_embedded_form.embed_form_layout_manager');
     $response->setContent($layoutManager->getLayout($formEntity, $form)->render());
     return $response;
 }
Exemplo n.º 23
0
 public function showPageAction($id, $extraParams = null, $currentpage = null, $totalpageitems = null, $linkUrlParams = null)
 {
     // Get data to display
     $page = $this->getDoctrine()->getRepository('BlogBundle:Blog')->find($id);
     $userRole = $this->get('sonata_user.services.helpers')->getLoggedUserHighestRole();
     $settings = $this->get('bardiscms_settings.load_settings')->loadSettings();
     // Simple ACL for publishing
     if ($page->getPublishState() == 0) {
         return $this->render404Page();
     }
     if ($page->getPublishState() == 2 && $userRole == '') {
         return $this->render404Page();
     }
     if ($userRole == "") {
         $publishStates = array(1);
     } else {
         $publishStates = array(1, 2);
     }
     if ($this->container->getParameter('kernel.environment') == 'prod' && $settings->getActivateHttpCache()) {
         $response = new Response();
         // set a custom Cache-Control directive
         $response->headers->addCacheControlDirective('must-revalidate', true);
         // set multiple vary headers
         $response->setVary(array('Accept-Encoding', 'User-Agent'));
         // create a Response with a Last-Modified header
         $response->setLastModified($page->getDateLastModified());
         // Set response as public. Otherwise it will be private by default.
         $response->setPublic();
         //var_dump($response->isNotModified($this->getRequest()));
         //var_dump($response->getStatusCode());
         if (!$response->isNotModified($this->getRequest())) {
             // Marks the Response stale
             $response->expire();
         } else {
             // return the 304 Response immediately
             $response->setSharedMaxAge(3600);
             return $response;
         }
     }
     // Set the website settings and metatags
     $page = $this->get('bardiscms_settings.set_page_settings')->setPageSettings($page);
     // Set the pagination variables
     if (!$totalpageitems) {
         if (is_object($settings)) {
             $totalpageitems = $settings->getBlogItemsPerPage();
         } else {
             $totalpageitems = 10;
         }
     }
     // Render the correct view depending on pagetype
     return $this->renderPage($page, $id, $publishStates, $extraParams, $currentpage, $totalpageitems, $linkUrlParams);
 }
Exemplo n.º 24
0
 public function listAction(Request $request, Application $app)
 {
     $pager = $app['document_repository']->paginate((int) $request->query->get('page', 1), (int) $request->query->get('limit', 10));
     $response = new Response();
     $results = (array) $pager->getCurrentPageResults();
     $response->setPublic();
     $response->setETag($this->computeETag($request, $results));
     if ($response->isNotModified($request)) {
         return $response;
     }
     $documents = $app['hateoas.pagerfanta_factory']->createRepresentation($pager, new Route('document_list', [], true), new CollectionRepresentation($results, 'documents', null, null, null, [new Relation("expr(curies_prefix ~ ':documents')", new Route("document_list", [], true))]), true);
     return $app['view_handler']->handle($documents, 200, [], $response);
 }
Exemplo n.º 25
0
 public function helloWorldTwigCachedAction()
 {
     $response = new Response();
     $response->setPublic();
     $response->setETag("HelloWorldTwigTag");
     //        $response->setLastModified( new DateTime( "2012-01-01 00:00:00+0000" ) );
     // Check that the Response is not modified for the given Request
     if ($response->isNotModified($this->getRequest())) {
         // return the 304 Response immediately
         return $response;
     }
     return $this->render("eZDemoBundle::hello_world.html.twig", array(), $response);
 }
Exemplo n.º 26
0
 /**
  * @Rest\View
  */
 public function getLatestCommentsAction($limit)
 {
     $em = $this->getDoctrine()->getEntityManager();
     $comments = $em->getRepository('KoiosBlogBackendBundle:Comment')->getLatestComments($limit);
     $response = new SymResponse();
     $response->setLastModified(count($comments) ? end($comments)->getUpdated() : new \DateTime());
     $response->setPublic();
     if ($response->isNotModified($this->getRequest())) {
         return $response;
     }
     $view = View::create()->setStatusCode(200)->setData($comments);
     return $this->get('fos_rest.view_handler')->handle($view, $this->getRequest(), $response);
 }
 /**
  * This Action displays the user info (name and profile pic)
  *
  * @return Response
  */
 public function userInfoAction()
 {
     $tokenHandler = $this->get('instaphp_token_handler');
     $response = new Response();
     $response->setETag($tokenHandler->getToken());
     if ($response->isNotModified($this->getRequest())) {
         return $response;
     } else {
         $instaphp = $this->get('instaphp');
         $info = $instaphp->Users->Info('self');
         return $this->render('OhInstagramBundle:Instagram:userInfo.html.twig', array('info' => $info), $response);
     }
 }
Exemplo n.º 28
0
 private function checkEtagsAndStuff(Request $request)
 {
     $hash = $this->getGitLatestCommitHash();
     if (!empty($hash)) {
         $response = new Response();
         $response->setMaxAge(600);
         $response->setPublic();
         $response->setETag(md5($hash));
         if ($response->isNotModified($request)) {
             return $response;
         }
     }
     return null;
 }
 /**
  * @param Request $request
  *
  * @return Response
  */
 public function changelogAction(Request $request)
 {
     $content = file_get_contents($this->kernelRootDir . '/../changelog.yml');
     $response = new Response();
     $response->setPublic();
     $response->setEtag(md5($content));
     $response->setVary('Accept-Encoding', 'User-Agent');
     if (!$response->isNotModified($request)) {
         $parser = new Parser();
         $response->setLastModified(new \DateTime());
         return $this->engine->renderResponse('@CertificationyWeb/Site/changelog.html.twig', ['changelog' => $parser->parse($content)]);
     }
     return $response;
 }
Exemplo n.º 30
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;
 }