setPrivate() public method

It makes the response ineligible for serving other clients.
public setPrivate ( ) : Response
return Response
 public function indexAction(Request $request)
 {
     $response = new Response();
     $response->setPrivate();
     $response->setContent($this->twig->render('www/Index.twig', array()));
     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;
 }
 /**
  * {@inheritdoc}
  */
 public function render(BlockInterface $block, Response $response = null)
 {
     if ($this->logger) {
         $this->logger->info(sprintf('[cms::renderBlock] block.id=%d, block.type=%s ', $block->getId(), $block->getType()));
     }
     try {
         $service = $this->blockServiceManager->get($block);
         $service->load($block);
         // load the block
         $response = $service->execute($block, $response);
         if (!$response instanceof Response) {
             throw new \RuntimeException('A block service must return a Response object');
         }
     } catch (\Exception $e) {
         if ($this->logger) {
             $this->logger->crit(sprintf('[cms::renderBlock] block.id=%d - error while rendering block - %s', $block->getId(), $e->getMessage()));
         }
         if ($this->debug) {
             throw $e;
         }
         $response = new Response();
         $response->setPrivate();
     }
     return $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();
     }
 }
示例#5
0
文件: Frontend.php 项目: bolt/bolt
 /**
  * {@inheritdoc}
  */
 public function after(Request $request, Response $response)
 {
     if ($this->session()->isStarted()) {
         $response->setPrivate();
     } else {
         $sharedMaxAge = $this->getOption('general/caching/duration', 10) * 60;
         $response->setPublic()->setSharedMaxAge($sharedMaxAge);
     }
 }
 /**
  * @param Request $request
  * @param Response $response
  * @return Response
  */
 public function setCacheHeaders(Request $request, Response $response)
 {
     $response->setMaxAge($this->defaultMaxAge);
     if ($this->isLoggedIn($request) || $this->isWordpressAdminPage($request)) {
         $response->setPrivate();
     } else {
         $response->setPublic();
     }
     return $response;
 }
 /**
  * @param Request $request
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function embedAction(Request $request)
 {
     $response = new Response();
     $response->setPrivate();
     $response->setMaxAge(0);
     $response->setSharedMaxAge(0);
     $response->headers->addCacheControlDirective('must-revalidate', true);
     $response->headers->addCacheControlDirective('no-store', true);
     $response->headers->set(HttpCache::HEADER_REVERSE_PROXY_TTL, 0);
     return $this->render($this->getTemplate(Configuration::TYPE_LOGIN, Configuration::TEMPLATE_FORM_EMBED), ['user' => $this->getUser()], $response);
 }
 /**
  * @param Response $response
  * @param Request $request
  *
  * @return ResponseConfigurator
  */
 protected function setPrivateCache(Response $response, Request $request)
 {
     if (!$response->headers->hasCacheControlDirective('private')) {
         $response->setPublic();
         foreach ($this->private_headers as $private_header) {
             if ($request->headers->has($private_header)) {
                 $response->setPrivate();
                 break;
             }
         }
     }
     return $this;
 }
示例#9
0
 /**
  * /token/event.pixel
  *
  * @param string $token Event
  * @param string $event Token
  *
  * @return Response Empty response
  */
 public function addEntryAction($token, $event)
 {
     $requestQuery = $this->requestStack->getCurrentRequest()->query;
     $value = $requestQuery->get('i', 0);
     $type = (int) $requestQuery->get('t', ElcodiMetricTypes::TYPE_BEACON_ALL);
     $this->metricManager->addEntry($token, $event, $value, $type, $this->dateTimeFactory->create());
     $content = base64_decode(self::IMAGE_CONTENT);
     $response = new Response($content);
     $response->setPrivate();
     $response->headers->addCacheControlDirective('no-cache', true);
     $response->headers->addCacheControlDirective('must-revalidate', true);
     $response->headers->set('Content-Type', 'image/png');
     return $response;
 }
 /**
  * @return Response
  */
 public function getResponse()
 {
     if (null !== $this->response) {
         $this->response->setPublic();
         $this->response->setPrivate();
         $this->response->setMaxAge($this->configuration->getTtl());
         $this->response->setSharedMaxAge($this->configuration->getTtl());
         $this->response->setCharset('UTF-8');
         $this->response->prepare($this->request);
         return $this->response;
     } else {
         throw new \RuntimeException("Request had not been handled. Use handle() method before getResponse()", 1);
     }
 }
示例#11
0
 public function testIsPrivate()
 {
     $response = new Response();
     $response->headers->set('Cache-Control', 'max-age=100');
     $response->setPrivate();
     $this->assertEquals(100, $response->headers->getCacheControlDirective('max-age'), '->isPrivate() adds the private Cache-Control directive when set to true');
     $this->assertTrue($response->headers->getCacheControlDirective('private'), '->isPrivate() adds the private Cache-Control directive when set to true');
     $response = new Response();
     $response->headers->set('Cache-Control', 'public, max-age=100');
     $response->setPrivate();
     $this->assertEquals(100, $response->headers->getCacheControlDirective('max-age'), '->isPrivate() adds the private Cache-Control directive when set to true');
     $this->assertTrue($response->headers->getCacheControlDirective('private'), '->isPrivate() adds the private Cache-Control directive when set to true');
     $this->assertFalse($response->headers->hasCacheControlDirective('public'), '->isPrivate() removes the public Cache-Control directive');
 }
示例#12
0
 /**
  * @param $id
  * @param $size
  * @return Response
  */
 public function getImagePreviewAction($id, $size)
 {
     /**
      * @var Piece $piece
      */
     $piece = $this->get('jahller.artlas.repository.piece')->find($id);
     /**
      * @var Image $image
      */
     $image = $piece->getImage();
     $content = $this->get('jahller.attachment.manager.image')->getPreview($image, $size);
     $response = new Response($content, 202, array('Content-type' => 'image/png'));
     $response->setPrivate();
     /* 1 month = 2.628.000 seconds */
     $response->setMaxAge(2628000);
     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;
     }
 }
 public function infoAction(Request $request)
 {
     $jsonp = $request->query->get('jsonp');
     $locale = $request->query->get('_locale');
     if (isset($locale)) {
         $request->setLocale($locale);
     }
     $locale = $request->getLocale();
     $decklist_id = $request->query->get('decklist_id');
     $content = null;
     /* @var $user \Netrunnerdb\UserBundle\Entity\User */
     $user = $this->getUser();
     if ($user) {
         $user_id = $user->getId();
         $public_profile_url = $this->get('router')->generate('user_profile_view', array('_locale' => $this->getRequest()->getLocale(), 'user_id' => $user_id, 'user_name' => urlencode($user->getUsername())));
         $content = array('public_profile_url' => $public_profile_url, 'id' => $user_id, 'name' => $user->getUsername(), 'faction' => $user->getFaction(), 'locale' => $locale);
         if (isset($decklist_id)) {
             /* @var $em \Doctrine\ORM\EntityManager */
             $em = $this->get('doctrine')->getManager();
             /* @var $decklist \Netrunnerdb\BuilderBundle\Entity\Decklist */
             $decklist = $em->getRepository('NetrunnerdbBuilderBundle:Decklist')->find($decklist_id);
             if ($decklist) {
                 $decklist_id = $decklist->getId();
                 $dbh = $this->get('doctrine')->getConnection();
                 $content['is_liked'] = (bool) $dbh->executeQuery("SELECT\n        \t\t\t\tcount(*)\n        \t\t\t\tfrom decklist d\n        \t\t\t\tjoin vote v on v.decklist_id=d.id\n        \t\t\t\twhere v.user_id=?\n        \t\t\t\tand d.id=?", array($user_id, $decklist_id))->fetch(\PDO::FETCH_NUM)[0];
                 $content['is_favorite'] = (bool) $dbh->executeQuery("SELECT\n        \t\t\t\tcount(*)\n        \t\t\t\tfrom decklist d\n        \t\t\t\tjoin favorite f on f.decklist_id=d.id\n        \t\t\t\twhere f.user_id=?\n        \t\t\t\tand d.id=?", array($user_id, $decklist_id))->fetch(\PDO::FETCH_NUM)[0];
                 $content['is_author'] = $user_id == $decklist->getUser()->getId();
                 $content['can_delete'] = $decklist->getNbcomments() == 0 && $decklist->getNbfavorites() == 0 && $decklist->getNbvotes() == 0;
             }
         }
     }
     $content = json_encode($content);
     $response = new Response();
     $response->setPrivate();
     if (isset($jsonp)) {
         $content = "{$jsonp}({$content})";
         $response->headers->set('Content-Type', 'application/javascript');
     } else {
         $response->headers->set('Content-Type', 'application/json');
     }
     $response->setContent($content);
     return $response;
 }
 /**
  * @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']);
     }
 }
 /**
  * Filter the `core.response` event to decorate the action.
  *
  * @param FilterResponseEvent $event
  *
  * @throws InternalErrorException
  */
 public function onCoreResponse(FilterResponseEvent $event)
 {
     $cms = $this->cmsSelector->retrieve();
     $response = $event->getResponse();
     $request = $event->getRequest();
     if ($this->cmsSelector->isEditor()) {
         $response->setPrivate();
         if (!$request->cookies->has('sonata_page_is_editor')) {
             $response->headers->setCookie(new Cookie('sonata_page_is_editor', 1));
         }
     }
     $page = $cms->getCurrentPage();
     // display a validation page before redirecting, so the editor can edit the current page
     if ($page && $response->isRedirection() && $this->cmsSelector->isEditor() && !$request->get('_sonata_page_skip')) {
         $response = new Response($this->templating->render('SonataPageBundle:Page:redirect.html.twig', array('response' => $response, 'page' => $page)));
         $response->setPrivate();
         $event->setResponse($response);
         return;
     }
     if (!$this->decoratorStrategy->isDecorable($event->getRequest(), $event->getRequestType(), $response)) {
         return;
     }
     if (!$this->cmsSelector->isEditor() && $request->cookies->has('sonata_page_is_editor')) {
         $response->headers->clearCookie('sonata_page_is_editor');
     }
     if (!$page) {
         throw new InternalErrorException('No page instance available for the url, run the sonata:page:update-core-routes and sonata:page:create-snapshots commands');
     }
     // only decorate hybrid page or page with decorate = true
     if (!$page->isHybrid() || !$page->getDecorate()) {
         return;
     }
     $parameters = array('content' => $response->getContent());
     $response = $this->pageServiceManager->execute($page, $request, $parameters, $response);
     if (!$this->cmsSelector->isEditor() && $page->isCms()) {
         $response->setTtl($page->getTtl());
     }
     $event->setResponse($response);
 }
示例#17
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;
     }
 }
示例#19
0
 public function fetchTemplateAction(Request $request, $name)
 {
     $namespace = 'Default';
     // TODO make this into a feature
     $parameters = $request->query->get('parameters');
     if (!is_array($parameters) || !isset($parameters)) {
         return new Response('Client error: Expected parameters array.', 400);
     }
     try {
         // TODO return XML object with fully generated data
         $renderedTemplate = $this->container->get('templating')->render(sprintf('AchieversTempestBundle:%s:%s.html.twig', $namespace, $name), $parameters);
     } catch (\Twig_Error $e) {
         dump($e);
         $this->get('logger')->error($e);
         return new Response('Server error.', 500);
         // TODO log exception
     }
     $response = new Response($renderedTemplate, 200);
     $response->setPublic();
     $response->setPrivate();
     $response->setMaxAge(600);
     $response->setSharedMaxAge(600);
     return $response;
 }
示例#20
0
 /**
  * {@inheritdoc}
  */
 public function sendbank(OrderInterface $order)
 {
     $params = array('bank' => $this->getCode(), 'reference' => $order->getReference(), 'check' => $this->generateUrlCheck($order));
     // call the callback handler ...
     $url = $this->router->generate($this->getOption('url_callback'), $params, true);
     $response = $this->browser->get($url);
     if ($response->getContent() == 'ok') {
         $routeName = 'url_return_ok';
     } else {
         $routeName = 'url_return_ko';
         $this->logger->critical(sprintf('The CheckPayment received a ko result : %s', $response->getContent()));
     }
     // redirect the user to the correct page
     $response = new Response('', 302, array('Location' => $this->router->generate($this->getOption($routeName), $params, true)));
     $response->setPrivate();
     return $response;
 }
 function apidocAction()
 {
     $response = new Response();
     $response->setPrivate();
     return $this->render('NetrunnerdbCardsBundle:Default:apidoc.html.twig', array("pagetitle" => "API documentation"), $response);
 }
示例#22
0
 /**
  * {@inheritdoc}
  */
 public function sendbank(OrderInterface $order)
 {
     $params = array('bank' => $this->getCode(), 'reference' => $order->getReference(), 'check' => $this->generateUrlCheck($order));
     // call the callback handler ...
     $url = $this->router->generate($this->getOption('url_callback'), $params, UrlGeneratorInterface::ABSOLUTE_URL);
     $response = $this->browser->get($url);
     $routeName = $response->getContent() == 'ok' ? 'url_return_ok' : 'url_return_ko';
     // redirect the user to the correct page
     $response = new Response('', 302, array('Location' => $this->router->generate($this->getOption($routeName), $params, UrlGeneratorInterface::ABSOLUTE_URL), 'Content-Type' => 'text/plain'));
     $response->setPrivate();
     return $response;
 }
示例#23
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;
 }
示例#24
0
 public function usercommentsAction($page, Request $request)
 {
     $response = new Response();
     $response->setPrivate();
     /* @var $user \AppBundle\Entity\User */
     $user = $this->getUser();
     $limit = 100;
     if ($page < 1) {
         $page = 1;
     }
     $start = ($page - 1) * $limit;
     /* @var $dbh \Doctrine\DBAL\Driver\PDOConnection */
     $dbh = $this->getDoctrine()->getConnection();
     $comments = $dbh->executeQuery("SELECT SQL_CALC_FOUND_ROWS\n\t\t\t\tc.id,\n\t\t\t\tc.text,\n\t\t\t\tc.date_creation,\n\t\t\t\td.id decklist_id,\n\t\t\t\td.name decklist_name,\n\t\t\t\td.name_canonical decklist_name_canonical\n\t\t\t\tfrom comment c\n\t\t\t\tjoin decklist d on c.decklist_id=d.id\n\t\t\t\twhere c.user_id=?\n\t\t\t\torder by date_creation desc\n\t\t\t\tlimit {$start}, {$limit}", array($user->getId()))->fetchAll(\PDO::FETCH_ASSOC);
     $maxcount = $dbh->executeQuery("SELECT FOUND_ROWS()")->fetch(\PDO::FETCH_NUM)[0];
     // pagination : calcul de nbpages // currpage // prevpage // nextpage
     // à partir de $start, $limit, $count, $maxcount, $page
     $currpage = $page;
     $prevpage = max(1, $currpage - 1);
     $nbpages = min(10, ceil($maxcount / $limit));
     $nextpage = min($nbpages, $currpage + 1);
     $route = $request->get('_route');
     $pages = [];
     for ($page = 1; $page <= $nbpages; $page++) {
         $pages[] = array("numero" => $page, "url" => $this->generateUrl($route, array("page" => $page)), "current" => $page == $currpage);
     }
     return $this->render('AppBundle:Default:usercomments.html.twig', array('user' => $user, 'comments' => $comments, 'url' => $request->getRequestUri(), 'route' => $route, 'pages' => $pages, 'prevurl' => $currpage == 1 ? null : $this->generateUrl($route, array("page" => $prevpage)), 'nexturl' => $currpage == $nbpages ? null : $this->generateUrl($route, array("page" => $nextpage))), $response);
 }
示例#25
0
 /**
  * @param $link
  *
  * @return Response
  */
 public function displayCustomAdminBarAction(Request $request, $link)
 {
     $response = new Response();
     $response->setPrivate();
     $response->setMaxAge(900);
     if ($this->isAuthenticated($request)) {
         $content = $this->renderView('AlpixelCMSBundle:admin:blocks/admin_bar_page.html.twig', ['link' => $link]);
         $response->setContent($content);
     }
     return $response;
 }
示例#26
0
 /**
  * This method is responsible to cascade ttl to the parent block.
  *
  * @param Response              $response
  * @param BlockContextInterface $blockContext
  * @param BlockServiceInterface $service
  *
  * @return Response
  */
 protected function addMetaInformation(Response $response, BlockContextInterface $blockContext, BlockServiceInterface $service)
 {
     // a response exists, use it
     if ($this->lastResponse && $this->lastResponse->isCacheable()) {
         $response->setTtl($this->lastResponse->getTtl());
         $response->setPublic();
     } elseif ($this->lastResponse) {
         // not cacheable
         $response->setPrivate();
         $response->setTtl(0);
         $response->headers->removeCacheControlDirective('s-maxage');
         $response->headers->removeCacheControlDirective('maxage');
     }
     // no more children available in the stack, reseting the state object
     if (!$blockContext->getBlock()->hasParent()) {
         $this->lastResponse = null;
     } else {
         // contains a parent so storing the response
         $this->lastResponse = $response;
     }
     return $response;
 }
示例#27
0
 public function publishAction($deck_id, Request $request)
 {
     $response = new Response();
     $response->setPrivate();
     $response->headers->set('Content-Type', 'application/json');
     /* @var $em \Doctrine\ORM\EntityManager */
     $em = $this->get('doctrine')->getManager();
     /* @var $deck \Netrunnerdb\BuilderBundle\Entity\Deck */
     $deck = $this->getDoctrine()->getRepository('NetrunnerdbBuilderBundle:Deck')->find($deck_id);
     if ($this->getUser()->getId() != $deck->getUser()->getId()) {
         $response->setContent(json_encode(array('success' => false, 'message' => "You don't have access to this deck.")));
         return $response;
     }
     $judge = $this->get('judge');
     $analyse = $judge->analyse($deck->getCards());
     if (is_string($analyse)) {
         $response->setContent(json_encode(array('success' => false, 'message' => $judge->problem($analyse))));
         return $response;
     }
     $new_content = json_encode($deck->getContent());
     $new_signature = md5($new_content);
     $old_decklists = $this->getDoctrine()->getRepository('NetrunnerdbBuilderBundle:Decklist')->findBy(array('signature' => $new_signature));
     foreach ($old_decklists as $decklist) {
         if (json_encode($decklist->getContent()) == $new_content) {
             $response->setContent(json_encode(array('success' => false, 'message' => "That decklist already exists.")));
             return $response;
         }
     }
     $name = filter_var($request->request->get('name'), FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
     $name = substr($name, 0, 60);
     if (empty($name)) {
         $name = $deck->getName();
     }
     $rawdescription = filter_var($request->request->get('description'), FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
     if (empty($rawdescription)) {
         $rawdescription = $deck->getDescription();
     }
     $description = Markdown::defaultTransform($rawdescription);
     $decklist = new Decklist();
     $decklist->setName($name);
     $decklist->setPrettyname(preg_replace('/[^a-z0-9]+/', '-', mb_strtolower($name)));
     $decklist->setRawdescription($rawdescription);
     $decklist->setDescription($description);
     $decklist->setUser($this->getUser());
     $decklist->setCreation(new \DateTime());
     $decklist->setTs(new \DateTime());
     $decklist->setSignature($new_signature);
     $decklist->setIdentity($deck->getIdentity());
     $decklist->setFaction($deck->getIdentity()->getFaction());
     $decklist->setSide($deck->getSide());
     $decklist->setLastPack($deck->getLastPack());
     $decklist->setNbvotes(0);
     $decklist->setNbfavorites(0);
     $decklist->setNbcomments(0);
     foreach ($deck->getSlots() as $slot) {
         $card = $slot->getCard();
         $decklistslot = new Decklistslot();
         $decklistslot->setQuantity($slot->getQuantity());
         $decklistslot->setCard($card);
         $decklistslot->setDecklist($decklist);
         $decklist->getSlots()->add($decklistslot);
     }
     if (count($deck->getChildren())) {
         $decklist->setPrecedent($deck->getChildren()[0]);
     } else {
         if ($deck->getParent()) {
             $decklist->setPrecedent($deck->getParent());
         }
     }
     $decklist->setParent($deck);
     $em->persist($decklist);
     $em->flush();
     $response->setContent(json_encode(array('success' => true, 'message' => array("id" => $decklist->getId(), "url" => $this->generateUrl('decklist_detail', array('decklist_id' => $decklist->getId(), 'decklist_name' => $decklist->getPrettyName()))))));
     return $response;
 }
    $success = false;
    try {
        $imagine = new \Imagine\Gd\Imagine();
        $prefix = __DIR__ . '/../../config/';
        foreach (array('herman.original.jpg', 'robert.original.jpg') as $original) {
            $image = $imagine->open($prefix . $original);
            $image->draw()->ellipse(new \Imagine\Image\Point(mt_rand(0, 50), mt_rand(0, 50)), new \Imagine\Image\Box(mt_rand(50, 200), mt_rand(50, 200)), new \Imagine\Image\Color(array(mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255))), true);
            $image->save($prefix . str_replace('.original', '', $original));
        }
        $success = true;
    } catch (\Exception $e) {
    }
    return new JsonResponse(array('success' => $success));
});
$app->get('/image/{image_id}', function ($image_id, Application $app, Request $request) use($datas) {
    if (!isset($datas[$image_id])) {
        throw new \Exception('Invalid image id');
    }
    $response = new Response();
    $response->setPrivate();
    $response->setProtocolVersion('1.1');
    $response->setEtag($datas[$image_id]['etag']);
    $response->setLastModified($datas[$image_id]['last_modified']);
    $response->headers->addCacheControlDirective('must-revalidate', true);
    if (!$response->isNotModified($request)) {
        $response->headers->set('content-type', 'image/jpeg');
        $response->setContent(file_get_contents(__DIR__ . '/../../config/' . $image_id));
    }
    return $response;
})->assert('image_id', '(herman|robert)\\.jpg');
return $app;
 public function infoAction(Request $request)
 {
     $jsonp = $request->query->get('jsonp');
     $decklist_id = $request->query->get('decklist_id');
     $card_id = $request->query->get('card_id');
     $content = null;
     /* @var $user \AppBundle\Entity\User */
     $user = $this->getUser();
     if ($user) {
         $user_id = $user->getId();
         $public_profile_url = $this->get('router')->generate('user_profile_public', array('user_id' => $user_id, 'user_name' => urlencode($user->getUsername())));
         $content = array('public_profile_url' => $public_profile_url, 'id' => $user_id, 'name' => $user->getUsername(), 'faction' => $user->getColor(), 'donation' => $user->getDonation(), 'is_admin' => $user->hasRole('role_admin'));
         if (isset($decklist_id)) {
             /* @var $em \Doctrine\ORM\EntityManager */
             $em = $this->get('doctrine')->getManager();
             /* @var $decklist \AppBundle\Entity\Decklist */
             $decklist = $em->getRepository('AppBundle:Decklist')->find($decklist_id);
             if ($decklist) {
                 $decklist_id = $decklist->getId();
                 $dbh = $this->get('doctrine')->getConnection();
                 $content['is_liked'] = (bool) $dbh->executeQuery("SELECT\r\n        \t\t\t\tcount(*)\r\n        \t\t\t\tfrom decklist d\r\n        \t\t\t\tjoin vote v on v.decklist_id=d.id\r\n        \t\t\t\twhere v.user_id=?\r\n        \t\t\t\tand d.id=?", array($user_id, $decklist_id))->fetch(\PDO::FETCH_NUM)[0];
                 $content['is_favorite'] = (bool) $dbh->executeQuery("SELECT\r\n        \t\t\t\tcount(*)\r\n        \t\t\t\tfrom decklist d\r\n        \t\t\t\tjoin favorite f on f.decklist_id=d.id\r\n        \t\t\t\twhere f.user_id=?\r\n        \t\t\t\tand d.id=?", array($user_id, $decklist_id))->fetch(\PDO::FETCH_NUM)[0];
                 $content['is_author'] = $user_id == $decklist->getUser()->getId();
                 $content['can_delete'] = $decklist->getNbcomments() == 0 && $decklist->getNbfavorites() == 0 && $decklist->getnbVotes() == 0;
             }
         }
         if (isset($card_id)) {
             /* @var $em \Doctrine\ORM\EntityManager */
             $em = $this->get('doctrine')->getManager();
             /* @var $card \AppBundle\Entity\Card */
             $card = $em->getRepository('AppBundle:Card')->find($card_id);
             if ($card) {
                 $reviews = $card->getReviews();
                 /* @var $review \AppBundle\Entity\Review */
                 foreach ($reviews as $review) {
                     if ($review->getUser()->getId() === $user->getId()) {
                         $content['review_id'] = $review->getId();
                         $content['review_text'] = $review->getRawtext();
                     }
                 }
             }
         }
     }
     $content = json_encode($content);
     $response = new Response();
     $response->setPrivate();
     if (isset($jsonp)) {
         $content = "{$jsonp}({$content})";
         $response->headers->set('Content-Type', 'application/javascript');
     } else {
         $response->headers->set('Content-Type', 'application/json');
     }
     $response->setContent($content);
     return $response;
 }
示例#30
0
 /**
  * Request a single protected font file from Roadiz.
  *
  * @param string                                   $filename
  * @param string                                   $extension
  * @param string                                   $token
  *
  * @return Symfony\Component\HttpFoundation\Response
  */
 public function fontFileAction($filename, $variant, $extension, $token)
 {
     $font = $this->getService('em')->getRepository('RZ\\Roadiz\\Core\\Entities\\Font')->findOneBy(['hash' => $filename, 'variant' => $variant]);
     if (null !== $font) {
         $token = new CsrfToken($font->getHash() . $font->getVariant(), $token);
         if ($this->getService('csrfTokenManager')->isTokenValid($token)) {
             switch ($extension) {
                 case 'eot':
                     $fontpath = $font->getEOTAbsolutePath();
                     $mime = \RZ\Roadiz\Core\Entities\Font::$extensionToMime['eot'];
                     break;
                 case 'woff':
                     $fontpath = $font->getWOFFAbsolutePath();
                     $mime = \RZ\Roadiz\Core\Entities\Font::$extensionToMime['woff'];
                     break;
                 case 'woff2':
                     $fontpath = $font->getWOFF2AbsolutePath();
                     $mime = \RZ\Roadiz\Core\Entities\Font::$extensionToMime['woff2'];
                     break;
                 case 'svg':
                     $fontpath = $font->getSVGAbsolutePath();
                     $mime = \RZ\Roadiz\Core\Entities\Font::$extensionToMime['svg'];
                     break;
                 case 'otf':
                 case 'ttf':
                     $fontpath = $font->getOTFAbsolutePath();
                     $mime = \RZ\Roadiz\Core\Entities\Font::$extensionToMime['otf'];
                     break;
                 default:
                     $fontpath = "";
                     $mime = "text/html";
                     break;
             }
             if ("" != $fontpath) {
                 $response = new Response(file_get_contents($fontpath), Response::HTTP_OK, ['content-type' => $mime]);
                 $date = new \DateTime();
                 $date->modify('+2 hours');
                 $response->setExpires($date);
                 $response->setPrivate();
                 $response->setMaxAge(60 * 60 * 2);
                 return $response;
             }
         } else {
             return new Response("Font Fail " . $token, Response::HTTP_NOT_FOUND, ['content-type' => 'text/html']);
         }
     } else {
         return new Response("Font doesn't exist " . $filename, Response::HTTP_NOT_FOUND, ['content-type' => 'text/html']);
     }
 }