setPublic() public method

It makes the response eligible for serving other clients.
public setPublic ( ) : Response
return Response
Ejemplo n.º 1
0
 public function testDisableCache()
 {
     // disable cache
     $this->structure->getCacheLifeTime()->willReturn(0);
     $this->response->setPublic()->shouldNotBeCalled();
     $this->response->setMaxAge($this->maxAge)->shouldNotBeCalled();
     $this->response->setSharedMaxAge($this->sharedMaxAge)->shouldNotBeCalled();
     $this->handler->updateResponse($this->response->reveal(), $this->structure->reveal());
 }
Ejemplo n.º 2
0
 /**
  * Constructor
  *
  * @param IrisEntityManager $irisEntityManager
  * @param Cache $cache
  * @param int $httpCacheMaxAgeInSeconds
  */
 public function __construct(IrisEntityManager $irisEntityManager, Cache $cache, $httpCacheMaxAgeInSeconds = 3600)
 {
     $this->irisEntityManager = $irisEntityManager;
     $this->cache = $cache;
     $this->httpCacheMaxAgeInSeconds = $httpCacheMaxAgeInSeconds;
     // Set up response with public cache parameters
     $this->response = new Response();
     $this->response->setPublic()->setMaxAge($httpCacheMaxAgeInSeconds)->setSharedMaxAge($httpCacheMaxAgeInSeconds);
 }
 /**
  * Constructor
  *
  * @param SystemBrand $systemBrandService
  * @param int $httpCacheMaxAgeInSeconds
  */
 public function __construct(SystemBrand $systemBrandService, $httpCacheMaxAgeInSeconds = 3600)
 {
     $this->systemBrandService = $systemBrandService;
     $this->irisEntityManager = $this->systemBrandService->irisEntityManager;
     $this->cache = $this->systemBrandService->cache;
     $this->httpCacheMaxAgeInSeconds = $httpCacheMaxAgeInSeconds;
     // Set up response with public cache parameters
     $this->response = new Response();
     $this->response->setPublic()->setMaxAge($httpCacheMaxAgeInSeconds)->setSharedMaxAge($httpCacheMaxAgeInSeconds);
 }
Ejemplo n.º 4
0
Archivo: Server.php Proyecto: 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;
 }
Ejemplo n.º 5
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);
 }
Ejemplo n.º 6
0
 /**
  * @Route("/{_locale}", name="donate_front_home", defaults={"_locale"="fr"}, requirements = {"_locale" = "fr|en"})
  */
 public function indexAction(Request $request, $_locale)
 {
     //cache validation tjrs public, c'est l'ESI qui gère la sidebar
     $response = new Response();
     $response->setPublic();
     $response->setSharedMaxAge(3600);
     $data = new Customer();
     $layoutMgr = $this->get('donate_core.layout.manager');
     $layout = $layoutMgr->getDefault($_locale);
     $form = $this->createForm(new DonationType($this->get('translator')), $data, array('civilities' => $this->getParameter('donate_front.form.civility'), 'equivalences' => $this->get('donate_core.equivalence.factory')->getAll(), 'payment_methods' => $this->get('donate_core.payment_method_discovery')->getEnabledMethods(), 'affectations' => $layout->getAffectations()));
     $form->handleRequest($request);
     if ($form->isValid()) {
         $intentMgr = $this->get('donate_core.intent_manager');
         $paymentMethods = $this->get('donate_core.payment_method_discovery')->getEnabledMethods();
         foreach ($paymentMethods as $pm) {
             if ($form->get('payment_method')->get($pm->getId())->isClicked()) {
                 $amount = $form->get('tunnels')->get($pm->getTunnel())->getData();
                 $intent = $intentMgr->newIntent($amount, $pm->getId());
                 $intent->setFiscalReceipt($form['erf']->getData());
                 //add affectation if any
                 $intent->setAffectationCode($form['affectations']->getData());
                 $data->addIntent($intent);
                 $em = $this->getDoctrine()->getManager();
                 $em->persist($data);
                 $em->flush();
                 $response = $intentMgr->handle($intent);
                 return $response;
             }
         }
     }
     return $this->render('DonateFrontBundle:Form:index.html.twig', array('form' => $form->createView()), $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);
 }
 function apidocAction()
 {
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge($this->container->getParameter('cache_expiration'));
     return $this->render('AppBundle:Default:apidoc.html.twig', array("pagetitle" => "API documentation"), $response);
 }
Ejemplo n.º 9
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;
 }
Ejemplo n.º 10
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);
 }
 /**
  * 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;
     }
 }
Ejemplo n.º 12
0
 public function indexAction()
 {
     $response = new Response($this->dumper->dump(), 200, array('Content-Type' => 'application/xml'));
     $response->setPublic();
     $response->setClientTtl($this->httpCache['ttl']);
     return $response;
 }
Ejemplo n.º 13
0
 /**
  * @param integer $fichaTec
  * @param string $dimension
  * @Get("/rest-service/data/{id}/{dimension}", options={"expose"=true})
  * @Rest\View
  */
 public function getIndicadorAction(FichaTecnica $fichaTec, $dimension)
 {
     $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());
     $response->setLastModified($this->get('kernel')->getEnvironment() == 'dev' ? new \DateTime('NOW') : $fichaTec->getUltimaLectura());
     $response->setPublic();
     // 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();
         $filtro = $this->getRequest()->get('filtro');
         $verSql = $this->getRequest()->get('ver_sql') == 'true' ? true : false;
         if ($filtro == null or $filtro == '') {
             $filtros = null;
         } else {
             $filtrObj = json_decode($filtro);
             foreach ($filtrObj as $f) {
                 $filtros_dimensiones[] = $f->codigo;
                 $filtros_valores[] = $f->valor;
             }
             $filtros = array_combine($filtros_dimensiones, $filtros_valores);
         }
         $em = $this->getDoctrine()->getManager();
         $fichaRepository = $em->getRepository('IndicadoresBundle:FichaTecnica');
         $fichaRepository->crearIndicador($fichaTec, $dimension, $filtros);
         $resp['datos'] = $fichaRepository->calcularIndicador($fichaTec, $dimension, $filtros, $verSql);
         $response->setContent(json_encode($resp));
         return $response;
     }
 }
Ejemplo n.º 14
0
 /**
  * @Route("/catalog/fulltree", name="spb_shop_catalog_fulltree")
  */
 public function fullTreeAction()
 {
     $em = $this->getDoctrine()->getManager();
     $repo = $em->getRepository('SpbShopBundle:Category');
     $controller = $this;
     $options = array('decorate' => true, 'rootOpen' => '<ul class="dropdown-menu">', 'rootClose' => '</ul>', 'childOpen' => function ($child) {
         if ($child['rgt'] - $child['lft'] == 1) {
             return '<li>';
         } else {
             return '<li class="dropdown-submenu">';
         }
     }, 'childClose' => '</li>', 'nodeDecorator' => function ($node) use(&$controller) {
         return '<a href="' . $controller->generateUrl('spb_shop_catalog_category', array('slug' => $node['slug'], 'tag' => $node['tag'])) . '">' . $node['title'] . '</a>';
     });
     $htmlTree = $repo->childrenHierarchy(null, false, $options);
     $response = new Response($htmlTree);
     // пометить ответ как public или private
     $response->setPublic();
     //$response->setPrivate();
     //
     // установить max age для private и shared ответов
     $response->setMaxAge(6000);
     $response->setSharedMaxAge(6000);
     // установить специальную директиву Cache-Control
     $response->headers->addCacheControlDirective('must-revalidate', true);
     return $response;
 }
Ejemplo n.º 15
0
 /**
  * Renders the tag.
  *
  * @param \Netgen\TagsBundle\API\Repository\Values\Tags\Tag $tag
  * @param \Symfony\Component\HttpFoundation\Request $request
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 protected function renderTag(Tag $tag, Request $request)
 {
     $configResolver = $this->getConfigResolver();
     if ($this->adapter instanceof TagAdapterInterface) {
         $this->adapter->setTag($tag);
     }
     $pager = new Pagerfanta($this->adapter);
     $pager->setMaxPerPage($configResolver->getParameter('tag_view.related_content_list.limit', 'eztags'));
     $pager->setCurrentPage($request->get('page', 1));
     $response = new Response();
     $response->headers->set('X-Tag-Id', $tag->id);
     if ($configResolver->getParameter('tag_view.cache', 'eztags') === true) {
         $response->setPublic();
         if ($configResolver->getParameter('tag_view.ttl_cache', 'eztags') === true) {
             $response->setSharedMaxAge($configResolver->getParameter('tag_view.default_ttl', 'eztags'));
         }
         // Make the response vary against X-User-Hash header ensures that an HTTP
         // reverse proxy caches the different possible variations of the
         // response as it can depend on user role for instance.
         if ($request->headers->has('X-User-Hash')) {
             $response->setVary('X-User-Hash');
         }
         $response->setLastModified($tag->modificationDate);
     }
     return $this->render($configResolver->getParameter('tag_view.template', 'eztags'), array('tag' => $tag, 'pager' => $pager), $response);
 }
 public function sitemapAction()
 {
     $ttl = 3600 * 6;
     $response = new Response();
     $response->headers->set('Content-Type', 'text/xml');
     $response->setPublic();
     $response->setSharedMaxAge($ttl);
     $siteaccessName = $this->container->get('ezpublish.siteaccess')->name;
     $cacheFile = $this->container->getParameter('kernel.cache_dir') . '/sitemap_' . $siteaccessName . '.xml';
     $cacheFileMtime = 0;
     if (file_exists($cacheFile)) {
         $cacheFileMtime = stat($cacheFile)['mtime'];
     }
     if ($cacheFileMtime < time() - $ttl) {
         $urls = array();
         $hostname = $this->getRequest()->getHost();
         $publishToolsService = $this->get('cjw_publishtools.service.functions');
         $rootLocationId = $this->getConfigResolver()->getParameter('content.tree_root.location_id');
         $listLocations = $publishToolsService->fetchLocationListArr(array($rootLocationId), array('depth' => 10, 'limit' => 25000, 'main_location_only' => true, 'datamap' => false));
         foreach ($listLocations[$rootLocationId]['children'] as $location) {
             $loc = $this->generateUrl($location);
             $lastmod = date('c', $location->contentInfo->modificationDate->getTimestamp());
             $urls[] = array('loc' => $loc, 'lastmod' => $lastmod);
         }
         $sitemapXmlResponse = $this->render('CjwPublishToolsBundle::sitemap.xml.twig', array('urls' => $urls, 'hostname' => 'https://' . $hostname), $response);
         file_put_contents($cacheFile, $sitemapXmlResponse->getContent());
     } else {
         $sitemapXmlResponse = $response->setContent(file_get_contents($cacheFile));
     }
     return $sitemapXmlResponse;
 }
Ejemplo n.º 17
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);
 }
Ejemplo n.º 18
0
 public function render($template_name, array $content)
 {
     $response = new Response();
     $response->setContent($this->twig->render($template_name, $content));
     $response->setPublic();
     return $response;
 }
Ejemplo n.º 19
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;
 }
Ejemplo n.º 20
0
 /**
  * @Route(
  *     path="/uploads/{endpoint}/{file}",
  *     requirements={"file": ".+"},
  *     name="view_orphanage_upload"
  * )
  *
  * @return Response
  */
 public function orphanageAction(Request $request)
 {
     try {
         $orphanageStorage = $this->get('oneup_uploader.orphanage_manager')->get($request->get('endpoint'));
     } catch (\Exception $e) {
         throw $this->createNotFoundException();
     }
     $founded = false;
     foreach ($orphanageStorage->getFiles() as $file) {
         if ($file->getRelativePathname() === $request->get('file')) {
             $founded = true;
             break;
         }
     }
     if (!$founded) {
         throw $this->createNotFoundException();
     }
     $content = null;
     try {
         if (method_exists($file, 'getContents')) {
             $content = $file->getContents();
         } elseif (method_exists($file, 'getContent')) {
             $content = $file->getContent();
         } else {
             throw new \Exception();
         }
     } catch (\Exception $e) {
         throw $this->createNotFoundException();
     }
     $response = new Response();
     $response->setPublic()->setMaxAge($this::RESPONSE_MAX_AGE)->setSharedMaxAge($this::RESPONSE_SHARED_MAX_AGE)->setContent($content)->headers->add(['Content-Type' => $this->get('liip_imagine.binary.mime_type_guesser')->guess($content), 'Content-Disposition' => $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $file->getBasename())]);
     return $response;
 }
Ejemplo n.º 21
0
 public function indexAction(Request $request)
 {
     //mini formulaire d'abonnement
     $news = new Newsletter();
     $form = $this->createFormBuilder($news)->add('news', 'email')->add('Envoyer', 'submit')->getForm();
     $form->handleRequest($request);
     if ($form->isValid()) {
         $email = $news->getNews();
         $message = \Swift_Message::newInstance()->setSubject('Bonjour')->setFrom($email)->setTo('*****@*****.**')->setBody('Bonjour Fabrice cet email : ' . $email . ' souhaite un abonnement à votre newsletter, cordialement');
         $this->get('mailer')->send($message);
         return $this->redirect($this->generateUrl('front_homepage'));
     }
     $essais = $this->getCat('essais');
     $arr = $this->get('front.base.service')->recupInfo();
     $arr['essais'] = $essais;
     $arr['nav_accueil'] = ' ';
     $arr['nav_xix'] = ' ';
     $arr['nav_essais'] = 'active';
     $arr['nav_litt'] = ' ';
     $arr['nav_audio'] = ' ';
     $arr['nav_video'] = ' ';
     $arr['nav_info'] = ' ';
     $arr['newsletter'] = $form->createView();
     $response = new Response();
     if ($this->getRequest()->isMethod('GET')) {
         $response->setPublic();
         $response->setSharedMaxAge(1);
         $response->setVary(array('Accept-Encoding', 'User-Agent'));
     }
     return $this->render('FrontBundle:Essais:index.html.twig', $arr, $response);
 }
 /**
  * Obtener los datos del costeo
  * @Get("/rest-service/costos/data/{codigo}", options={"expose"=true})
  * @Rest\View
  */
 public function getDatosCosteoAction($codigo)
 {
     $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() );
     $response->setPublic();
     // 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();
     $data = $em->getRepository('CostosBundle:Formulario')->getDatosCosteo($codigo);
     if (count($data) == 0) {
         $response->setContent('{"estado" : "error", "msj": "' . $this->get('translator')->trans('_no_datos_') . '"}');
     } else {
         $response->setContent(json_encode($data));
     }
     return $response;
     //}
 }
Ejemplo n.º 23
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;
 }
Ejemplo n.º 24
0
 /**
  * @Route("/feed")
  */
 public function feedAction()
 {
     $em = $this->getDoctrine()->getManager();
     $manager = $this->getDoctrine()->getManager();
     $core = $this->getParameter('core');
     $dql = "SELECT p, pTrans FROM BlogBundle:Post p JOIN p.translations pTrans ORDER BY p.created DESC";
     $entities = $manager->createQuery($dql)->getResult();
     $rssfeed = '<?xml version="1.0" encoding="ISO-8859-1"?>';
     $rssfeed .= '<rss version="2.0">';
     $rssfeed .= '<channel>';
     $rssfeed .= '<title>Kundalini Woman RSS feed</title>';
     $rssfeed .= '<link>http://www.undaliniwoman.com</link>';
     $rssfeed .= '<description>This is an example Kundalini Woman RSS feed</description>';
     $rssfeed .= '<language>en-us</language>';
     $rssfeed .= '<copyright>Copyright (C) 2009 mywebsite.com</copyright>';
     foreach ($entities as $value) {
         $rssfeed .= '<item>';
         $rssfeed .= '<title>' . utf8_decode($value->getTitle()) . '</title>';
         $rssfeed .= '<description>' . utf8_decode($value->getDescription()) . '</description>';
         $rssfeed .= '<link>' . $core['server_base_url'] . $this->generateUrl('blog_blog_show', array('slug' => $value->getSlug())) . '</link>';
         $rssfeed .= '<pubDate>' . $value->getCreated()->format("D, d M Y H:i:s O") . '</pubDate>';
         $rssfeed .= '</item>';
     }
     $rssfeed .= '</channel>';
     $rssfeed .= '</rss>';
     $response = new Response($rssfeed);
     $response->headers->set('Content-Type', 'application/rss+xml');
     $response->setPublic();
     $response->setMaxAge(3600);
     $now = new DateTime();
     $response->setLastModified($now);
     return $response;
 }
Ejemplo n.º 25
0
 public function importAction()
 {
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge($this->container->getParameter('long_cache'));
     return $this->render('NetrunnerdbBuilderBundle:Builder:directimport.html.twig', array('pagetitle' => "Import a deck", 'locales' => $this->renderView('NetrunnerdbCardsBundle:Default:langs.html.twig')), $response);
 }
Ejemplo n.º 26
0
 public function indexAction($campaignHash, $platformHash, $isNextButton)
 {
     if ($campaignHash === 'next') {
         $campaign = null;
     } else {
         $campaignRepo = $this->em->getRepository('VifeedCampaignBundle:Campaign');
         $campaign = $campaignRepo->findOneBy(['hashId' => $campaignHash]);
         if (!$campaign) {
             throw $this->createNotFoundException('The video is not found');
         }
         if (!$campaign->getUser()->isEnabled()) {
             throw $this->createNotFoundException();
         }
     }
     $platformRepo = $this->em->getRepository('VifeedPlatformBundle:Platform');
     $platform = $platformRepo->findOneBy(['hashId' => $platformHash]);
     if ($platform && !$platform->getUser()->isEnabled()) {
         throw $this->createNotFoundException();
     }
     $videoHash = $campaign ? $campaign->getHash() : null;
     $meta = $this->getMeta($campaign);
     $meta['og:url'] = $this->get('router')->generate('vifeed_video_promo_homepage', ['platformHash' => $platformHash, 'campaignHash' => $campaignHash, 'domain' => $this->container->getParameter('promo_domain')]);
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge(60 * 60 * 3);
     return $this->render('VifeedVideoPromoBundle:Default:index.html.twig', ['platformHash' => $platformHash, 'campaignHash' => $campaignHash, 'campaignTitle' => $campaign ? $campaign->getName() : null, 'campaignDescription' => $campaign ? $campaign->getDescription() : null, 'videoHash' => $videoHash, 'nextBtn' => $isNextButton, 'meta' => $meta], $response);
 }
 /**
  * Controller  for top menu
  * @param int $currentLocationId
  *
  * @return Response
  */
 public function topMenuAction($currentLocationId)
 {
     $rootLocationId = $this->getConfigResolver()->getParameter('content.tree_root.location_id');
     $response = new Response();
     $parameters = array();
     $helper = $this->get('bananamanu_simple_design.subelement_helper');
     $menu = $helper->getSubElementLocation($rootLocationId);
     // Get current master
     try {
         $currentLocation = $this->getRepository()->getLocationService()->loadLocation($currentLocationId);
         $pathString = explode('/', $currentLocation->pathString);
         if ((int) $pathString[3] > 0) {
             $currentMasterLocationId = $pathString[3];
         } else {
             $currentMasterLocationId = $rootLocationId;
         }
     } catch (\Exception $e) {
         $currentMasterLocationId = $rootLocationId;
     }
     // Get current user
     $user = $this->getRepository()->getCurrentUser();
     // Cache control
     $response->setSharedMaxAge(84600);
     $response->setVary('X-User-Hash');
     $response->setPublic();
     $parameters['menu'] = $menu;
     $parameters['user'] = $user;
     $parameters['currentMasterLocationId'] = $currentMasterLocationId;
     return $this->render('BananamanuSimpleDesignBundle::page_topmenu.html.twig', $parameters, $response);
 }
Ejemplo n.º 28
0
 function apiIntroAction()
 {
     $response = new Response();
     $response->setPublic();
     $response->setMaxAge($this->container->getParameter('cache_expiration'));
     return $this->render('AppBundle:Default:apiIntro.html.twig', array("pagetitle" => "API", "game_name" => $this->container->getParameter('game_name'), "publisher_name" => $this->container->getParameter('publisher_name')), $response);
 }
Ejemplo n.º 29
0
 /**
  * Index Action
  *
  * @return Response
  */
 public function indexAction()
 {
     $response = new Response();
     $response->setPublic();
     $response->setSharedMaxAge(86400);
     // 1 day
     return $this->render('UnifikSystemBundle:Frontend/Home:index.html.twig', [], $response);
 }
 /**
  * Set response status
  * 
  * @param Response $response
  * @param string   $status
  */
 protected function setResponseStatus(Response $response, $status)
 {
     if (CacheableInterface::CACHE_PUBLIC == $status) {
         $response->setPublic();
     } else {
         $response->setPrivate();
     }
 }