setExpires() public method

Passing null as value will remove the header.
public setExpires ( DateTime $date = null ) : Response
$date DateTime A \DateTime instance or null to remove the header
return Response
 /**
  * Update a valid non cacheable Response with http cache headers
  *
  * @see http://symfony.com/fr/doc/current/book/http_cache.html
  */
 public function handleResponse(Response $response)
 {
     // do not handle invalid response
     if (!$response->isOk()) {
         return $response;
     }
     // do not handle response with http cache headers
     if ($response->isCacheable()) {
         return $response;
     }
     // seek for optional configuration
     $this->readRoutingConfiguration();
     // mark the response as private
     $response->setPrivate();
     // set the private or shared max age
     $response->setMaxAge($this->duration);
     $response->setSharedMaxAge($this->duration);
     // set expires
     $date = new \DateTime();
     $date->modify(sprintf('+%d seconds', $this->duration));
     $response->setExpires($date);
     // set a custom Cache-Control directive
     $response->headers->addCacheControlDirective('must-revalidate', true);
     return $response;
 }
Example #2
0
 /**
  * Cache the response 1 year (31536000 sec)
  */
 protected function cacheResponse(Response $response)
 {
     $response->setSharedMaxAge(31536000);
     $response->setMaxAge(31536000);
     $response->setExpires(new \DateTime('+1 year'));
     return $response;
 }
Example #3
0
 /**
  * @Route("/routeC")
  */
 public function hellaAction()
 {
     $date = new \DateTime();
     $date->modify('+5 seconds');
     $response = new Response('');
     $response->setExpires($date);
 }
 /**
  * Get the details of a person.
  *
  * @param int $id The ID of the person as assigned by MyAnimeList
  *
  * @return View
  */
 public function getAction($id)
 {
     // http://myanimelist.net/people/#{id}
     $downloader = $this->get('atarashii_api.communicator');
     try {
         $personDetails = $downloader->fetch('/people/' . $id);
     } catch (Exception\CurlException $e) {
         return $this->view(array('error' => 'network-error'), 500);
     } catch (Exception\ClientErrorResponseException $e) {
         $personDetails = $e->getResponse();
     }
     if (strpos($personDetails, 'This page doesn\'t exist') !== false) {
         return $this->view(array('error' => 'not-found'), 200);
     } else {
         $person = PersonParser::parse($personDetails);
         $response = new Response();
         $response->setPublic();
         $response->setMaxAge(86400);
         //One day
         $response->headers->addCacheControlDirective('must-revalidate', true);
         //Also, set "expires" header for caches that don't understand Cache-Control
         $date = new \DateTime();
         $date->modify('+172800 seconds');
         //two days
         $response->setExpires($date);
         $view = $this->view($person);
         $view->setResponse($response);
         $view->setStatusCode(200);
         return $view;
     }
 }
Example #5
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;
 }
 public function indexAction($search, $page = 1)
 {
     $this->construct();
     $res = new Response();
     $res->setExpires((new \DateTime())->modify('+ 120 seconds'));
     $finder = $this->container->get('fos_elastica.finder.search.post');
     if (!$search) {
         $search = $this->get('request')->query->get('search');
     }
     $res->setETag(md5($search));
     $posts = $projects = $photoCategories = $photos = array();
     $res->setPublic();
     try {
         $posts = $this->tryCache($search, 'post_search', 'ArrayCollection<Aldor\\BlogBundle\\Entity\\Post>', 'fos_elastica.finder.search.post');
         $projects = $this->tryCache($search, 'projects', 'ArrayCollection<Aldor\\PortfolioBundle\\Entity\\Project>', 'fos_elastica.finder.search.project');
         $photoCategories = $this->tryCache($search, 'photo_catgory', 'ArrayCollection<Aldor\\GalleryBundle\\Entity\\PhotoCategory>', 'fos_elastica.finder.search.photo_category');
         $photos = $this->tryCache($search, 'photos', 'ArrayCollection<Aldor\\GalleryBundle\\Entity\\Photo>', 'fos_elastica.finder.search.photo');
     } catch (\Exception $err) {
         $logger = $this->get('logger');
         $logger->error('Elastica error' . $err);
     }
     $posts = $this->m_paginator->paginate($posts, $this->get('request')->query->get('strona', $page), $this->container->getParameter('max_post_on_page'));
     $projects = $this->m_paginator->paginate($projects, $this->get('request')->query->get('strona', $page), $this->container->getParameter('max_post_on_page'));
     $posts->setUsedRoute('inftech_search');
     $posts->setParam('search', '*' . $search . '*');
     $seoPage = $this->container->get('sonata.seo.page');
     $seoPage->setTitle('Szukaj - mkaciuba.pl')->addMeta('name', 'description', 'Marcin Kaciuba - blog o tematyce IT i fotografii')->addMeta('property', 'og:title', 'Szukaj - mkaciuba.pl')->addMeta('property', 'og:type', 'blog')->addMeta('property', 'og:description', 'Marcin Kaciuba - blog o tematyce IT i fotografii');
     return $this->render('AldorInftechBundle:Search:index.html.twig', array('posts' => $posts, 'photoCategories' => $photoCategories, 'projects' => $projects, 'resultCount' => count($posts) + count($photoCategories) + count($projects) + count($photos), 'photos' => $photos, 'search' => $search), $res);
 }
 /**
  * Renders the footer
  *
  * @return Response
  */
 public function footerAction()
 {
     $footerContent = $this->get('metalfrance.repository.layout')->getFooter();
     $response = new Response();
     $response->setExpires(new DateTime('next year'));
     $response->headers->set('X-Location-Id', $footerContent->contentInfo->mainLocationId);
     return $this->render('MetalFranceSiteBundle:Layout:footer.html.twig', ['footer_content' => $footerContent], $response);
 }
Example #8
0
 public function uncachableResponse()
 {
     $response = new Response();
     $date = new DateTime();
     $date->modify('-1 day');
     $response->setExpires($date);
     $response->headers->addCacheControlDirective('must-revalidate', true);
     $response->headers->addCacheControlDirective('no-store', true);
     $response->headers->addCacheControlDirective('no-cache', true);
     return $response;
 }
Example #9
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;
 }
Example #10
0
 public function displayAction($id)
 {
     $basepath = $this->container->getParameter('symfony_cmf_content.static_basepath');
     $image = $this->dm->find(null, $basepath . '/' . $id);
     $data = stream_get_contents($image->content);
     $response = new Response($data);
     $response->headers->set('Content-Type', 'image/jpeg');
     $response->setPublic();
     $date = new \DateTime();
     $date->setTimestamp(time() + 332640000);
     $response->setExpires($date);
     $response->setMaxAge(332640000);
     return $response;
 }
Example #11
0
 /**
  * @Route("/{code}", name="short_url")
  */
 public function indexAction(Request $request, $code)
 {
     $shortCode = $this->get('short_url')->get($code);
     if ($shortCode) {
         $response = new RedirectResponse($shortCode->getUrl(), RedirectResponse::HTTP_FOUND);
         $response->setPublic();
         $response->setExpires(new DateTime('+1 year'));
         return $response;
     }
     $response = new Response();
     $response->setPublic();
     $response->setExpires(new DateTime('+1 hour'));
     return $this->render('notFound.html.twig', ['code' => $code], $response);
 }
 /**
  * public function channelAction()
  *
  * This function mimics the channel.html file suggested by facebook.
  *
  * References :
  * https://developers.facebook.com/docs/reference/javascript/
  *
  * @version         1.0
  *
  * @author          Antoine Durieux
  *
  * @return Response
  */
 public function channelAction()
 {
     // Retrieve parameters from the container.
     $culture = $this->container->getParameter('fos_facebook.culture');
     $cacheExpire = $this->container->getParameter('fos_facebook.channel.expire');
     // Compute expiration date.
     $date = new \DateTime();
     $date->modify('+' . $cacheExpire . ' seconds');
     // Generate new response, and set parameters recommended by Facebook.
     $response = new Response();
     $response->headers->set("Pragma", "public");
     $response->setMaxAge($cacheExpire);
     $response->setExpires($date);
     $response->setContent('<script src="//connect.facebook.net/' . $culture . '/all.js"></script>');
     return $response;
 }
Example #13
0
 /**
  * List of posts with HTTP Response
  * @return Response
  */
 public function indexAction(Request $request)
 {
     $date = new \Datetime('+1 day');
     $response = new Response();
     $response->setETag($response->getContent());
     $response->setLastModified($date);
     $response->setPublic();
     $response->setExpires($date);
     $response->headers->addCacheControlDirective('must-revalidate', true);
     if ($response->isNotModified($request)) {
         return $response;
     } else {
         $em = $this->getDoctrine()->getManager();
         $posts = $em->getRepository('HeticPublicBundle:Post')->findAll();
         return $this->render('HeticPublicBundle:Post:index.html.twig', array('posts' => $posts));
     }
 }
Example #14
0
 protected function _prepareResponse($etag, $modifed = null, $expires = " +300 seconds", $s_max_age = 600, $max_age = 300)
 {
     $response = new Response();
     $currentTime = new \DateTime();
     $req = $this->getRequest();
     $deviceView = $this->m_deviceView->getViewType();
     $response->setExpires($currentTime->modify($expires));
     $response->setETag(md5($etag . $deviceView . $req->headers->get('x-forwarded-proto')));
     $response->setPublic();
     $response->setMaxAge($max_age);
     $response->setSharedMaxAge($s_max_age);
     if ($modifed) {
         $response->setLastModified($modifed);
     }
     $response->setVary(array('x-device-type', 'x-forwarded-proto'));
     return $response;
 }
 /**
  * Send a media stored via the UploadedFileManager
  *
  * @Config\Route("/{key}", name="open_orchestra_media_get")
  * @Config\Method({"GET"})
  *
  * @return Response
  */
 public function getAction($key)
 {
     $mediaStorageManager = $this->get('open_orchestra_media_file.manager.storage');
     $fileContent = $mediaStorageManager->getFileContent($key);
     $finfo = finfo_open(FILEINFO_MIME);
     $mimetype = finfo_buffer($finfo, $fileContent);
     finfo_close($finfo);
     $response = new Response();
     $response->headers->set('Content-Type', $mimetype);
     $response->headers->set('Content-Length', strlen($fileContent));
     $response->setContent($fileContent);
     $response->setPublic();
     $response->setMaxAge(2629743);
     $date = new \DateTime();
     $date->modify('+' . $response->getMaxAge() . ' seconds');
     $response->setExpires($date);
     return $response;
 }
 /**
  * This action applies a given filter to a given image, saves the image and
  * outputs it to the browser at the same time
  *
  * @param string $path
  * @param string $filter
  *
  * @return Response
  *
  * @throws Exception
  */
 public function filterAction($path, $filter)
 {
     $baseUrl = $this->request->getBaseUrl();
     try {
         try {
             $cachedPath = $this->cacheManager->cacheImage($baseUrl, $path, $filter);
         } catch (RuntimeException $e) {
             if (!isset($this->notFoundImages[$filter])) {
                 throw $e;
             }
             $path = $this->notFoundImages[$filter];
             $cachedPath = $this->cacheManager->cacheImage($baseUrl, $path, $filter);
         }
     } catch (RouteNotFoundException $e) {
         throw new NotFoundHttpException('Filter doesn\'t exist.');
     }
     // if cache path cannot be determined, return 404
     if (null === $cachedPath) {
         throw new NotFoundHttpException('Image doesn\'t exist');
     }
     try {
         // Using File instead of Imagine::open(), because i.e. image/x-icon is not widely supported.
         $file = new ImageFile($cachedPath, false);
         // TODO: add more media headers
         $headers = ['content-type' => $file->getMimeType(), 'content-length' => $file->getSize()];
         $response = new Response($file->getContents(), 201, $headers);
         // Cache
         if (!($cacheType = $this->filterManager->getOption($filter, 'cache_type', false))) {
             return $response;
         }
         $cacheType === 'public' ? $response->setPublic() : $response->setPrivate();
         $cacheExpires = $this->filterManager->getOption($filter, 'cache_expires', '1 day');
         $expirationDate = new DateTime('+' . $cacheExpires);
         $maxAge = $expirationDate->format('U') - time();
         if ($maxAge < 0) {
             throw new InvalidArgumentException('Invalid cache expiration date');
         }
         $response->setExpires($expirationDate);
         $response->setMaxAge($maxAge);
         return $response;
     } catch (Exception $e) {
         throw $e;
     }
 }
 /**
  * @param Response $response
  */
 public function apply(Response $response)
 {
     if (empty($this->parameters['enabled'])) {
         return;
     }
     $this->parameters['public'] ? $response->setPublic() : $response->setPrivate();
     if (is_integer($this->parameters['maxage'])) {
         $response->setMaxAge($this->parameters['maxage']);
     }
     if (is_integer($this->parameters['smaxage'])) {
         $response->setSharedMaxAge($this->parameters['smaxage']);
     }
     if ($this->parameters['expires'] !== null) {
         $response->setExpires(new \DateTime($this->parameters['expires']));
     }
     if (!empty($this->parameters['vary'])) {
         $response->setVary($this->parameters['vary']);
     }
 }
Example #18
0
 public function execute(Request $request, WorkingFolder $workingFolder, Config $config, ThumbnailRepository $thumbnailRepository)
 {
     if (!$config->get('thumbnails.enabled')) {
         throw new CKFinderException('Thumbnails feature is disabled', Error::THUMBNAILS_DISABLED);
     }
     $fileName = $request->get('fileName');
     $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
     if (!Image::isSupportedExtension($ext, $thumbnailRepository->isBitmapSupportEnabled())) {
         throw new InvalidNameException('Invalid source file name');
     }
     if (null === $fileName || !File::isValidName($fileName, $config->get('disallowUnsafeCharacters'))) {
         throw new InvalidRequestException('Invalid file name');
     }
     list($requestedWidth, $requestedHeight) = Image::parseSize($request->get('size'));
     $thumbnail = $thumbnailRepository->getThumbnail($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $requestedWidth, $requestedHeight);
     /**
      * This was added on purpose to reset any Cache-Control headers set
      * for example by session_start(). Symfony Session has a workaround,
      * but but we can't rely on this as application may not use Symfony
      * components to handle sessions.
      */
     header('Cache-Control:');
     $response = new Response();
     $response->setPublic();
     $response->setEtag(dechex($thumbnail->getTimestamp()) . "-" . dechex($thumbnail->getSize()));
     $lastModificationDate = new \DateTime();
     $lastModificationDate->setTimestamp($thumbnail->getTimestamp());
     $response->setLastModified($lastModificationDate);
     if ($response->isNotModified($request)) {
         return $response;
     }
     $thumbnailsCacheExpires = (int) $config->get('cache.thumbnails');
     if ($thumbnailsCacheExpires > 0) {
         $response->setMaxAge($thumbnailsCacheExpires);
         $expireTime = new \DateTime();
         $expireTime->modify('+' . $thumbnailsCacheExpires . 'seconds');
         $response->setExpires($expireTime);
     }
     $response->headers->set('Content-Type', $thumbnail->getMimeType() . '; name="' . $thumbnail->getFileName() . '"');
     $response->setContent($thumbnail->getImageData());
     return $response;
 }
Example #19
0
 private function asset_response($asset)
 {
     $response = new Response();
     $response->setExpires(new \DateTime());
     // last-modified
     if (null !== ($lastModified = $asset->getLastModified())) {
         $date = new \DateTime();
         $date->setTimestamp($lastModified);
         $response->setLastModified($date);
     }
     if ($response->isNotModified(Request::createFromGlobals())) {
         $response->send();
         exit;
     }
     $asset_content = $asset->dump();
     $response->setContent($asset_content);
     $response->headers->set("Content-type", $this->guess_mime($asset));
     $response->send();
     exit;
 }
Example #20
0
 public function execute(Request $request, WorkingFolder $workingFolder, Config $config, ThumbnailRepository $thumbnailRepository)
 {
     if (!$config->get('thumbnails.enabled')) {
         throw new CKFinderException('Thumbnails feature is disabled', Error::THUMBNAILS_DISABLED);
     }
     $fileName = (string) $request->get('fileName');
     $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
     if (!Image::isSupportedExtension($ext, $thumbnailRepository->isBitmapSupportEnabled())) {
         throw new InvalidNameException('Invalid source file name');
     }
     if (null === $fileName || !File::isValidName($fileName, $config->get('disallowUnsafeCharacters'))) {
         throw new InvalidRequestException('Invalid file name');
     }
     if (!$workingFolder->containsFile($fileName)) {
         throw new FileNotFoundException();
     }
     list($requestedWidth, $requestedHeight) = Image::parseSize((string) $request->get('size'));
     $thumbnail = $thumbnailRepository->getThumbnail($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $requestedWidth, $requestedHeight);
     Utils::removeSessionCacheHeaders();
     $response = new Response();
     $response->setPublic();
     $response->setEtag(dechex($thumbnail->getTimestamp()) . "-" . dechex($thumbnail->getSize()));
     $lastModificationDate = new \DateTime();
     $lastModificationDate->setTimestamp($thumbnail->getTimestamp());
     $response->setLastModified($lastModificationDate);
     if ($response->isNotModified($request)) {
         return $response;
     }
     $thumbnailsCacheExpires = (int) $config->get('cache.thumbnails');
     if ($thumbnailsCacheExpires > 0) {
         $response->setMaxAge($thumbnailsCacheExpires);
         $expireTime = new \DateTime();
         $expireTime->modify('+' . $thumbnailsCacheExpires . 'seconds');
         $response->setExpires($expireTime);
     }
     $response->headers->set('Content-Type', $thumbnail->getMimeType() . '; name="' . $thumbnail->getFileName() . '"');
     $response->setContent($thumbnail->getImageData());
     return $response;
 }
Example #21
0
 public function track(Request $request)
 {
     $this->request = $request;
     $referer = $this->request->query->get('utmr', '');
     $path = $this->request->query->get('utmp', '');
     $account = $this->request->query->get('utmac');
     $userAgent = $this->request->server->get('HTTP_USER_AGENT', '');
     $visitorId = $this->request->cookies->get($this->cookieName);
     if (empty($visitorId)) {
         $visitorId = $this->getVisitorId($this->getGuidHeader(), $account, $userAgent);
     }
     $url = $this->constructGifUrl($referer, $path, $account, $visitorId, $this->maskVisitorIp());
     $this->browser->get($url, array('Accept-Language: ' . $this->request->server->get('HTTP_ACCEPT_LANGUAGE'), 'User-Agent: ' . $userAgent));
     $cookie = new Cookie($this->cookieName, $visitorId, time() + $this->cookiePersistence, $this->cookiePath, $this->request->getHost());
     $response = new Response();
     $response->headers->add(array('Content-Type' => 'image/gif', 'Pragma' => 'no-cache'));
     $response->setPrivate();
     $response->mustRevalidate();
     $response->setExpires(new \DateTime('-10 year'));
     $response->setContent(join($this->gifData));
     $response->headers->setCookie($cookie);
     return $response;
 }
 /**
  * This action applies a given filter to a given image, saves the image and
  * outputs it to the browser at the same time
  *
  * @param string $path
  * @param string $filter
  *
  * @return Response
  */
 public function filter($path, $filter)
 {
     $cachedPath = $this->cacheManager->cacheImage($this->request->getBaseUrl(), $path, $filter);
     // if cache path cannot be determined, return 404
     if (null === $cachedPath) {
         throw new NotFoundHttpException('Image doesn\'t exist');
     }
     ob_start();
     try {
         $format = $this->filterManager->getOption($filter, "format", "png");
         $this->imagine->open($cachedPath)->show($format);
         $type = 'image/' . $format;
         $length = ob_get_length();
         $content = ob_get_clean();
         // TODO: add more media headers
         $response = new Response($content, 201, array('content-type' => $type, 'content-length' => $length));
         // Cache
         $cacheType = $this->filterManager->getOption($filter, "cache_type", false);
         if (false == $cacheType) {
             return $response;
         }
         $cacheType === "public" ? $response->setPublic() : $response->setPrivate();
         $cacheExpires = $this->filterManager->getOption($filter, "cache_expires", "1 day");
         $expirationDate = new \DateTime("+" . $cacheExpires);
         $maxAge = $expirationDate->format("U") - time();
         if ($maxAge < 0) {
             throw new \InvalidArgumentException("Invalid cache expiration date");
         }
         $response->setExpires($expirationDate);
         $response->setMaxAge($maxAge);
         return $response;
     } catch (\Exception $e) {
         ob_end_clean();
         throw $e;
     }
 }
Example #23
0
 /**
  * @return Response
  */
 public function generateResponse()
 {
     $this->render();
     $response = new Response();
     $response->headers->addCacheControlDirective('no-store');
     $response->headers->addCacheControlDirective('no-cache');
     $response->headers->addCacheControlDirective('must-revalidate');
     $response->headers->addCacheControlDirective('post-check', 0);
     $response->headers->addCacheControlDirective('pre-check', 0);
     $response->headers->set('Pragma', 'no-cache');
     $response->setLastModified(new \DateTime());
     $response->setExpires(new \DateTime());
     if ($this->imageContent) {
         $response->setContent($this->imageContent);
     } else {
         ob_start();
         switch (strtoupper($this->config['format'])) {
             case 'JPEG':
             case 'JPG':
                 $response->headers->set('Content-Type', 'image/jpeg');
                 imagejpeg($this->image, null, 90);
                 break;
             case 'GIF':
                 $response->headers->set('Content-Type', 'image/gif');
                 imagegif($this->image);
                 break;
             default:
                 $response->headers->set('Content-Type', 'image/png');
                 imagepng($this->image);
                 break;
         }
         $content = ob_get_clean();
         $response->setContent($content);
         imagedestroy($this->image);
     }
     switch (strtoupper($this->config['format'])) {
         case 'JPEG':
         case 'JPG':
             $response->headers->set('Content-Type', 'image/jpeg');
             break;
         case 'GIF':
             $response->headers->set('Content-Type', 'image/gif');
             break;
         default:
             $response->headers->set('Content-Type', 'image/png');
             break;
     }
     return $response;
 }
Example #24
0
    /**
     * Maps headers sent by the legacy stack to $response.
     *
     * @param array $headers Array headers.
     * @param \Symfony\Component\HttpFoundation\Response $response
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function mapHeaders( array $headers, Response $response )
    {
        foreach ( $headers as $header )
        {
            $headerArray = explode( ": ", $header, 2 );
            $headerName = strtolower( $headerArray[0] );
            $headerValue = $headerArray[1];
            // Removing existing header to avoid duplicate values
            $this->removeHeader( $headerName );

            switch ( $headerName )
            {
                // max-age and s-maxage are skipped because they are values of the cache-control header
                case "etag":
                    $response->setEtag( $headerValue );
                    break;
                case "last-modified":
                    $response->setLastModified( new DateTime( $headerValue ) );
                    break;
                case "expires":
                    $response->setExpires( new DateTime( $headerValue ) );
                    break;
                default;
                    $response->headers->set( $headerName, $headerValue, true );
                    break;
            }
        }

        return $response;
    }
 public function testSetExpires()
 {
     $response = new Response();
     $response->setExpires(null);
     $this->assertNull($response->getExpires(), '->setExpires() remove the header when passed null');
     $now = new \DateTime();
     $response->setExpires($now);
     $this->assertEquals($response->getExpires()->getTimestamp(), $now->getTimestamp());
 }
Example #26
0
 public function getTranslationsAction(Request $request, $domain, $_format)
 {
     $locales = $this->getLocales($request);
     if (0 === count($locales)) {
         throw new NotFoundHttpException();
     }
     $cache = new ConfigCache(sprintf('%s/%s.%s.%s', $this->cacheDir, $domain, implode('-', $locales), $_format), $this->debug);
     if (!$cache->isFresh()) {
         $resources = array();
         $translations = array();
         foreach ($locales as $locale) {
             $translations[$locale] = array();
             $files = $this->translationFinder->get($domain, $locale);
             if (1 > count($files)) {
                 continue;
             }
             $translations[$locale][$domain] = array();
             foreach ($files as $filename) {
                 $extension = pathinfo($filename, \PATHINFO_EXTENSION);
                 if (isset($this->loaders[$extension])) {
                     $resources[] = new FileResource($filename);
                     $catalogue = $this->loaders[$extension]->load($filename, $locale, $domain);
                     $translations[$locale][$domain] = array_replace_recursive($translations[$locale][$domain], $catalogue->all($domain));
                 }
             }
         }
         $content = $this->engine->render('BazingaJsTranslationBundle::getTranslations.' . $_format . '.twig', array('fallback' => $this->localeFallback, 'defaultDomain' => $this->defaultDomain, 'translations' => $translations, 'include_config' => true));
         try {
             $cache->write($content, $resources);
         } catch (IOException $e) {
             throw new NotFoundHttpException();
         }
     }
     if (method_exists($cache, 'getPath')) {
         $cachePath = $cache->getPath();
     } else {
         $cachePath = (string) $cache;
     }
     $expirationTime = new \DateTime();
     $expirationTime->modify('+' . $this->httpCacheTime . ' seconds');
     $response = new Response(file_get_contents($cachePath), 200, array('Content-Type' => $request->getMimeType($_format)));
     $response->prepare($request);
     $response->setPublic();
     $response->setETag(md5($response->getContent()));
     $response->isNotModified($request);
     $response->setExpires($expirationTime);
     return $response;
 }
 /**
  * Get the topic of MAL.
  *
  * @param Request $request HTTP Request object
  * @param int     $id      The ID of the forum topic as assigned by MyAnimeList
  *
  * @return View
  */
 public function getForumTopicAction(Request $request, $id)
 {
     // http://myanimelist.net/forum/?topicid=#{id}
     $page = (int) $request->query->get('page');
     if ($page <= 0) {
         $page = 1;
     }
     if ((int) $id == '') {
         return $this->view(array('error' => 'Invalid topic ID'), 200);
     }
     $downloader = $this->get('atarashii_api.communicator');
     try {
         $forumcontent = $downloader->fetch('/forum/?topicid=' . $id . '&show=' . ($page * 50 - 50));
     } catch (Exception\CurlException $e) {
         return $this->view(array('error' => 'network-error'), 500);
     }
     $forumtopic = ForumParser::parseTopic($forumcontent);
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge(300);
     //5 minutes
     $response->headers->addCacheControlDirective('must-revalidate', true);
     $response->setEtag('forum/topic/' . $id);
     //Also, set "expires" header for caches that don't understand Cache-Control
     $date = new \DateTime();
     $date->modify('+300 seconds');
     //5 minutes
     $response->setExpires($date);
     $view = $this->view($forumtopic);
     $view->setResponse($response);
     $view->setStatusCode(200);
     return $view;
 }
 /**
  * Fetch Top-rated Manga by Popularity.
  *
  * Gets a list of the top-rated manga on MyAnimeList sorted by popularity. The get
  * variable "page" is used to select the set of results to return (in a default of 30
  * items per set). An invalid or missing value defaults to page 1.
  *
  * @param string  $apiVersion The API version of the request
  * @param Request $request    Contains all the needed information to get the list.
  *
  * @return View
  */
 public function getPopularMangaAction($apiVersion, Request $request)
 {
     // http://myanimelist.net/topmanga.php?type=bypopularity&limit=#{0}
     $page = (int) $request->query->get('page');
     if ($page <= 0) {
         $page = 1;
     }
     $downloader = $this->get('atarashii_api.communicator');
     try {
         $mangacontent = $downloader->fetch('/topmanga.php?type=bypopularity&limit=' . ($page * 50 - 50));
     } catch (Exception\CurlException $e) {
         return $this->view(array('error' => 'network-error'), 500);
     }
     $response = new Response();
     $serializationContext = SerializationContext::create();
     $serializationContext->setVersion($apiVersion);
     //For compatibility, API 1.0 explicitly passes null parameters.
     if ($apiVersion == '1.0') {
         $serializationContext->setSerializeNull(true);
     }
     $response->setPublic();
     $response->setMaxAge(10800);
     //Three hours
     $response->headers->addCacheControlDirective('must-revalidate', true);
     $response->setEtag('manga/popular?page=' . urlencode($page));
     //Also, set "expires" header for caches that don't understand Cache-Control
     $date = new \DateTime();
     $date->modify('+10800 seconds');
     //Three hours
     $response->setExpires($date);
     if (strpos($mangacontent, 'No manga titles') !== false) {
         $view = $this->view(array('error' => 'not-found'));
         $view->setResponse($response);
         $view->setStatusCode(404);
         return $view;
     } else {
         $popularmanga = Top::parse($mangacontent, 'manga');
         $view = $this->view($popularmanga);
         $view->setSerializationContext($serializationContext);
         $view->setResponse($response);
         $view->setStatusCode(200);
         return $view;
     }
 }
 /**
  * Disable caching in ancient browsers and for HTTP/1.0 proxies and clients.
  *
  * HTTP/1.0 proxies do not support the Vary header, so prevent any caching by
  * sending an Expires date in the past. HTTP/1.1 clients ignore the Expires
  * header if a Cache-Control: max-age= directive is specified (see RFC 2616,
  * section 14.9.3).
  *
  * @param \Symfony\Component\HttpFoundation\Response $response
  *   A response object.
  */
 protected function setExpiresNoCache(Response $response)
 {
     $response->setExpires(\DateTime::createFromFormat('j-M-Y H:i:s T', '19-Nov-1978 05:00:00 GMT'));
 }
Example #30
0
 /**
  * Returns content of the chat button.
  *
  * @param Request $request
  * @return string Rendered page content
  */
 public function indexAction(Request $request)
 {
     $referer = $request->server->get('HTTP_REFERER', '');
     // We need to display message about visited page only if the visitor
     // really change it.
     $new_page = empty($_SESSION[SESSION_PREFIX . 'last_visited_page']) || $_SESSION[SESSION_PREFIX . 'last_visited_page'] != $referer;
     // Display message about page change
     if ($referer && isset($_SESSION[SESSION_PREFIX . 'threadid']) && $new_page) {
         $thread = Thread::load($_SESSION[SESSION_PREFIX . 'threadid']);
         if ($thread && $thread->state != Thread::STATE_CLOSED) {
             $msg = getlocal("Visitor navigated to {0}", array($referer), $thread->locale, true);
             $thread->postMessage(Thread::KIND_FOR_AGENT, $msg);
         }
     }
     $_SESSION[SESSION_PREFIX . 'last_visited_page'] = $referer;
     $image = $request->query->get('i', '');
     if (!preg_match("/^\\w+\$/", $image)) {
         $image = 'mibew';
     }
     $lang = $request->query->get('lang', '');
     if (!preg_match("/^[\\w-]{2,5}\$/", $lang)) {
         $lang = '';
     }
     if (!$lang || !locale_is_available($lang)) {
         $lang = get_current_locale();
     }
     $group_id = $request->query->get('group', '');
     if (!preg_match("/^\\d{1,8}\$/", $group_id)) {
         $group_id = false;
     }
     if ($group_id) {
         if (Settings::get('enablegroups') == '1') {
             $group = group_by_id($group_id);
             if (!$group) {
                 $group_id = false;
             }
         } else {
             $group_id = false;
         }
     }
     // Get image file content
     $image_postfix = has_online_operators($group_id) ? "on" : "off";
     $file_name = "locales/{$lang}/button/{$image}_{$image_postfix}.png";
     $content_type = 'image/png';
     if (!is_readable($file_name)) {
         // Fall back to .gif image
         $file_name = "locales/{$lang}/button/{$image}_{$image_postfix}.gif";
         $content_type = 'image/gif';
     }
     $fh = fopen($file_name, 'rb');
     if ($fh) {
         // Create response with image in body
         $file_size = filesize($file_name);
         $content = fread($fh, $file_size);
         fclose($fh);
         $response = new Response($content, 200);
         // Set correct content info
         $response->headers->set('Content-Type', $content_type);
         $response->headers->set('Content-Length', $file_size);
     } else {
         $response = new Response('Not found', 404);
     }
     // Disable caching
     $response->headers->addCacheControlDirective('no-cache', true);
     $response->headers->addCacheControlDirective('no-store', true);
     $response->headers->addCacheControlDirective('must-revalidate', true);
     $response->setExpires(new \DateTime('yesterday noon'));
     $response->headers->set('Pragma', 'no-cache');
     return $response;
 }