Exemplo n.º 1
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.º 2
0
 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);
 }
Exemplo n.º 3
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.º 4
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.º 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;
 }
Exemplo n.º 6
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;
 }
 /**
  * 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.º 8
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.º 9
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.º 10
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;
 }
Exemplo n.º 11
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;
 }
Exemplo n.º 12
0
 public function indexAction($enabledSlides)
 {
     $response = new Response();
     $response->setPublic();
     $response->setSharedMaxAge(100800);
     $response->setETag(md5('public'));
     if ($response->isNotModified($this->getRequest())) {
         return $response;
     }
     $slides = ['main' => ['type' => 'advertiser', 'title' => 'Как это работает', 'text' => 'Zombakka — это простая и быстрая платформа<br>для продвижения ваших видео.', 'btnTitle' => 'Узнать больше'], 'music' => ['type' => 'advertiser', 'title' => 'Для музыкантов', 'text' => 'Сервис продвижения видео<br> для независимых исполнителей.', 'btnUrl' => $this->generateUrl('for_musicians'), 'btnTitle' => 'Запустить кампанию'], 'partners' => ['type' => 'advertiser', 'title' => 'Для партнеров', 'text' => 'Специальные условия для<br> рекламных агентств и партнеров.', 'btnUrl' => $this->generateUrl('for_partners'), 'btnTitle' => 'Узнать больше'], 'movies' => ['type' => 'advertiser', 'title' => 'Для фильмов', 'text' => 'Сервис для продвижения фильмов от киностудий<br> или независимых режиссеров.', 'btnUrl' => $this->generateUrl('for_movies'), 'btnTitle' => 'Запустить кампанию'], 'games' => ['type' => 'advertiser', 'title' => 'Для игр', 'text' => 'Сервис для продвижения игр от ведущих<br> издателей или инди разработчиков.', 'btnUrl' => $this->generateUrl('for_games'), 'btnTitle' => 'Запустить кампанию'], 'companies' => ['type' => 'advertiser', 'title' => 'Для компаний', 'text' => 'Сервис для продвижения брендов<br> вирусными технологиями.', 'btnUrl' => $this->generateUrl('for_companies'), 'btnTitle' => 'Запустить кампанию'], 'publishers' => ['type' => 'publisher', 'title' => 'Для владельцев площадок', 'text' => 'Сервис для безграничного заработка<br> на просмотрах видео, размещенных на ваших площадках.', 'btnUrl' => $this->generateUrl('for_publishers'), 'btnTitle' => 'Начать зарабатывать']];
     foreach ($slides as $key => $slide) {
         if (!in_array($key, $enabledSlides)) {
             unset($slides[$key]);
         }
     }
     return $this->render('VifeedFrontendBundle:Public:carousel.html.twig', ['slides' => $slides], $response);
 }
Exemplo n.º 13
0
 public function indexAction($enabledVideos)
 {
     $response = new Response();
     $response->setPublic();
     $response->setSharedMaxAge(100800);
     $response->setETag(md5('public'));
     if ($response->isNotModified($this->getRequest())) {
         return $response;
     }
     $videos = ['films' => ['title' => 'Brick Mansions Promo', 'before' => '320 700', 'after' => '743 168'], 'films2' => ['title' => 'Несносный дед. Русский трейлер', 'before' => '215 521', 'after' => '629 878'], 'for_company1' => ['title' => 'Как остановить время', 'before' => '850 932', 'after' => '1 475 031'], 'for_company2' => ['title' => 'Шашлычок 72 или как защитить ваш офис', 'before' => '397 000', 'after' => '813 935'], 'game1' => ['title' => 'Вечеринка компании Wargaming', 'before' => '12 834', 'after' => '122 839'], 'game2' => ['title' => 'Pro Игры - Metro: Last Light', 'before' => '154 000', 'after' => '487 392'], 'music2' => ['title' => 'NuSkOOl — Lambretta', 'before' => '1 629', 'after' => '39 991'], 'music1' => ['title' => 'LITTLE BIG - Everyday I\'m drinking', 'before' => '1 789 013', 'after' => '3 610 259']];
     foreach ($videos as $key => $video) {
         if (!in_array($key, $enabledVideos)) {
             unset($videos[$key]);
         }
     }
     return $this->render('VifeedFrontendBundle:Public:videos.html.twig', ['videos' => $videos], $response);
 }
Exemplo n.º 14
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));
     }
 }
Exemplo n.º 15
0
 /**
  * Generates a JavaScript file with client-side localization constants.
  *
  * @param Request $request Incoming request.
  * @return Response Prepared JavaScript file with client side localization
  * constants.
  */
 public function indexAction(Request $request)
 {
     $locale = $request->attributes->get('locale');
     $item = $this->getCache()->getItem('translation/js/' . $locale);
     $content = $item->get(Invalidation::OLD);
     if ($item->isMiss()) {
         $item->lock();
         $messages = load_messages($locale);
         // Store JSON-encoded data to reduce count of json_encode calls.
         $content = sprintf('%s(%s);', 'Mibew.Localization.set', json_encode($messages));
         $item->set($content);
     }
     // Session is started automatically during application initialization
     // and PHP sets "Cache-Control" and "Expires" headers to forbid caching
     // and to keep the session private. In this script we actually does not
     // use session stuff, thus we can remove these headers to provide
     // caching. Notice that all headers are removed to clear "Set-Cookie"
     // header with session ID and may be some other unsafe headers that
     // must not be cached.
     header_remove();
     // The whole response body (JSON-encoded with a callback function) is
     // cached via cache backend, thus it's simpler to use Symfony's
     // Response class instead of JsonResponse.
     $response = new Response();
     $response->headers->set('Content-Type', 'text/javascript');
     // Set various cache headers
     $response->setPublic();
     $response->setMaxAge(120);
     if ($item->getCreation()) {
         // Creation field can be unavailable for some cache drivers.
         $response->setLastModified($item->getCreation());
     }
     $response->setETag(sha1($content));
     if ($response->isNotModified($request)) {
         $response->setNotModified();
         // We does not need to send content for the client. Just return 304
         // status code.
         return $response;
     }
     // Pass the whole response for the client.
     $response->setContent($content);
     return $response;
 }
Exemplo n.º 16
0
 protected function checkEndingAndEtag(Request $request, $ending, callable $callable)
 {
     if ($ending != '' && $ending != '.tpl') {
         throw $this->createNotFoundException('File Not Found');
     }
     $etag = '';
     $response = null;
     if ($ending == '.tpl') {
         if ($request->isXmlHttpRequest() || $this->container->get('kernel')->getEnvironment() == 'dev') {
             $response = new Response();
             $etag = $callable();
             $response->setETag($etag);
             if (!$response->isNotModified($request)) {
                 //is newer, need to generate a new response and cannot use the old one
                 $response = null;
             }
         } else {
             $response = new Response('partials are only available per xmlHttpRequest', Response::HTTP_BAD_REQUEST);
         }
     }
     return [$etag, $response];
 }
Exemplo n.º 17
0
 /**
  * Obtener los datos del indicador sin aplicar la fórmula ni filtros
  * @param integer $fichaTec
  * @param string $dimension
  * @Get("/rest-service/data/{id}", options={"expose"=true})
  * @Rest\View
  */
 public function getDatosIndicadorAction(FichaTecnica $fichaTec)
 {
     $response = new Response();
     // crea una respuesta con una cabecera ETag y Last-Modified
     // para determinar si se debe calcular el indicador u obtener de la caché
     // para el modo de desarrollo (dev) nunca tomar de caché
     $response->setETag($fichaTec->getId() . '_datos');
     $response->setLastModified($this->get('kernel')->getEnvironment() == 'dev' ? new \DateTime('NOW') : $fichaTec->getUltimaLectura());
     // verifica que la respuesta no se ha modificado para la petición dada
     if ($response->isNotModified($this->getRequest())) {
         // devuelve inmediatamente la respuesta 304 de la caché
         return $response;
     } else {
         $resp = array();
         $em = $this->getDoctrine()->getManager();
         $fichaRepository = $em->getRepository('IndicadoresBundle:FichaTecnica');
         $fichaRepository->crearIndicador($fichaTec);
         $resp = $fichaRepository->getDatosIndicador($fichaTec);
         $respj = json_encode($resp);
         $response->setContent($respj);
         return $response;
     }
 }
Exemplo n.º 18
0
 /**
  * Render a content page without the body. Used for ajax calls.
  *
  * @param Request $request
  * @param         $path
  *
  * @return Response
  */
 public function contentAction(Request $request, $path)
 {
     $pageInfo = $this->reader->getInfo($path . '.md');
     $response = new Response();
     $response->setETag($pageInfo->getEtag());
     $lastModified = $pageInfo->getLastModified();
     if ($this->assetsVersion - $pageInfo->getLastModified()->getTimestamp() > 0) {
         $lastModified = new \DateTime('@' . $this->assetsVersion);
     }
     $response->setLastModified($lastModified);
     $response->setPublic();
     if ($response->isNotModified($request)) {
         return $response;
     }
     $p = $this->reader->getPage($path . '.md');
     $response->setContent($p->getContent());
     return $response;
 }
 /**
  * Factory method that creates a response for translations.
  *
  * @param Request $request
  * @param string $content
  * @param string $format
  * @return Response
  */
 private function createResponse(Request $request, $content, $format)
 {
     $expirationTime = new \DateTime("+{$this->httpCacheTime} seconds");
     $response = new Response($content, 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;
 }
Exemplo n.º 20
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;
 }
Exemplo n.º 21
0
 /**
  * exposeTranslationAction action.
  */
 public function exposeTranslationAction(Request $request, $domain_name, $_locale, $_format)
 {
     $cache = new ConfigCache($this->cacheDir . '/' . $domain_name . '.' . $_locale . '.' . $_format, $this->debug);
     if (!$cache->isFresh()) {
         $locales = $this->translationFinder->createLocalesArray(array($this->localeFallback, $_locale));
         $files = array();
         foreach ($locales as $locale) {
             foreach ($this->translationFinder->getResources($domain_name, $locale) as $file) {
                 $files[] = $file;
             }
         }
         $resources = array();
         $catalogues = array();
         foreach ($files as $file) {
             $extension = pathinfo($file->getFilename(), \PATHINFO_EXTENSION);
             if (isset($this->loaders[$extension])) {
                 $resources[] = new FileResource($file->getPath());
                 $catalogues[] = $this->loaders[$extension]->load($file, $_locale, $domain_name);
             }
         }
         $messages = array();
         foreach ($catalogues as $catalogue) {
             $messages = array_replace_recursive($messages, $catalogue->all());
         }
         $content = $this->engine->render('BazingaExposeTranslationBundle::exposeTranslation.' . $_format . '.twig', array('messages' => $messages, 'locale' => $_locale, 'defaultDomains' => $this->defaultDomains));
         $cache->write($content, $resources);
     }
     $content = file_get_contents((string) $cache);
     $response = new Response($content);
     $response->prepare($request);
     $response->setPublic();
     $response->setETag(md5($response->getContent()));
     $response->isNotModified($request);
     return $response;
 }
 /**
  * @param $articleSlug
  * @param Request $request
  * @return Response
  * @Route(
  *      "/article/slug/{articleSlug}",
  *      defaults={"articleSlug": "Article slug"},
  * )
  */
 public function showActionCache($articleSlug, Request $request)
 {
     // Get the minimum information to compute
     // the ETag or the Last-Modified value
     // (based on the Request, data is retrieved from
     // a database or a key-value store for instance)
     $article = $this->showAction($articleSlug);
     //        $article = array('key' => $articleSlug);
     // create a Response with an ETag and/or a Last-Modified header
     $response = new Response();
     $response->setETag($article->getEtag());
     //computeETag());//->getContent());
     $response->setLastModified($article->getLastModified());
     //PublishedAt());
     // Set response as public. Otherwise it will be private by default.
     $response->setPublic();
     // Check that the Response is not modified for the given Request
     if ($response->isNotModified($request)) {
         // return the 304 Response immediately
         return $response;
     }
     // do more work here - like retrieving more data
     $comments = 'comment 1';
     // or render a template with the $response you've already started
     return $this->render('article/show.html.twig', array('article' => $article, 'comments' => $comments), $response);
 }
Exemplo n.º 23
0
 public function JSONResponse($jsonString, $etag)
 {
     $response = new Response();
     $response->setETag($etag);
     $response->setLastModified(new \DateTime());
     // Set response as public. Otherwise it will be private by default.
     $response->setPublic();
     $response->headers->set('Content-Type', 'application/json');
     // Check that the Response is not modified for the given Request
     if ($response->isNotModified($this->getRequest())) {
         // return the 304 Response immediately
         return $response;
     }
     $response->setContent($jsonString);
     return $response;
 }
Exemplo n.º 24
0
 protected function handleCacheOptions($pageName, Context $context, Response $response, array $config)
 {
     $response->setExpires(new \DateTime());
     if ($config['cache']['enable'] !== true) {
         return $response;
     }
     $provider = $this->getPageProvider($pageName);
     $lastModified = $provider->getLastModified($pageName, $context, $this->getSiteConfig());
     if (null !== $lastModified) {
         $date = new \DateTime();
         $date->setTimestamp($lastModified);
         $response->setLastModified($date);
     }
     $response->setMaxAge($config['cache']['lifetime']);
     $response->setSharedMaxAge($config['cache']['lifetime']);
     if ($config['cache']['public'] === true) {
         $response->setPublic();
     } else {
         $response->setPrivate();
     }
     $response->setETag(md5($pageName . $lastModified));
     return $response;
 }
Exemplo n.º 25
0
 /**
  * Provide an asset.
  *
  * @param string  $path    The assets sub dir.
  *
  * @param string  $file    The file name within the sub dir..
  *
  * @param Request $request The request to process.
  *
  * @return Response
  */
 public function assetAction($path, $file, Request $request)
 {
     $filePath = $this->getAssetsDir() . '/' . $path . '/' . $file;
     if (!file_exists($filePath)) {
         return new Response($filePath . ' not found', 404);
     }
     $response = new Response();
     $response->setPublic();
     $response->headers->addCacheControlDirective('must-revalidate', true);
     $lastModified = filemtime($filePath);
     $response->setETag(md5($filePath . $lastModified));
     $response->setLastModified(new \DateTime('@' . $lastModified));
     if ($response->isNotModified($request)) {
         // return the 304 Response immediately
         return $response;
     }
     $mime = $this->getMime($filePath);
     if ($mime !== null) {
         $response->headers->set('Content-Type', $mime);
     }
     return $response->setContent(file_get_contents($filePath));
 }
 /**
  * @Route("/upload/{type}/{uuid}.{ext}", name="sf_upload_cache", requirements={"type" = "html|file", "uuid" = "[0-9a-f]{8}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{12}", "ext" = "\w{2,5}" } )
  * @Template()
  */
 public function fileViewAction(Request $request, $type, $uuid, $ext)
 {
     $repo = $this->container->get('doctrine')->getManager()->getRepository('Symforce\\AdminBundle\\Entity\\File');
     $file = $repo->loadByUUID($uuid);
     $is_debug = $this->container->getParameter('kernel.debug');
     if ($file && $file->getSessionId() && $this->getRequest()->getSession()->getId() !== $file->getSessionId()) {
         if ($is_debug) {
             \Dev::dump($file);
         }
         return new Response('Not Found', 404, array('Content-Type' => 'text/plain'));
     }
     if (!$file) {
         return new Response('Not Found', 404, array('Content-Type' => 'text/plain'));
     }
     if ($ext !== $file->getExt()) {
         if ($is_debug) {
             \Dev::dump($file);
         }
         return new Response('Not Found', 404, array('Content-Type' => 'text/plain'));
     }
     $is_html_file = 'html' === $type;
     if ($is_html_file !== $file->getIsHtmlFile()) {
         if ($is_debug) {
             \Dev::dump($file);
         }
         return new Response('Not Found', 404, array('Content-Type' => 'text/plain'));
     }
     $response = new Response();
     $response->setPrivate();
     $response->setMaxAge(600);
     $response->setSharedMaxAge(600);
     // set a custom Cache-Control directive
     $response->headers->addCacheControlDirective('must-revalidate', true);
     $date = $file->getUpdated();
     $response->setETag($date->getTimestamp());
     $response->setLastModified($date);
     if ($response->isNotModified($request)) {
         return $response;
     }
     $response->headers->set('Content-Type', $file->getType());
     $response->setContent(stream_get_contents($file->getContent()));
     return $response;
 }
Exemplo n.º 27
0
 /**
  * Page Dashboard on Backend
  */
 public function indexAction()
 {
     //        $entryData = array(
     //            'category' => 'Presse'
     //            , 'title'    => 'Article de Sarkozy :)'
     //            , 'article'  => 7
     //            , 'when'     => time()
     //        );
     //
     //// This is our new stuff
     //        $context = new \ZMQContext();
     //        $socket = $context->getSocket(\ZMQ::SOCKET_PUSH, 'pushed');
     //        $socket->connect("tcp://*****:*****@gmail.com');
     // Récupérer l'utilisateur
     $user = $this->getUser();
     //
     //        $this->get('store.backend.email')->sendparam($user, '*****@*****.**',
     //            'StoreBackendBundle:Email:welcome.html.twig', "Bienvenue :)",'*****@*****.**', '<p>okay</p>');
     //
     // Récupérer Doctrine Manager
     $em = $this->getDoctrine()->getManager();
     // Stats of counters
     $nbprod = $em->getRepository('StoreBackendBundle:Product')->getCountByUser($user);
     $nbsupp = $em->getRepository('StoreBackendBundle:Supplier')->getCountByUser($user);
     $nbcms = $em->getRepository('StoreBackendBundle:CMS')->getCountByUser($user);
     $nbcomm = $em->getRepository('StoreBackendBundle:Comment')->getCountByUser($user);
     // Turn Over
     $ca = $em->getRepository('StoreBackendBundle:Order')->getCA($user);
     //nb de product à null
     $nbprodempty = $em->getRepository('StoreBackendBundle:Product')->getNbProdEmpty($user);
     //nb de product à null
     $nblikes = $em->getRepository('StoreBackendBundle:Product')->getNbLikesByUser($user);
     //5 last comments
     $lastcommentsactifs = $em->getRepository('StoreBackendBundle:Comment')->getLastComments($user, 5, 2);
     $lastcommentsencours = $em->getRepository('StoreBackendBundle:Comment')->getLastComments($user, 5, 1);
     $lastcommentsinactifs = $em->getRepository('StoreBackendBundle:Comment')->getLastComments($user, 5, 0);
     //commandes
     $orders = $em->getRepository('StoreBackendBundle:Order')->getOrderByUser($user, 5);
     $bestcategories = $em->getRepository('StoreBackendBundle:Category')->getBestCategoryByUser($user, 5);
     //last messages
     $messages = $em->getRepository('StoreBackendBundle:Message')->getLastMessagesByUser($user, 5);
     // Chart in last 6 months
     $statorder[] = $em->getRepository('StoreBackendBundle:Order')->getNbOrderByMonth($user, new \DateTime('now'));
     $statorder[] = $em->getRepository('StoreBackendBundle:Order')->getNbOrderByMonth($user, new \DateTime('-1 month'));
     $statorder[] = $em->getRepository('StoreBackendBundle:Order')->getNbOrderByMonth($user, new \DateTime('-2 month'));
     $statorder[] = $em->getRepository('StoreBackendBundle:Order')->getNbOrderByMonth($user, new \DateTime('-3 month'));
     $statorder[] = $em->getRepository('StoreBackendBundle:Order')->getNbOrderByMonth($user, new \DateTime('-4 month'));
     $statorder[] = $em->getRepository('StoreBackendBundle:Order')->getNbOrderByMonth($user, new \DateTime('-5 month'));
     $response = new Response();
     $response->setPrivate();
     // définit une directive personnalisée du Cache-Control
     $response->headers->addCacheControlDirective('must-revalidate', true);
     $date = new \DateTime();
     $date->modify('+600 seconds');
     $response->setExpires($date);
     $response->setContent($this->renderView('StoreBackendBundle:Main:index.html.twig', array('ca' => $ca, 'nbprod' => $nbprod, 'nbprodempty' => $nbprodempty, 'lastcommentsactifs' => $lastcommentsactifs, 'lastcommentsencours' => $lastcommentsencours, 'lastcommentsinactifs' => $lastcommentsinactifs, 'bestcategories' => $bestcategories, 'messages' => $messages, 'orders' => $orders, 'nblikes' => $nblikes, 'nbsupp' => $nbsupp, 'nbcms' => $nbcms, 'nbcomm' => $nbcomm, 'statorder' => $statorder)));
     $response->setETag(md5($response->getContent()));
     // définit l'âge max des caches privés ou des caches partagés
     $response->setMaxAge(600);
     // je retourne la vue index de mon dossier Main
     return $response;
 }
Exemplo n.º 28
0
 public function feedAction()
 {
     $this->construct();
     $res = new Response();
     $etag = 'cas';
     $cacheKey = CacheManager::KEY_POSTS_ALL;
     $posts = $this->m_cacheManager->get($cacheKey, 'ArrayCollection<Aldor\\BlogBundle\\Entity\\Post>');
     if (!$posts) {
         $posts = $this->m_em->getRepository('AldorBlogBundle:Post')->getAllPostsFromCategories();
         $this->m_cacheManager->put($cacheKey, $posts, 6000, 'list');
     }
     if (count($posts)) {
         $etag = md5("post:{" . count($posts) . "}:" . $this->m_cacheManager->get($cacheKey));
         $res->setETag($etag);
         $res->setPublic();
         if ($res->isNotModified($this->get('request'))) {
             $res->headers->set('Content-Type', 'application/rss+xml');
             return $res;
         }
     }
     $feed = $this->get('eko_feed.feed.manager')->get('posts');
     $feed->addFromArray($posts);
     $res->setContent($feed->render('atom'));
     $res->setCharset('UTF-8');
     $res->headers->set('Content-Type', 'application/xml');
     return $res;
 }