vendor/pimcore/pimcore/bundles/CoreBundle/Controller/PublicServicesController.php line 221

Open in your IDE?
  1. <?php
  2. /**
  3.  * Pimcore
  4.  *
  5.  * This source file is available under two different licenses:
  6.  * - GNU General Public License version 3 (GPLv3)
  7.  * - Pimcore Commercial License (PCL)
  8.  * Full copyright and license information is available in
  9.  * LICENSE.md which is distributed with this source code.
  10.  *
  11.  *  @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  12.  *  @license    http://www.pimcore.org/license     GPLv3 and PCL
  13.  */
  14. namespace Pimcore\Bundle\CoreBundle\Controller;
  15. use function date;
  16. use Pimcore\Config;
  17. use Pimcore\Controller\Controller;
  18. use Pimcore\File;
  19. use Pimcore\Logger;
  20. use Pimcore\Model\Asset;
  21. use Pimcore\Model\Site;
  22. use Pimcore\Model\Tool\TmpStore;
  23. use Pimcore\Tool\Storage;
  24. use Symfony\Component\HttpFoundation\Cookie;
  25. use Symfony\Component\HttpFoundation\RedirectResponse;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\HttpFoundation\StreamedResponse;
  29. use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;
  30. use function time;
  31. /**
  32.  * @internal
  33.  */
  34. class PublicServicesController extends Controller
  35. {
  36.     /**
  37.      * @param Request $request
  38.      *
  39.      * @return RedirectResponse|StreamedResponse
  40.      */
  41.     public function thumbnailAction(Request $request)
  42.     {
  43.         $storage Storage::get('thumbnail');
  44.         $assetId = (int) $request->get('assetId');
  45.         $thumbnailName $request->get('thumbnailName');
  46.         $thumbnailType $request->get('type');
  47.         $filename $request->get('filename');
  48.         $requestedFileExtension strtolower(File::getFileExtension($filename));
  49.         $asset Asset::getById($assetId);
  50.         if ($asset) {
  51.             $prefix preg_replace('@^cache-buster\-[\d]+\/@'''$request->get('prefix'));
  52.             $prefix preg_replace('@' $asset->getId() . '/$@'''$prefix);
  53.             if ($asset->getPath() === ('/' $prefix)) {
  54.                 // we need to check the path as well, this is important in the case you have restricted the public access to
  55.                 // assets via rewrite rules
  56.                 try {
  57.                     $thumbnail null;
  58.                     $thumbnailStream null;
  59.                     // just check if the thumbnail exists -> throws exception otherwise
  60.                     $thumbnailConfigClass 'Pimcore\\Model\\Asset\\' ucfirst($thumbnailType) . '\\Thumbnail\Config';
  61.                     $thumbnailConfig $thumbnailConfigClass::getByName($thumbnailName);
  62.                     if (!$thumbnailConfig) {
  63.                         // check if there's an item in the TmpStore
  64.                         // remove an eventually existing cache-buster prefix first (eg. when using with a CDN)
  65.                         $pathInfo preg_replace('@^/cache-buster\-[\d]+@'''$request->getPathInfo());
  66.                         $deferredConfigId 'thumb_' $assetId '__' md5(urldecode($pathInfo));
  67.                         if ($thumbnailConfigItem TmpStore::get($deferredConfigId)) {
  68.                             $thumbnailConfig $thumbnailConfigItem->getData();
  69.                             TmpStore::delete($deferredConfigId);
  70.                             if (!$thumbnailConfig instanceof $thumbnailConfigClass) {
  71.                                 throw new \Exception('Deferred thumbnail config file doesn\'t contain a valid '.$thumbnailConfigClass.' object');
  72.                             }
  73.                         } elseif ($this->getParameter('pimcore.config')['assets'][$thumbnailType]['thumbnails']['status_cache']) {
  74.                             // Delete Thumbnail Name from Cache so the next call can generate a new TmpStore entry
  75.                             $asset->getDao()->deleteFromThumbnailCache($thumbnailName);
  76.                         }
  77.                     }
  78.                     if (!$thumbnailConfig) {
  79.                         throw $this->createNotFoundException("Thumbnail '" $thumbnailName "' file doesn't exist");
  80.                     }
  81.                     if ($thumbnailType == 'image' && strcasecmp($thumbnailConfig->getFormat(), 'SOURCE') === 0) {
  82.                         $formatOverride $requestedFileExtension;
  83.                         if (in_array($requestedFileExtension, ['jpg''jpeg'])) {
  84.                             $formatOverride 'pjpeg';
  85.                         }
  86.                         $thumbnailConfig->setFormat($formatOverride);
  87.                     }
  88.                     if ($asset instanceof Asset\Video) {
  89.                         if ($thumbnailType == 'video') {
  90.                             $thumbnail $asset->getThumbnail($thumbnailName, [$requestedFileExtension]);
  91.                             $storagePath urldecode($thumbnail['formats'][$requestedFileExtension]);
  92.                             if ($storage->fileExists($storagePath)) {
  93.                                 $thumbnailStream $storage->readStream($storagePath);
  94.                             }
  95.                         } else {
  96.                             $time 1;
  97.                             if (preg_match("|~\-~time\-(\d+)\.|"$filename$matchesThumbs)) {
  98.                                 $time = (int)$matchesThumbs[1];
  99.                             }
  100.                             $thumbnail $asset->getImageThumbnail($thumbnailConfig$time);
  101.                             $thumbnailStream $thumbnail->getStream();
  102.                         }
  103.                     } elseif ($asset instanceof Asset\Document) {
  104.                         $page 1;
  105.                         if (preg_match("|~\-~page\-(\d+)\.|"$filename$matchesThumbs)) {
  106.                             $page = (int)$matchesThumbs[1];
  107.                         }
  108.                         $thumbnailConfig->setName(preg_replace("/\-[\d]+/"''$thumbnailConfig->getName()));
  109.                         $thumbnailConfig->setName(str_replace('document_'''$thumbnailConfig->getName()));
  110.                         $thumbnail $asset->getImageThumbnail($thumbnailConfig$page);
  111.                         $thumbnailStream $thumbnail->getStream();
  112.                     } elseif ($asset instanceof Asset\Image) {
  113.                         //check if high res image is called
  114.                         preg_match("@([^\@]+)(\@[0-9.]+x)?\.([a-zA-Z]{2,5})@"$filename$matches);
  115.                         if (empty($matches) || !isset($matches[1])) {
  116.                             throw $this->createNotFoundException('Requested asset does not exist');
  117.                         }
  118.                         if (array_key_exists(2$matches) && $matches[2]) {
  119.                             $highResFactor = (float)str_replace(['@''x'], ''$matches[2]);
  120.                             $thumbnailConfig->setHighResolution($highResFactor);
  121.                         }
  122.                         // check if a media query thumbnail was requested
  123.                         if (preg_match("#~\-~media\-\-(.*)\-\-query#"$matches[1], $mediaQueryResult)) {
  124.                             $thumbnailConfig->selectMedia($mediaQueryResult[1]);
  125.                         }
  126.                         $thumbnail $asset->getThumbnail($thumbnailConfig);
  127.                         $thumbnailStream $thumbnail->getStream();
  128.                     }
  129.                     if ($thumbnail && $thumbnailStream) {
  130.                         if ($thumbnailType == 'image') {
  131.                             $mime $thumbnail->getMimeType();
  132.                             $fileSize $thumbnail->getFileSize();
  133.                             $pathReference $thumbnail->getPathReference();
  134.                             $actualFileExtension File::getFileExtension($pathReference['src']);
  135.                             if ($actualFileExtension !== $requestedFileExtension) {
  136.                                 // create a copy/symlink to the file with the original file extension
  137.                                 // this can be e.g. the case when the thumbnail is called as foo.png but the thumbnail config
  138.                                 // is set to auto-optimized format so the resulting thumbnail can be jpeg
  139.                                 $requestedFile preg_replace('/\.' $actualFileExtension '$/''.' $requestedFileExtension$pathReference['src']);
  140.                                 $storage->writeStream($requestedFile$thumbnailStream);
  141.                             }
  142.                         } elseif ($thumbnailType =='video' && isset($storagePath)) {
  143.                             $mime $storage->mimeType($storagePath);
  144.                             $fileSize $storage->fileSize($storagePath);
  145.                         } else {
  146.                             throw new \Exception('Cannot determine mime type and file size of '.$thumbnailType.' thumbnail, see logs for details.');
  147.                         }
  148.                         // set appropriate caching headers
  149.                         // see also: https://github.com/pimcore/pimcore/blob/1931860f0aea27de57e79313b2eb212dcf69ef13/.htaccess#L86-L86
  150.                         $lifetime 86400 7// 1 week lifetime, same as direct delivery in .htaccess
  151.                         $headers = [
  152.                             'Cache-Control' => 'public, max-age=' $lifetime,
  153.                             'Expires' => date('D, d M Y H:i:s T'time() + $lifetime),
  154.                             'Content-Type' => $mime,
  155.                             'Content-Length' => $fileSize,
  156.                         ];
  157.                         $headers[AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER] = true;
  158.                         return new StreamedResponse(function () use ($thumbnailStream) {
  159.                             fpassthru($thumbnailStream);
  160.                         }, 200$headers);
  161.                     }
  162.                     throw new \Exception('Unable to generate '.$thumbnailType.' thumbnail, see logs for details.');
  163.                 } catch (\Exception $e) {
  164.                     Logger::error($e->getMessage());
  165.                     return new RedirectResponse('/bundles/pimcoreadmin/img/filetype-not-supported.svg');
  166.                 }
  167.             }
  168.         }
  169.         throw $this->createNotFoundException('Asset not found');
  170.     }
  171.     /**
  172.      * @param Request $request
  173.      *
  174.      * @return Response
  175.      */
  176.     public function robotsTxtAction(Request $request)
  177.     {
  178.         // check for site
  179.         $domain \Pimcore\Tool::getHostname();
  180.         $site Site::getByDomain($domain);
  181.         $config Config::getRobotsConfig()->toArray();
  182.         $siteId 'default';
  183.         if ($site instanceof Site) {
  184.             $siteId $site->getId();
  185.         }
  186.         // send correct headers
  187.         header('Content-Type: text/plain; charset=utf8');
  188.         while (@ob_end_flush()) ;
  189.         // check for configured robots.txt in pimcore
  190.         $content '';
  191.         if (array_key_exists($siteId$config)) {
  192.             $content $config[$siteId];
  193.         }
  194.         if (empty($content)) {
  195.             // default behavior, allow robots to index everything
  196.             $content "User-agent: *\nDisallow:";
  197.         }
  198.         return new Response($contentResponse::HTTP_OK, [
  199.             'Content-Type' => 'text/plain',
  200.         ]);
  201.     }
  202.     /**
  203.      * @param Request $request
  204.      *
  205.      * @return Response
  206.      */
  207.     public function commonFilesAction(Request $request)
  208.     {
  209.         return new Response("HTTP/1.1 404 Not Found\nFiltered by common files filter"404);
  210.     }
  211.     /**
  212.      * @param Request $request
  213.      *
  214.      * @return \Symfony\Component\HttpFoundation\RedirectResponse
  215.      */
  216.     public function customAdminEntryPointAction(Request $request)
  217.     {
  218.         $params $request->query->all();
  219.         if (isset($params['token'])) {
  220.             $url $this->generateUrl('pimcore_admin_login_check'$params);
  221.         } else {
  222.             $url $this->generateUrl('pimcore_admin_login'$params);
  223.         }
  224.         $redirect = new RedirectResponse($url);
  225.         $customAdminPathIdentifier $this->getParameter('pimcore_admin.custom_admin_path_identifier');
  226.         if (!empty($customAdminPathIdentifier) && $request->cookies->get('pimcore_custom_admin') != $customAdminPathIdentifier) {
  227.             $redirect->headers->setCookie(new Cookie('pimcore_custom_admin'$customAdminPathIdentifierstrtotime('+1 year')));
  228.         }
  229.         return $redirect;
  230.     }
  231. }