/** * {@inheritdoc} */ public function update(Response $response) { // if we have no embedded Response, do nothing if (0 === $this->embeddedResponses) { return; } // Remove validation related headers in order to avoid browsers using // their own cache, because some of the response content comes from // at least one embedded response (which likely has a different caching strategy). if ($response->isValidateable()) { $response->setEtag(null); $response->setLastModified(null); $this->cacheable = false; } if (!$this->cacheable) { $response->headers->set('Cache-Control', 'no-cache, must-revalidate'); return; } $this->ttls[] = $response->getTtl(); $this->maxAges[] = $response->getMaxAge(); if (null !== ($maxAge = min($this->maxAges))) { $response->setSharedMaxAge($maxAge); $response->headers->set('Age', $maxAge - min($this->ttls)); } $response->setMaxAge(0); }
public function setLastModified($timestamp = 0, $max_age = 0) { $time = new \DateTime('@' . $timestamp); $etag = md5($this->builder->getTheme()->getDir() . $this->builder->getStyle() . '|' . $timestamp . '|' . $max_age); $this->response->headers->addCacheControlDirective('must-revalidate', true); $this->response->setLastModified($time); $this->response->setEtag($etag); $this->response->setMaxAge($max_age); }
/** * {@inheritdoc} */ protected function setHeaders(Response $response, ImageInterface $image, \DateTime $lastMod) { $response->headers->set('Content-type', $image->getMimeType()); $response->setContent($content = $image->getContents()); $response->setLastModified($lastMod); $response->setEtag(hash('md5', $response->getContent())); $response->headers->set('Accept-ranges', 'bytes'); $response->headers->set('Keep-Alive', 'timeout=15, max=200'); $response->headers->set('Connection', 'Keep-Alive', true); }
/** * Set the appripriate HTTP cache headers * * @param \DateTime $lastModified The last time the resource was modified. * @param String $eTag Unique eTag for the resource. * @param Integer $maxAge The max age (in seconds). * @return Void */ private function setHttpCacheHeaders(\DateTime $lastModified, $eTag, $maxAge) { $this->response->setMaxAge($maxAge); $this->response->setPublic(); if ($this->maxAge === 0) { $this->response->headers->set('Cache-Control', 'no-cache'); return; } $this->response->setLastModified($lastModified); $this->response->setEtag($eTag); }
/** * {@inheritdoc} */ protected function setHeaders(Response $response, ImageInterface $image, \DateTime $lastMod) { $response->headers->set('Content-type', $image->getMimeType()); $response->setLastModified($lastMod); $response->headers->set('Accept-ranges', 'bytes'); $response->headers->set('Keep-Alive', 'timeout=5, max=99'); $response->headers->set('Connection', 'keep-alive', true); // return normal by setting image contents; if ($image->isProcessed()) { $response->setContent($content = $image->getContents()); $response->setEtag(hash('md5', $content)); } else { // set the xsend header: $file = $image->getSource(); $response->setEtag(md5_file($file)); $response->headers->set('Content-Length', filesize($file)); $response->headers->set('Content-Disposition', sprintf('inline; filename="%s"', basename($file))); $response->headers->set('X-Sendfile', $file); } }
/** * Display a text by its id * * @param Request $request * @param integer $textId * * @return Response */ public function displayTextByIdAction(Request $request, $textId) { $textLastUpdate = $this->textRepository->findLastUpdate(null, null, $textId); $response = new Response(); $response->setPublic(); $response->setEtag($textId . $textLastUpdate); if ($response->isNotModified($request)) { return $response; } $text = $this->textRepository->findOneBy(array('id' => $textId, 'active' => true)); return $this->render('UnifikSystemBundle:Frontend/Text:displayTexts.html.twig', ['texts' => is_null($text) ? null : array($text), 'textId' => $textId], $response); }
public function execute(Request $request, Config $config, WorkingFolder $workingFolder, ResizedImageRepository $resizedImageRepository, CacheManager $cache) { $fileName = (string) $request->query->get('fileName'); list($requestedWidth, $requestedHeight) = Image::parseSize((string) $request->get('size')); $downloadedFile = new DownloadedFile($fileName, $this->app); $downloadedFile->isValid(); if (!Image::isSupportedExtension(pathinfo($fileName, PATHINFO_EXTENSION), $config->get('thumbnails.bmpSupported'))) { throw new InvalidExtensionException('Unsupported image type or not image file'); } Utils::removeSessionCacheHeaders(); $response = new Response(); $response->setPublic(); $response->setEtag(dechex($downloadedFile->getTimestamp()) . "-" . dechex($downloadedFile->getSize())); $lastModificationDate = new \DateTime(); $lastModificationDate->setTimestamp($downloadedFile->getTimestamp()); $response->setLastModified($lastModificationDate); if ($response->isNotModified($request)) { return $response; } $imagePreviewCacheExpires = (int) $config->get('cache.imagePreview'); if ($imagePreviewCacheExpires > 0) { $response->setMaxAge($imagePreviewCacheExpires); $expireTime = new \DateTime(); $expireTime->modify('+' . $imagePreviewCacheExpires . 'seconds'); $response->setExpires($expireTime); } $cachedInfoPath = Path::combine($workingFolder->getResourceType()->getName(), $workingFolder->getClientCurrentFolder(), $fileName); $cachedInfo = $cache->get($cachedInfoPath); $resultImage = null; // Try to reuse existing resized image if ($cachedInfo && isset($cachedInfo['width']) && isset($cachedInfo['height'])) { // Fix received aspect ratio $size = Image::calculateAspectRatio($requestedWidth, $requestedHeight, $cachedInfo['width'], $cachedInfo['height']); $resizedImage = $resizedImageRepository->getResizedImageBySize($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $size['width'], $size['height']); if ($resizedImage) { $resultImage = Image::create($resizedImage->getImageData()); } } // Fallback - get and resize the original image if (null === $resultImage) { $resultImage = Image::create($downloadedFile->getContents(), $config->get('thumbnails.bmpSupported')); $cache->set($cachedInfoPath, $resultImage->getInfo()); $resultImage->resize($requestedWidth, $requestedHeight); } $mimeType = $resultImage->getMimeType(); if (in_array($mimeType, array('image/bmp', 'image/x-ms-bmp'))) { $mimeType = 'image/jpeg'; // Image::getData() by default converts resized images to JPG } $response->headers->set('Content-Type', $mimeType . '; name="' . $downloadedFile->getFileName() . '"'); $response->setContent($resultImage->getData()); return $response; }
/** * @Route("/submit/{id}", name="oro_embedded_form_submit", requirements={"id"="[-\d\w]+"}) */ public function formAction(EmbeddedForm $formEntity, Request $request) { $response = new Response(); $response->setPublic(); $response->setEtag($formEntity->getId() . $formEntity->getUpdatedAt()->format(\DateTime::ISO8601)); if ($response->isNotModified($request)) { return $response; } /** @var EntityManager $em */ $em = $this->get('doctrine.orm.entity_manager'); /** @var EmbeddedFormManager $formManager */ $formManager = $this->get('oro_embedded_form.manager'); $form = $formManager->createForm($formEntity->getFormType()); if (in_array($request->getMethod(), ['POST', 'PUT'])) { $dataClass = $form->getConfig()->getOption('data_class'); if (isset($dataClass) && class_exists($dataClass)) { $ref = new \ReflectionClass($dataClass); $constructor = $ref->getConstructor(); $data = $constructor && $constructor->getNumberOfRequiredParameters() ? $ref->newInstanceWithoutConstructor() : $ref->newInstance(); $form->setData($data); } else { $data = []; } $event = new EmbeddedFormSubmitBeforeEvent($data, $formEntity); $eventDispatcher = $this->get('event_dispatcher'); $eventDispatcher->dispatch(EmbeddedFormSubmitBeforeEvent::EVENT_NAME, $event); $form->submit($request); $event = new EmbeddedFormSubmitAfterEvent($data, $formEntity, $form); $eventDispatcher->dispatch(EmbeddedFormSubmitAfterEvent::EVENT_NAME, $event); } if ($form->isValid()) { $entity = $form->getData(); /** * Set owner ID (current organization) to concrete form entity */ $entityClass = ClassUtils::getClass($entity); $config = $this->get('oro_entity_config.provider.ownership'); $entityConfig = $config->getConfig($entityClass); $formEntityConfig = $config->getConfig($formEntity); if ($entityConfig->get('owner_type') === OwnershipType::OWNER_TYPE_ORGANIZATION) { $accessor = PropertyAccess::createPropertyAccessor(); $accessor->setValue($entity, $entityConfig->get('owner_field_name'), $accessor->getValue($formEntity, $formEntityConfig->get('owner_field_name'))); } $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('oro_embedded_form_success', ['id' => $formEntity->getId()])); } /** @var EmbedFormLayoutManager $layoutManager */ $layoutManager = $this->get('oro_embedded_form.embed_form_layout_manager'); $response->setContent($layoutManager->getLayout($formEntity, $form)->render()); return $response; }
/** * @param Request $request * * @return Response */ public function changelogAction(Request $request) { $content = file_get_contents($this->kernelRootDir . '/../changelog.yml'); $response = new Response(); $response->setPublic(); $response->setEtag(md5($content)); $response->setVary('Accept-Encoding', 'User-Agent'); if (!$response->isNotModified($request)) { $parser = new Parser(); $response->setLastModified(new \DateTime()); return $this->engine->renderResponse('@CertificationyWeb/Site/changelog.html.twig', ['changelog' => $parser->parse($content)]); } return $response; }
/** * Thumbnailing à la volée */ public function getAction($storageKey, $size) { $file = $this->get('social.picture.storage')->getImagePath($storageKey, $size); $response = new Response(); $lastModif = \DateTime::createFromFormat('U', filemtime($file)); $response->setLastModified($lastModif); $response->setEtag(sha1(filesize($file))); $response->setSharedMaxAge(3600); if ($response->isNotModified($this->getRequest())) { return $response; } $response->headers->set('X-Sendfile', $file); $response->headers->set('Content-Type', 'image/' . pathinfo($storageKey, PATHINFO_EXTENSION)); $this->get('logger')->debug("{$storageKey} xsended"); return $response; }
public function execute(Request $request, WorkingFolder $workingFolder, Config $config, ThumbnailRepository $thumbnailRepository) { if (!$config->get('thumbnails.enabled')) { throw new CKFinderException('Thumbnails feature is disabled', Error::THUMBNAILS_DISABLED); } $fileName = $request->get('fileName'); $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); if (!Image::isSupportedExtension($ext, $thumbnailRepository->isBitmapSupportEnabled())) { throw new InvalidNameException('Invalid source file name'); } if (null === $fileName || !File::isValidName($fileName, $config->get('disallowUnsafeCharacters'))) { throw new InvalidRequestException('Invalid file name'); } list($requestedWidth, $requestedHeight) = Image::parseSize($request->get('size')); $thumbnail = $thumbnailRepository->getThumbnail($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $requestedWidth, $requestedHeight); /** * This was added on purpose to reset any Cache-Control headers set * for example by session_start(). Symfony Session has a workaround, * but but we can't rely on this as application may not use Symfony * components to handle sessions. */ header('Cache-Control:'); $response = new Response(); $response->setPublic(); $response->setEtag(dechex($thumbnail->getTimestamp()) . "-" . dechex($thumbnail->getSize())); $lastModificationDate = new \DateTime(); $lastModificationDate->setTimestamp($thumbnail->getTimestamp()); $response->setLastModified($lastModificationDate); if ($response->isNotModified($request)) { return $response; } $thumbnailsCacheExpires = (int) $config->get('cache.thumbnails'); if ($thumbnailsCacheExpires > 0) { $response->setMaxAge($thumbnailsCacheExpires); $expireTime = new \DateTime(); $expireTime->modify('+' . $thumbnailsCacheExpires . 'seconds'); $response->setExpires($expireTime); } $response->headers->set('Content-Type', $thumbnail->getMimeType() . '; name="' . $thumbnail->getFileName() . '"'); $response->setContent($thumbnail->getImageData()); return $response; }
/** * @param mixed $value to be serialized * @param mixed $context Serialization context * @param string $format * * @return Response */ protected function serialize($value, $context = null, $format = null, Response $response = null) { $request = $this->get('request_stack')->getCurrentRequest(); if ($format === null) { $format = $this->getParameter('exsyst_api.serializer.default_format'); } if ($response === null) { $response = new Response(); } $serializedValue = $this->serializeView($value, $context, $format); $response->setContent($serializedValue); $response->headers->set('Content-Type', $request->getMimeType($format)); $etagGenerator = $this->get('exsyst_api.etag_generator'); $etag = $etagGenerator->generate($response->getContent()); if ($etag !== false) { $response->setEtag($etag->getValue(), $etag->isWeak()); $response->isNotModified($request); } return $response; }
public function execute(Request $request, WorkingFolder $workingFolder, Config $config, ThumbnailRepository $thumbnailRepository) { if (!$config->get('thumbnails.enabled')) { throw new CKFinderException('Thumbnails feature is disabled', Error::THUMBNAILS_DISABLED); } $fileName = (string) $request->get('fileName'); $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); if (!Image::isSupportedExtension($ext, $thumbnailRepository->isBitmapSupportEnabled())) { throw new InvalidNameException('Invalid source file name'); } if (null === $fileName || !File::isValidName($fileName, $config->get('disallowUnsafeCharacters'))) { throw new InvalidRequestException('Invalid file name'); } if (!$workingFolder->containsFile($fileName)) { throw new FileNotFoundException(); } list($requestedWidth, $requestedHeight) = Image::parseSize((string) $request->get('size')); $thumbnail = $thumbnailRepository->getThumbnail($workingFolder->getResourceType(), $workingFolder->getClientCurrentFolder(), $fileName, $requestedWidth, $requestedHeight); Utils::removeSessionCacheHeaders(); $response = new Response(); $response->setPublic(); $response->setEtag(dechex($thumbnail->getTimestamp()) . "-" . dechex($thumbnail->getSize())); $lastModificationDate = new \DateTime(); $lastModificationDate->setTimestamp($thumbnail->getTimestamp()); $response->setLastModified($lastModificationDate); if ($response->isNotModified($request)) { return $response; } $thumbnailsCacheExpires = (int) $config->get('cache.thumbnails'); if ($thumbnailsCacheExpires > 0) { $response->setMaxAge($thumbnailsCacheExpires); $expireTime = new \DateTime(); $expireTime->modify('+' . $thumbnailsCacheExpires . 'seconds'); $response->setExpires($expireTime); } $response->headers->set('Content-Type', $thumbnail->getMimeType() . '; name="' . $thumbnail->getFileName() . '"'); $response->setContent($thumbnail->getImageData()); return $response; }
/** * Build the response so that depending on settings it's cacheable * * @param string|null $etag * @param \DateTime|null $lastModified * * @return \Symfony\Component\HttpFoundation\Response */ protected function buildResponse($etag = null, DateTime $lastModified = null) { $request = $this->getRequest(); $response = new Response(); if ($this->getParameter('content.view_cache') === true) { $response->setPublic(); if ($etag !== null) { $response->setEtag($etag); } if ($this->getParameter('content.ttl_cache') === true) { $response->setSharedMaxAge($this->getParameter('content.default_ttl')); } // 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'); } if ($lastModified != null) { $response->setLastModified($lastModified); } } return $response; }
/** * Get the topic of MAL. * * @param Request $request HTTP Request object * @param int $id The ID of the forum topic as assigned by MyAnimeList * * @return View */ public function getForumTopicAction(Request $request, $id) { // http://myanimelist.net/forum/?topicid=#{id} $page = (int) $request->query->get('page'); if ($page <= 0) { $page = 1; } if ((int) $id == '') { return $this->view(array('error' => 'Invalid topic ID'), 200); } $downloader = $this->get('atarashii_api.communicator'); try { $forumcontent = $downloader->fetch('/forum/?topicid=' . $id . '&show=' . ($page * 50 - 50)); } catch (Exception\CurlException $e) { return $this->view(array('error' => 'network-error'), 500); } $forumtopic = ForumParser::parseTopic($forumcontent); $response = new Response(); $response->setPublic(); $response->setMaxAge(300); //5 minutes $response->headers->addCacheControlDirective('must-revalidate', true); $response->setEtag('forum/topic/' . $id); //Also, set "expires" header for caches that don't understand Cache-Control $date = new \DateTime(); $date->modify('+300 seconds'); //5 minutes $response->setExpires($date); $view = $this->view($forumtopic); $view->setResponse($response); $view->setStatusCode(200); return $view; }
/** * Resizes an image * * @return Response * * @throws EntityNotFoundException Requested image does not exist */ public function resizeAction() { $request = $this->requestStack->getCurrentRequest(); $id = $request->get('id'); /** * We retrieve image given its id */ $image = $this->imageRepository->find($id); if (!$image instanceof ImageInterface) { throw new EntityNotFoundException($this->imageRepository->getClassName()); } $response = new Response(); $height = $request->get('height'); $width = $request->get('width'); $type = $request->get('type'); $response->setEtag($this->imageEtagTransformer->transform($image, $height, $width, $type))->setLastModified($image->getUpdatedAt())->setStatusCode(304)->setPublic(); /** * If the object has not been modified, we return the response. * Symfony will automatically put a 304 status in the response * in that case */ if ($response->isNotModified($request)) { return $response; } $image = $this->imageManager->resize($image, $height, $width, $type); $imageData = $image->getContent(); $response->setStatusCode(200)->setMaxAge($this->maxAge)->setSharedMaxAge($this->sharedMaxAge)->setContent($imageData); $response->headers->add(array('Content-Type' => $image->getContentType())); return $response; }
/** * Search for a topic in the forum. * * @param Request $request The HTTP Request object. * * @return View */ public function getForumAction(Request $request) { // http://myanimelist.net/forum/?action=search&q=#{keyword}&u=#{user}&uloc=#{userCategory}&loc=#{category} $user = $request->query->get('user'); $query = $request->query->get('query'); $userCategory = (int) $request->query->get('userCategory'); $category = (int) $request->query->get('category'); if ($userCategory <= 0) { $userCategory = 1; } if ($category < 0) { $category = -1; } $downloader = $this->get('atarashii_api.communicator'); try { $content = $downloader->fetch('/forum/?action=search&q=' . $query . '&u=' . $user . '&uloc=' . $userCategory . '&loc=' . $category); } catch (Exception\CurlException $e) { return $this->view(array('error' => 'network-error'), 500); } $response = new Response(); $response->setPublic(); $response->setMaxAge(3600); //One hour $response->headers->addCacheControlDirective('must-revalidate', true); $response->setEtag('forum/search?q=' . urlencode($query . $user)); //Also, set "expires" header for caches that don't understand Cache-Control $date = new \DateTime(); $date->modify('+3600 seconds'); //One hour $response->setExpires($date); if (strpos($content, 'User not found') !== false || !strpos($content, 'Topic') !== false) { $view = $this->view(array('error' => 'not-found')); $view->setResponse($response); $view->setStatusCode(404); return $view; } else { $result = ForumParser::parseTopics($content); $view = $this->view($result); $view->setResponse($response); $view->setStatusCode(200); return $view; } }
/** * Fetch Top-rated Manga by Popularity. * * Gets a list of the top-rated manga on MyAnimeList sorted by popularity. The get * variable "page" is used to select the set of results to return (in a default of 30 * items per set). An invalid or missing value defaults to page 1. * * @param string $apiVersion The API version of the request * @param Request $request Contains all the needed information to get the list. * * @return View */ public function getPopularMangaAction($apiVersion, Request $request) { // http://myanimelist.net/topmanga.php?type=bypopularity&limit=#{0} $page = (int) $request->query->get('page'); if ($page <= 0) { $page = 1; } $downloader = $this->get('atarashii_api.communicator'); try { $mangacontent = $downloader->fetch('/topmanga.php?type=bypopularity&limit=' . ($page * 50 - 50)); } catch (Exception\CurlException $e) { return $this->view(array('error' => 'network-error'), 500); } $response = new Response(); $serializationContext = SerializationContext::create(); $serializationContext->setVersion($apiVersion); //For compatibility, API 1.0 explicitly passes null parameters. if ($apiVersion == '1.0') { $serializationContext->setSerializeNull(true); } $response->setPublic(); $response->setMaxAge(10800); //Three hours $response->headers->addCacheControlDirective('must-revalidate', true); $response->setEtag('manga/popular?page=' . urlencode($page)); //Also, set "expires" header for caches that don't understand Cache-Control $date = new \DateTime(); $date->modify('+10800 seconds'); //Three hours $response->setExpires($date); if (strpos($mangacontent, 'No manga titles') !== false) { $view = $this->view(array('error' => 'not-found')); $view->setResponse($response); $view->setStatusCode(404); return $view; } else { $popularmanga = Top::parse($mangacontent, 'manga'); $view = $this->view($popularmanga); $view->setSerializationContext($serializationContext); $view->setResponse($response); $view->setStatusCode(200); return $view; } }
$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 testSetEtag() { $response = new Response('', 200, array('ETag' => '"12345"')); $response->setEtag(); $this->assertNull($response->headers->get('Etag'), '->setEtag() removes Etags when call with null'); }
/** * @param $apiVersion The API version of the request * @param $requestType The anime or manga request string * @param Request $request HTTP Request object * * @return \FOS\RestBundle\View\View */ public function getBrowseAction($apiVersion, $requestType, Request $request) { $downloader = $this->get('atarashii_api.communicator'); $page = (int) $request->query->get('page'); if ($page <= 0) { $page = 1; } // Create URL parts supported by MAL $pagePart = '&show=' . ($page * 50 - 50); $keyword = '&q=' . $request->query->get('keyword'); $score = '&score=' . (int) $request->query->get('score'); $reverse = '&w=' . (int) $request->query->get('reverse'); $rating = '&r=' . (int) $request->query->get('rating'); $genreType = '&gx=' . (int) $request->query->get('genre_type'); $status = '&status=' . $this->getStatusId($request->query->get('status')); $endDateArray = explode('-', $request->query->get('end_date')); if (count($endDateArray) == 3) { $endDate = '&ey=' . $endDateArray[0] . '&em=' . $endDateArray[1] . '&ed=' . $endDateArray[2]; } else { $endDate = ''; } $startDateArray = explode('-', $request->query->get('start_date')); if (count($startDateArray) == 3) { $startDate = '&sy=' . $startDateArray[0] . '&sm=' . $startDateArray[1] . '&sd=' . $startDateArray[2]; } else { $startDate = ''; } if ($requestType === 'anime') { $type = '&type=' . Anime::getTypeId($request->query->get('type')); $genres = Anime::getGenresId($request->query->get('genres')); $sort = '&o=' . Anime::getColumnId($request->query->get('sort'), $requestType); } else { $type = '&type=' . Manga::getTypeId($request->query->get('type')); $genres = Manga::getGenresId($request->query->get('genres')); $sort = '&o=' . Manga::getColumnId($request->query->get('sort'), $requestType); } // Combine all URL parts for the request $url = $genres . $sort . $reverse . $endDate . $startDate . $rating . $status . $type . $keyword . $score . $genreType . $pagePart; try { $content = $downloader->fetch('/' . $requestType . '.php?c[]=a&c[]=b&c[]=c&c[]=d&c[]=e&c[]=f&c[]=g&c[]=g' . $url); } catch (Exception\CurlException $e) { return $this->view(array('error' => 'network-error'), 500); } catch (Exception\ClientErrorResponseException $e) { $content = $e->getResponse(); } $response = new Response(); $serializationContext = SerializationContext::create(); $serializationContext->setVersion($apiVersion); $response->setPublic(); $response->setMaxAge(86400); //One day $response->headers->addCacheControlDirective('must-revalidate', true); $response->setEtag($type . '/' . $requestType . '?' . $url); //Also, set "expires" header for caches that don't understand Cache-Control $date = new \DateTime(); $date->modify('+86400 seconds'); //One day $response->setExpires($date); // MAL does contain a bug where excluded genres allow the same amount of pages as normal without warning // To avoid issues we check if the page number does match the content page number. preg_match('/>\\[(\\d+?)\\]/', $content, $matches); if (strpos($content, 'No titles that matched') !== false || strpos($content, 'This page doesn\'t exist') !== false) { return $this->view(array('error' => 'not-found'), 404); } else { if (count($matches) > 1 && (int) $matches[1] !== $page) { return $this->view(array(), 200); } else { //MAL now returns 404 on a single result. Workaround if (method_exists($content, 'getStatusCode') && $content->getStatusCode() === 404) { $location = $content->getHeader('Location'); try { $content = $downloader->fetch($location); if ($type === 'anime') { $searchResult = array(AnimeParser::parse($content)); } else { $searchResult = array(MangaParser::parse($content)); } } catch (Exception\CurlException $e) { return $this->view(array('error' => 'network-error'), 500); } } else { if ($downloader->wasRedirected()) { if ($type === 'anime') { $searchResult = array(AnimeParser::parse($content)); } else { $searchResult = array(MangaParser::parse($content)); } } else { $searchResult = Upcoming::parse($content, $requestType); } } $view = $this->view($searchResult); $view->setSerializationContext($serializationContext); $view->setResponse($response); $view->setStatusCode(200); return $view; } } }
/** * Renders permanent original image * * @return Response */ public function renderOriginalAction() { $filepath = $this->getRequest()->get('filepath'); $hash = $this->getRequest()->get('hash'); $tag = md5($hash . $filepath); $response = new Response(); $response->setPublic(); $response->setEtag($tag); if ($response->isNotModified($this->getRequest())) { return $response; } $imageManager = $this->container->get('thrace_media.imagemanager'); try { $content = $imageManager->loadPermanentImageByName($filepath); } catch (FileNotFound $e) { throw new NotFoundHttpException(); } $response->setContent($content); $response->headers->set('Accept-Ranges', 'bytes'); $response->headers->set('Content-Length', mb_strlen($content)); $response->headers->set('Content-Type', $this->getMimeType($content)); return $response; }
/** * Saves the response object and if needed modifies it and returns it * * @param Response $response * @param array $cacheData * @return Response */ protected function saveResponseInCache(Response $response, array $cacheData) { $response->setPublic(); if (empty($cacheData['options']['skip_validation']) || $cacheData['options']['skip_validation'] !== true) { $response->setEtag($cacheData['key']); } else { $response->setMaxAge($cacheData['options']['expire']); } return $response; }
/** * Renders permanent file * * @return Response */ public function renderAction() { $name = $this->getRequest()->get('name'); $hash = $this->getRequest()->get('hash'); $response = new Response(); $response->setPublic(); $response->setEtag($hash); if ($response->isNotModified($this->getRequest())) { return $response; } $fileManager = $this->container->get('thrace_media.filemanager'); $content = $fileManager->getPermanentFileBlobByName($name); $response->setContent($content); $response->headers->set('Accept-Ranges', 'bytes'); $response->headers->set('Content-Length', mb_strlen($content)); $response->headers->set('Content-Type', $this->getMimeType($content)); return $response; }
/** * Get the airing schedule. * * @param Request $request HTTP Request object * * @return View */ public function getScheduleAction(Request $request) { // http://myanimelist.net/anime/#{id}/_/episode $downloader = $this->get('atarashii_api.communicator'); $timeZone = $request->query->get('timezone'); try { $details = $downloader->fetch('/anime/season/schedule'); } catch (Exception\CurlException $e) { return $this->view(array('error' => 'network-error'), 500); } $result = ScheduleParser::parse($details, $timeZone); $response = new Response(); $response->setPublic(); $response->setMaxAge(43200); //one day $response->headers->addCacheControlDirective('must-revalidate', true); $response->setEtag('anime/season/schedule' . $timeZone); //Also, set "expires" header for caches that don't understand Cache-Control $date = new \DateTime(); $date->modify('+43200 seconds'); //one day $response->setExpires($date); $view = $this->view($result); $view->setResponse($response); $view->setStatusCode(200); return $view; }
/** * Mailclient imageproxyAction * * @Security("has_role('ROLE_MAILCLIENT_LIST')") * * @param Request $request * @return Response */ public function imageproxyAction(Request $request) { $url = $request->get('url', ''); $md5url = md5($url); $response = new Response(); if ($request->server->has('HTTP_IF_NONE_MATCH') && trim($request->server->get('HTTP_IF_NONE_MATCH')) == $md5url) { $response->setStatusCode(304, 'Not Modified'); return $response; } $memcached = $this->get('memcached'); $imgfromcache = $memcached->get('xxam_mailclient_' . $md5url); if ($imgfromcache) { $response->headers->set('Content-Type', $imgfromcache['content_type']); //$response->headers->set('X-From-Cache','jou!'); $response->setContent($imgfromcache['content']); } else { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); $content = curl_exec($ch); curl_close($ch); $response->headers->set('Content-Type', $content_type); $response->setContent($content); $res = $memcached->set('xxam_mailclient_' . $md5url, ['content_type' => $content_type, 'content' => $content], time() + 86400); //$response->headers->set('X-From-Cache','Na!'.($res ? 'jo':'na').$memcached->getResultCode()); } $response->setEtag($md5url); return $response; }
/** * Create new response given a request and an image. * * Fill some data to this response given some Image properties and check if * created Response has changed. * * @param Request $request Request * @param ImageInterface $image Image * * @return Response Created response */ private function buildResponseFromImage(Request $request, ImageInterface $image) { $response = new Response(); $height = $request->get('height'); $width = $request->get('width'); $type = $request->get('type'); $response->setEtag($this->imageEtagTransformer->transform($image, $height, $width, $type))->setLastModified($image->getUpdatedAt())->setPublic(); /** * If the object has not been modified, we return the response. * Symfony will automatically put a 304 status in the response * in that case */ if ($response->isNotModified($request)) { return $response->setStatusCode(304); } $image = $this->imageManager->resize($image, $height, $width, $type); $imageData = $image->getContent(); $response->setStatusCode(200)->setMaxAge($this->maxAge)->setSharedMaxAge($this->sharedMaxAge)->setContent($imageData); $response->headers->add(['Content-Type' => $image->getContentType()]); return $response; }
/** * Set ETag. * * Need set Last-Modified before ETag * * @param Response $response * * @return ResponseConfigurator */ protected function setEtag(Response $response) { if (!$response->getEtag()) { $response->setEtag($this->key_builder->getEtag($response)); } return $this; }
/** * Maps headers sent by the legacy stack to $response. * * @param array $headers Array headers. * @param \Symfony\Component\HttpFoundation\Response $response * * @return \Symfony\Component\HttpFoundation\Response */ public function mapHeaders( array $headers, Response $response ) { foreach ( $headers as $header ) { $headerArray = explode( ": ", $header, 2 ); $headerName = strtolower( $headerArray[0] ); $headerValue = $headerArray[1]; // Removing existing header to avoid duplicate values $this->removeHeader( $headerName ); switch ( $headerName ) { // max-age and s-maxage are skipped because they are values of the cache-control header case "etag": $response->setEtag( $headerValue ); break; case "last-modified": $response->setLastModified( new DateTime( $headerValue ) ); break; case "expires": $response->setExpires( new DateTime( $headerValue ) ); break; default; $response->headers->set( $headerName, $headerValue, true ); break; } } return $response; }
use Symfony\Component\Routing\Route; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\Routing\Exception\ResourceNotFoundException; global $di, $request, $routes; #.html config $routes->add('front_index', new Route('/{path}/{file}.{_format}', array('file' => null, '_controller' => function (Request $request) { if (!file_exists(APP_FRONT_RESOURCE_PATH . $request->getPathInfo())) { throw new ResourceNotFoundException(APP_FRONT_RESOURCE_PATH . $request->getPathInfo()); } $file = file_get_contents(APP_FRONT_RESOURCE_PATH . $request->getPathInfo(), false, null, -1); $response = new Response($file); $response->headers->set('Content-Type', 'text/html'); $response->setEtag(md5($file, false)); $response->isNotModified($request); return $response; }), array('_method' => 'GET', '_format' => 'html', 'path' => 'app'))); #.css config $routes->add('css', new Route('/{path}/{file}.{_format}', array('file' => null, '_controller' => function (Request $request) { if (!file_exists(APP_FRONT_RESOURCE_PATH . $request->getPathInfo())) { throw new ResourceNotFoundException(APP_FRONT_RESOURCE_PATH . $request->getPathInfo()); } $css = file_get_contents(APP_FRONT_RESOURCE_PATH . $request->getPathInfo(), false, null, -1); $response = new Response($css); $response->headers->set('Content-Type', 'text/css'); //200 OK(BFCache) $response->setExpires(new \DateTime('2019-01-01')); return $response; }), array('_method' => 'GET', '_format' => 'css|min.css', 'path' => 'dist/css|assets/css|app/css')));