vendor/pimcore/pimcore/bundles/AdminBundle/Controller/Admin/Asset/AssetController.php line 1322

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\AdminBundle\Controller\Admin\Asset;
  15. use Pimcore\Bundle\AdminBundle\Controller\Admin\ElementControllerBase;
  16. use Pimcore\Bundle\AdminBundle\Controller\Traits\AdminStyleTrait;
  17. use Pimcore\Bundle\AdminBundle\Controller\Traits\ApplySchedulerDataTrait;
  18. use Pimcore\Bundle\AdminBundle\Helper\GridHelperService;
  19. use Pimcore\Bundle\AdminBundle\Security\CsrfProtectionHandler;
  20. use Pimcore\Config;
  21. use Pimcore\Controller\KernelControllerEventInterface;
  22. use Pimcore\Controller\Traits\ElementEditLockHelperTrait;
  23. use Pimcore\Db\Helper;
  24. use Pimcore\Event\Admin\ElementAdminStyleEvent;
  25. use Pimcore\Event\AdminEvents;
  26. use Pimcore\Event\AssetEvents;
  27. use Pimcore\File;
  28. use Pimcore\Loader\ImplementationLoader\Exception\UnsupportedException;
  29. use Pimcore\Logger;
  30. use Pimcore\Messenger\AssetPreviewImageMessage;
  31. use Pimcore\Model;
  32. use Pimcore\Model\Asset;
  33. use Pimcore\Model\Element;
  34. use Pimcore\Model\Metadata;
  35. use Pimcore\Model\Schedule\Task;
  36. use Pimcore\Tool;
  37. use Symfony\Component\EventDispatcher\GenericEvent;
  38. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  39. use Symfony\Component\HttpFoundation\JsonResponse;
  40. use Symfony\Component\HttpFoundation\Request;
  41. use Symfony\Component\HttpFoundation\Response;
  42. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  43. use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface;
  44. use Symfony\Component\HttpFoundation\StreamedResponse;
  45. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  46. use Symfony\Component\Mime\MimeTypes;
  47. use Symfony\Component\Process\Process;
  48. use Symfony\Component\Routing\Annotation\Route;
  49. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  50. /**
  51.  * @Route("/asset")
  52.  *
  53.  * @internal
  54.  */
  55. class AssetController extends ElementControllerBase implements KernelControllerEventInterface
  56. {
  57.     use AdminStyleTrait;
  58.     use ElementEditLockHelperTrait;
  59.     use ApplySchedulerDataTrait;
  60.     /**
  61.      * @var Asset\Service
  62.      */
  63.     protected $_assetService;
  64.     /**
  65.      * @Route("/tree-get-root", name="pimcore_admin_asset_treegetroot", methods={"GET"})
  66.      *
  67.      * @param Request $request
  68.      *
  69.      * @return JsonResponse
  70.      */
  71.     public function treeGetRootAction(Request $request)
  72.     {
  73.         return parent::treeGetRootAction($request);
  74.     }
  75.     /**
  76.      * @Route("/delete-info", name="pimcore_admin_asset_deleteinfo", methods={"GET"})
  77.      *
  78.      * @param Request $request
  79.      * @param EventDispatcherInterface $eventDispatcher
  80.      *
  81.      * @return JsonResponse
  82.      */
  83.     public function deleteInfoAction(Request $requestEventDispatcherInterface $eventDispatcher)
  84.     {
  85.         return parent::deleteInfoAction($request$eventDispatcher);
  86.     }
  87.     /**
  88.      * @Route("/get-data-by-id", name="pimcore_admin_asset_getdatabyid", methods={"GET"})
  89.      *
  90.      * @param Request $request
  91.      *
  92.      * @return JsonResponse
  93.      */
  94.     public function getDataByIdAction(Request $requestEventDispatcherInterface $eventDispatcher)
  95.     {
  96.         $assetId = (int)$request->get('id');
  97.         $type = (string)$request->get('type');
  98.         $asset Asset::getById($assetId);
  99.         if (!$asset instanceof Asset) {
  100.             return $this->adminJson(['success' => false'message' => "asset doesn't exist"]);
  101.         }
  102.         // check for lock on non-folder items only.
  103.         if ($type !== 'folder' && ($asset->isAllowed('publish') || $asset->isAllowed('delete'))) {
  104.             if (Element\Editlock::isLocked($assetId'asset')) {
  105.                 return $this->getEditLockResponse($assetId'asset');
  106.             }
  107.             Element\Editlock::lock($request->get('id'), 'asset');
  108.         }
  109.         $asset = clone $asset;
  110.         $asset->setParent(null);
  111.         $asset->setStream(null);
  112.         $data $asset->getObjectVars();
  113.         $data['locked'] = $asset->isLocked();
  114.         if ($asset instanceof Asset\Text) {
  115.             if ($asset->getFileSize() < 2000000) {
  116.                 // it doesn't make sense to show a preview for files bigger than 2MB
  117.                 $data['data'] = \ForceUTF8\Encoding::toUTF8($asset->getData());
  118.             } else {
  119.                 $data['data'] = false;
  120.             }
  121.         } elseif ($asset instanceof Asset\Document) {
  122.             $data['pdfPreviewAvailable'] = (bool)$this->getDocumentPreviewPdf($asset);
  123.         } elseif ($asset instanceof Asset\Video) {
  124.             $videoInfo = [];
  125.             if (\Pimcore\Video::isAvailable()) {
  126.                 $config Asset\Video\Thumbnail\Config::getPreviewConfig();
  127.                 $thumbnail $asset->getThumbnail($config, ['mp4']);
  128.                 if ($thumbnail) {
  129.                     if ($thumbnail['status'] == 'finished') {
  130.                         $videoInfo['previewUrl'] = $thumbnail['formats']['mp4'];
  131.                         $videoInfo['width'] = $asset->getWidth();
  132.                         $videoInfo['height'] = $asset->getHeight();
  133.                         $metaData $asset->getSphericalMetaData();
  134.                         if (isset($metaData['ProjectionType']) && strtolower($metaData['ProjectionType']) == 'equirectangular') {
  135.                             $videoInfo['isVrVideo'] = true;
  136.                         }
  137.                     }
  138.                 }
  139.             }
  140.             $data['videoInfo'] = $videoInfo;
  141.         } elseif ($asset instanceof Asset\Image) {
  142.             $imageInfo = [];
  143.             $previewUrl $this->generateUrl('pimcore_admin_asset_getimagethumbnail', [
  144.                 'id' => $asset->getId(),
  145.                 'treepreview' => true,
  146.                 '_dc' => time(),
  147.             ]);
  148.             if ($asset->isAnimated()) {
  149.                 $previewUrl $this->generateUrl('pimcore_admin_asset_getasset', [
  150.                     'id' => $asset->getId(),
  151.                     '_dc' => time(),
  152.                 ]);
  153.             }
  154.             $imageInfo['previewUrl'] = $previewUrl;
  155.             if ($asset->getWidth() && $asset->getHeight()) {
  156.                 $imageInfo['dimensions'] = [];
  157.                 $imageInfo['dimensions']['width'] = $asset->getWidth();
  158.                 $imageInfo['dimensions']['height'] = $asset->getHeight();
  159.             }
  160.             $imageInfo['exiftoolAvailable'] = (bool)\Pimcore\Tool\Console::getExecutable('exiftool');
  161.             if (!$asset->getEmbeddedMetaData(false)) {
  162.                 $asset->getEmbeddedMetaData(truefalse); // read Exif, IPTC and XPM like in the old days ...
  163.             }
  164.             $data['imageInfo'] = $imageInfo;
  165.         }
  166.         $predefinedMetaData Metadata\Predefined\Listing::getByTargetType('asset', [$asset->getType()]);
  167.         $predefinedMetaDataGroups = [];
  168.         /** @var Metadata\Predefined $item */
  169.         foreach ($predefinedMetaData as $item) {
  170.             if ($item->getGroup()) {
  171.                 $predefinedMetaDataGroups[$item->getGroup()] = true;
  172.             }
  173.         }
  174.         $data['predefinedMetaDataGroups'] = array_keys($predefinedMetaDataGroups);
  175.         $data['properties'] = Element\Service::minimizePropertiesForEditmode($asset->getProperties());
  176.         $data['metadata'] = Asset\Service::expandMetadataForEditmode($asset->getMetadata());
  177.         $data['versionDate'] = $asset->getModificationDate();
  178.         $data['filesizeFormatted'] = $asset->getFileSize(true);
  179.         $data['filesize'] = $asset->getFileSize();
  180.         $data['fileExtension'] = File::getFileExtension($asset->getFilename());
  181.         $data['idPath'] = Element\Service::getIdPath($asset);
  182.         $data['userPermissions'] = $asset->getUserPermissions($this->getAdminUser());
  183.         $frontendPath $asset->getFrontendFullPath();
  184.         $data['url'] = preg_match('/^http(s)?:\\/\\/.+/'$frontendPath) ?
  185.             $frontendPath :
  186.             $request->getSchemeAndHttpHost() . $frontendPath;
  187.         $data['scheduledTasks'] = array_map(
  188.             static function (Task $task) {
  189.                 return $task->getObjectVars();
  190.             },
  191.             $asset->getScheduledTasks()
  192.         );
  193.         $this->addAdminStyle($assetElementAdminStyleEvent::CONTEXT_EDITOR$data);
  194.         $data['php'] = [
  195.             'classes' => array_merge([get_class($asset)], array_values(class_parents($asset))),
  196.             'interfaces' => array_values(class_implements($asset)),
  197.         ];
  198.         $event = new GenericEvent($this, [
  199.             'data' => $data,
  200.             'asset' => $asset,
  201.         ]);
  202.         $eventDispatcher->dispatch($eventAdminEvents::ASSET_GET_PRE_SEND_DATA);
  203.         $data $event->getArgument('data');
  204.         if ($asset->isAllowed('view')) {
  205.             return $this->adminJson($data);
  206.         }
  207.         throw $this->createAccessDeniedHttpException();
  208.     }
  209.     /**
  210.      * @Route("/tree-get-childs-by-id", name="pimcore_admin_asset_treegetchildsbyid", methods={"GET"})
  211.      *
  212.      * @param Request $request
  213.      *
  214.      * @return JsonResponse
  215.      */
  216.     public function treeGetChildsByIdAction(Request $requestEventDispatcherInterface $eventDispatcher)
  217.     {
  218.         $allParams array_merge($request->request->all(), $request->query->all());
  219.         $assets = [];
  220.         $cv false;
  221.         $asset Asset::getById($allParams['node']);
  222.         $filter $request->get('filter');
  223.         $limit = (int)$allParams['limit'];
  224.         if (!is_null($filter)) {
  225.             if (substr($filter, -1) != '*') {
  226.                 $filter .= '*';
  227.             }
  228.             $filter str_replace('*''%'$filter);
  229.             $limit 100;
  230.             $offset 0;
  231.         } elseif (!$allParams['limit']) {
  232.             $limit 100000000;
  233.         }
  234.         $offset = isset($allParams['start']) ? (int)$allParams['start'] : 0;
  235.         $filteredTotalCount 0;
  236.         if ($asset->hasChildren()) {
  237.             if ($allParams['view']) {
  238.                 $cv \Pimcore\Model\Element\Service::getCustomViewById($allParams['view']);
  239.             }
  240.             // get assets
  241.             $childrenList = new Asset\Listing();
  242.             $childrenList->addConditionParam('parentId = ?', [$asset->getId()]);
  243.             $childrenList->filterAccessibleByUser($this->getAdminUser(), $asset);
  244.             if (!is_null($filter)) {
  245.                 $childrenList->addConditionParam('CAST(assets.filename AS CHAR CHARACTER SET utf8) COLLATE utf8_general_ci LIKE ?', [$filter]);
  246.             }
  247.             $childrenList->setLimit($limit);
  248.             $childrenList->setOffset($offset);
  249.             $childrenList->setOrderKey("FIELD(assets.type, 'folder') DESC, CAST(assets.filename AS CHAR CHARACTER SET utf8) COLLATE utf8_general_ci ASC"false);
  250.             \Pimcore\Model\Element\Service::addTreeFilterJoins($cv$childrenList);
  251.             $beforeListLoadEvent = new GenericEvent($this, [
  252.                 'list' => $childrenList,
  253.                 'context' => $allParams,
  254.             ]);
  255.             $eventDispatcher->dispatch($beforeListLoadEventAdminEvents::ASSET_LIST_BEFORE_LIST_LOAD);
  256.             /** @var Asset\Listing $childrenList */
  257.             $childrenList $beforeListLoadEvent->getArgument('list');
  258.             $children $childrenList->load();
  259.             $filteredTotalCount $childrenList->getTotalCount();
  260.             foreach ($children as $childAsset) {
  261.                 $assetTreeNode $this->getTreeNodeConfig($childAsset);
  262.                 if ($assetTreeNode['permissions']['list'] == 1) {
  263.                     $assets[] = $assetTreeNode;
  264.                 }
  265.             }
  266.         }
  267.         //Hook for modifying return value - e.g. for changing permissions based on asset data
  268.         $event = new GenericEvent($this, [
  269.             'assets' => $assets,
  270.         ]);
  271.         $eventDispatcher->dispatch($eventAdminEvents::ASSET_TREE_GET_CHILDREN_BY_ID_PRE_SEND_DATA);
  272.         $assets $event->getArgument('assets');
  273.         if ($allParams['limit']) {
  274.             return $this->adminJson([
  275.                 'offset' => $offset,
  276.                 'limit' => $limit,
  277.                 'total' => $asset->getChildAmount($this->getAdminUser()),
  278.                 'overflow' => !is_null($filter) && ($filteredTotalCount $limit),
  279.                 'nodes' => $assets,
  280.                 'filter' => $request->get('filter') ? $request->get('filter') : '',
  281.                 'inSearch' => (int)$request->get('inSearch'),
  282.             ]);
  283.         } else {
  284.             return $this->adminJson($assets);
  285.         }
  286.     }
  287.     /**
  288.      * @Route("/add-asset", name="pimcore_admin_asset_addasset", methods={"POST"})
  289.      *
  290.      * @param Request $request
  291.      * @param Config $config
  292.      *
  293.      * @return JsonResponse
  294.      */
  295.     public function addAssetAction(Request $requestConfig $config)
  296.     {
  297.         try {
  298.             $res $this->addAsset($request$config);
  299.             $response = [
  300.                 'success' => $res['success'],
  301.             ];
  302.             if ($res['success']) {
  303.                 $response['asset'] = [
  304.                     'id' => $res['asset']->getId(),
  305.                     'path' => $res['asset']->getFullPath(),
  306.                     'type' => $res['asset']->getType(),
  307.                 ];
  308.             }
  309.             return $this->adminJson($response);
  310.         } catch (\Exception $e) {
  311.             return $this->adminJson([
  312.                 'success' => false,
  313.                 'message' => $e->getMessage(),
  314.             ]);
  315.         }
  316.     }
  317.     /**
  318.      * @Route("/add-asset-compatibility", name="pimcore_admin_asset_addassetcompatibility", methods={"POST"})
  319.      *
  320.      * @param Request $request
  321.      * @param Config $config
  322.      *
  323.      * @return JsonResponse
  324.      */
  325.     public function addAssetCompatibilityAction(Request $requestConfig $config)
  326.     {
  327.         try {
  328.             // this is a special action for the compatibility mode upload (without flash)
  329.             $res $this->addAsset($request$config);
  330.             $response $this->adminJson([
  331.                 'success' => $res['success'],
  332.                 'msg' => $res['success'] ? 'Success' 'Error',
  333.                 'id' => $res['asset'] ? $res['asset']->getId() : null,
  334.                 'fullpath' => $res['asset'] ? $res['asset']->getRealFullPath() : null,
  335.                 'type' => $res['asset'] ? $res['asset']->getType() : null,
  336.             ]);
  337.             $response->headers->set('Content-Type''text/html');
  338.             return $response;
  339.         } catch (\Exception $e) {
  340.             return $this->adminJson([
  341.                 'success' => false,
  342.                 'message' => $e->getMessage(),
  343.             ]);
  344.         }
  345.     }
  346.     /**
  347.      * @Route("/exists", name="pimcore_admin_asset_exists", methods={"GET"})
  348.      *
  349.      * @param Request $request
  350.      *
  351.      * @return JsonResponse
  352.      *
  353.      * @throws \Exception
  354.      */
  355.     public function existsAction(Request $request)
  356.     {
  357.         $parentAsset \Pimcore\Model\Asset::getById((int)$request->get('parentId'));
  358.         return new JsonResponse([
  359.             'exists' => Asset\Service::pathExists($parentAsset->getRealFullPath().'/'.$request->get('filename')),
  360.         ]);
  361.     }
  362.     /**
  363.      * @param Request $request
  364.      * @param Config $config
  365.      *
  366.      * @return array
  367.      *
  368.      * @throws \Exception
  369.      */
  370.     protected function addAsset(Request $requestConfig $config)
  371.     {
  372.         $defaultUploadPath $config['assets']['default_upload_path'] ?? '/';
  373.         if (array_key_exists('Filedata'$_FILES)) {
  374.             $filename $_FILES['Filedata']['name'];
  375.             $sourcePath $_FILES['Filedata']['tmp_name'];
  376.         } elseif ($request->get('type') == 'base64') {
  377.             $filename $request->get('filename');
  378.             $sourcePath PIMCORE_SYSTEM_TEMP_DIRECTORY '/upload-base64' uniqid() . '.tmp';
  379.             $data preg_replace('@^data:[^,]+;base64,@'''$request->get('data'));
  380.             File::put($sourcePathbase64_decode($data));
  381.         } else {
  382.             throw new \Exception('The filename of the asset is empty');
  383.         }
  384.         $parentId $request->get('parentId');
  385.         $parentPath $request->get('parentPath');
  386.         if ($request->get('dir') && $request->get('parentId')) {
  387.             // this is for uploading folders with Drag&Drop
  388.             // param "dir" contains the relative path of the file
  389.             $parent Asset::getById((int) $request->get('parentId'));
  390.             $dir $request->get('dir');
  391.             if (strpos($dir'..') !== false) {
  392.                 throw new \Exception('not allowed');
  393.             }
  394.             $newPath $parent->getRealFullPath() . '/' trim($dir'/ ');
  395.             $maxRetries 5;
  396.             $newParent null;
  397.             for ($retries 0$retries $maxRetries$retries++) {
  398.                 try {
  399.                     $newParent Asset\Service::createFolderByPath($newPath);
  400.                     break;
  401.                 } catch (\Exception $e) {
  402.                     if ($retries < ($maxRetries 1)) {
  403.                         $waitTime rand(100000900000); // microseconds
  404.                         usleep($waitTime); // wait specified time until we restart the transaction
  405.                     } else {
  406.                         // if the transaction still fail after $maxRetries retries, we throw out the exception
  407.                         throw $e;
  408.                     }
  409.                 }
  410.             }
  411.             if ($newParent) {
  412.                 $parentId $newParent->getId();
  413.             }
  414.         } elseif (!$request->get('parentId') && $parentPath) {
  415.             $parent Asset::getByPath($parentPath);
  416.             if ($parent instanceof Asset\Folder) {
  417.                 $parentId $parent->getId();
  418.             }
  419.         }
  420.         $filename Element\Service::getValidKey($filename'asset');
  421.         if (empty($filename)) {
  422.             throw new \Exception('The filename of the asset is empty');
  423.         }
  424.         $context $request->get('context');
  425.         if ($context) {
  426.             $context json_decode($contexttrue);
  427.             $context $context $context : [];
  428.             $event = new \Pimcore\Event\Model\Asset\ResolveUploadTargetEvent($parentId$filename$context);
  429.             \Pimcore::getEventDispatcher()->dispatch($eventAssetEvents::RESOLVE_UPLOAD_TARGET);
  430.             $filename Element\Service::getValidKey($event->getFilename(), 'asset');
  431.             $parentId $event->getParentId();
  432.         }
  433.         if (!$parentId) {
  434.             $parentId Asset\Service::createFolderByPath($defaultUploadPath)->getId();
  435.         }
  436.         $parentAsset Asset::getById((int)$parentId);
  437.         if (!$request->get('allowOverwrite')) {
  438.             // check for duplicate filename
  439.             $filename $this->getSafeFilename($parentAsset->getRealFullPath(), $filename);
  440.         }
  441.         if (!$parentAsset->isAllowed('create')) {
  442.             throw $this->createAccessDeniedHttpException(
  443.                 'Missing the permission to create new assets in the folder: ' $parentAsset->getRealFullPath()
  444.             );
  445.         }
  446.         if (is_file($sourcePath) && filesize($sourcePath) < 1) {
  447.             throw new \Exception('File is empty!');
  448.         } elseif (!is_file($sourcePath)) {
  449.             throw new \Exception('Something went wrong, please check upload_max_filesize and post_max_size in your php.ini as well as the write permissions of your temporary directories.');
  450.         }
  451.         if ($request->get('allowOverwrite') && Asset\Service::pathExists($parentAsset->getRealFullPath().'/'.$filename)) {
  452.             $asset Asset::getByPath($parentAsset->getRealFullPath().'/'.$filename);
  453.             $asset->setStream(fopen($sourcePath'rb'falseFile::getContext()));
  454.             $asset->save();
  455.         } else {
  456.             $asset Asset::create($parentId, [
  457.                 'filename' => $filename,
  458.                 'sourcePath' => $sourcePath,
  459.                 'userOwner' => $this->getAdminUser()->getId(),
  460.                 'userModification' => $this->getAdminUser()->getId(),
  461.             ]);
  462.         }
  463.         @unlink($sourcePath);
  464.         return [
  465.             'success' => true,
  466.             'asset' => $asset,
  467.         ];
  468.     }
  469.     /**
  470.      * @param string $targetPath
  471.      * @param string $filename
  472.      *
  473.      * @return string
  474.      */
  475.     protected function getSafeFilename($targetPath$filename)
  476.     {
  477.         $pathinfo pathinfo($filename);
  478.         $originalFilename $pathinfo['filename'];
  479.         $originalFileextension = empty($pathinfo['extension']) ? '' '.' $pathinfo['extension'];
  480.         $count 1;
  481.         if ($targetPath == '/') {
  482.             $targetPath '';
  483.         }
  484.         while (true) {
  485.             if (Asset\Service::pathExists($targetPath '/' $filename)) {
  486.                 $filename $originalFilename '_' $count $originalFileextension;
  487.                 $count++;
  488.             } else {
  489.                 return $filename;
  490.             }
  491.         }
  492.     }
  493.     /**
  494.      * @Route("/replace-asset", name="pimcore_admin_asset_replaceasset", methods={"POST", "PUT"})
  495.      *
  496.      * @param Request $request
  497.      *
  498.      * @return JsonResponse
  499.      *
  500.      * @throws \Exception
  501.      */
  502.     public function replaceAssetAction(Request $request)
  503.     {
  504.         $asset Asset::getById((int) $request->get('id'));
  505.         $newFilename Element\Service::getValidKey($_FILES['Filedata']['name'], 'asset');
  506.         $mimetype MimeTypes::getDefault()->guessMimeType($_FILES['Filedata']['tmp_name']);
  507.         $newType Asset::getTypeFromMimeMapping($mimetype$newFilename);
  508.         if ($newType != $asset->getType()) {
  509.             return $this->adminJson([
  510.                 'success' => false,
  511.                 'message' => sprintf($this->trans('asset_type_change_not_allowed', [], 'admin'), $asset->getType(), $newType),
  512.             ]);
  513.         }
  514.         $stream fopen($_FILES['Filedata']['tmp_name'], 'r+');
  515.         $asset->setStream($stream);
  516.         $asset->setCustomSetting('thumbnails'null);
  517.         $asset->setUserModification($this->getAdminUser()->getId());
  518.         $newFileExt File::getFileExtension($newFilename);
  519.         $currentFileExt File::getFileExtension($asset->getFilename());
  520.         if ($newFileExt != $currentFileExt) {
  521.             $newFilename preg_replace('/\.' $currentFileExt '$/i''.' $newFileExt$asset->getFilename());
  522.             $newFilename Element\Service::getSafeCopyName($newFilename$asset->getParent());
  523.             $asset->setFilename($newFilename);
  524.         }
  525.         if ($asset->isAllowed('publish')) {
  526.             $asset->save();
  527.             $response $this->adminJson([
  528.                 'id' => $asset->getId(),
  529.                 'path' => $asset->getRealFullPath(),
  530.                 'success' => true,
  531.             ]);
  532.             // set content-type to text/html, otherwise (when application/json is sent) chrome will complain in
  533.             // Ext.form.Action.Submit and mark the submission as failed
  534.             $response->headers->set('Content-Type''text/html');
  535.             return $response;
  536.         } else {
  537.             throw new \Exception('missing permission');
  538.         }
  539.     }
  540.     /**
  541.      * @Route("/add-folder", name="pimcore_admin_asset_addfolder", methods={"POST"})
  542.      *
  543.      * @param Request $request
  544.      *
  545.      * @return JsonResponse
  546.      */
  547.     public function addFolderAction(Request $request)
  548.     {
  549.         $success false;
  550.         $parentAsset Asset::getById((int)$request->get('parentId'));
  551.         $equalAsset Asset::getByPath($parentAsset->getRealFullPath() . '/' $request->get('name'));
  552.         if ($parentAsset->isAllowed('create')) {
  553.             if (!$equalAsset) {
  554.                 $asset Asset::create($request->get('parentId'), [
  555.                     'filename' => $request->get('name'),
  556.                     'type' => 'folder',
  557.                     'userOwner' => $this->getAdminUser()->getId(),
  558.                     'userModification' => $this->getAdminUser()->getId(),
  559.                 ]);
  560.                 $success true;
  561.             }
  562.         } else {
  563.             Logger::debug('prevented creating asset because of missing permissions');
  564.         }
  565.         return $this->adminJson(['success' => $success]);
  566.     }
  567.     /**
  568.      * @Route("/delete", name="pimcore_admin_asset_delete", methods={"DELETE"})
  569.      *
  570.      * @param Request $request
  571.      *
  572.      * @return JsonResponse
  573.      */
  574.     public function deleteAction(Request $request)
  575.     {
  576.         $type $request->get('type');
  577.         if ($type === 'childs') {
  578.             trigger_deprecation(
  579.                 'pimcore/pimcore',
  580.                 '10.4',
  581.                 'Type childs is deprecated. Use children instead'
  582.             );
  583.             $type 'children';
  584.         }
  585.         if ($type === 'children') {
  586.             $parentAsset Asset::getById((int) $request->get('id'));
  587.             $list = new Asset\Listing();
  588.             $list->setCondition('path LIKE ?', [Helper::escapeLike($parentAsset->getRealFullPath()) . '/%']);
  589.             $list->setLimit((int)$request->get('amount'));
  590.             $list->setOrderKey('LENGTH(path)'false);
  591.             $list->setOrder('DESC');
  592.             $deletedItems = [];
  593.             foreach ($list as $asset) {
  594.                 $deletedItems[$asset->getId()] = $asset->getRealFullPath();
  595.                 if ($asset->isAllowed('delete') && !$asset->isLocked()) {
  596.                     $asset->delete();
  597.                 }
  598.             }
  599.             return $this->adminJson(['success' => true'deleted' => $deletedItems]);
  600.         }
  601.         if ($request->get('id')) {
  602.             $asset Asset::getById((int) $request->get('id'));
  603.             if ($asset && $asset->isAllowed('delete')) {
  604.                 if ($asset->isLocked()) {
  605.                     return $this->adminJson([
  606.                         'success' => false,
  607.                         'message' => 'prevented deleting asset, because it is locked: ID: ' $asset->getId(),
  608.                     ]);
  609.                 }
  610.                 $asset->delete();
  611.                 return $this->adminJson(['success' => true]);
  612.             }
  613.         }
  614.         throw $this->createAccessDeniedHttpException();
  615.     }
  616.     /**
  617.      * @param Asset $element
  618.      *
  619.      * @return array
  620.      */
  621.     protected function getTreeNodeConfig($element)
  622.     {
  623.         $asset $element;
  624.         $permissions =  $asset->getUserPermissions($this->getAdminUser());
  625.         $tmpAsset = [
  626.             'id' => $asset->getId(),
  627.             'key' => $element->getKey(),
  628.             'text' => htmlspecialchars($asset->getFilename()),
  629.             'type' => $asset->getType(),
  630.             'path' => $asset->getRealFullPath(),
  631.             'basePath' => $asset->getRealPath(),
  632.             'locked' => $asset->isLocked(),
  633.             'lockOwner' => $asset->getLocked() ? true false,
  634.             'elementType' => 'asset',
  635.             'permissions' => [
  636.                 'remove' => $permissions['delete'],
  637.                 'settings' => $permissions['settings'],
  638.                 'rename' => $permissions['rename'],
  639.                 'publish' => $permissions['publish'],
  640.                 'view' => $permissions['view'],
  641.                 'list' => $permissions['list'],
  642.             ],
  643.         ];
  644.         $hasChildren $asset->getDao()->hasChildren($this->getAdminUser());
  645.         // set type specific settings
  646.         if ($asset instanceof Asset\Folder) {
  647.             $tmpAsset['leaf'] = false;
  648.             $tmpAsset['expanded'] = !$hasChildren;
  649.             $tmpAsset['loaded'] = !$hasChildren;
  650.             $tmpAsset['permissions']['create'] = $permissions['create'];
  651.             $tmpAsset['thumbnail'] = $this->getThumbnailUrl($asset, ['origin' => 'treeNode']);
  652.         } else {
  653.             $tmpAsset['leaf'] = true;
  654.             $tmpAsset['expandable'] = false;
  655.             $tmpAsset['expanded'] = false;
  656.         }
  657.         $this->addAdminStyle($assetElementAdminStyleEvent::CONTEXT_TREE$tmpAsset);
  658.         if ($asset instanceof Asset\Image) {
  659.             try {
  660.                 $tmpAsset['thumbnail'] = $this->getThumbnailUrl($asset, ['origin' => 'treeNode']);
  661.                 // we need the dimensions for the wysiwyg editors, so that they can resize the image immediately
  662.                 if ($asset->getCustomSetting('imageDimensionsCalculated')) {
  663.                     $tmpAsset['imageWidth'] = $asset->getCustomSetting('imageWidth');
  664.                     $tmpAsset['imageHeight'] = $asset->getCustomSetting('imageHeight');
  665.                 }
  666.             } catch (\Exception $e) {
  667.                 Logger::debug('Cannot get dimensions of image, seems to be broken.');
  668.             }
  669.         } elseif ($asset->getType() == 'video') {
  670.             try {
  671.                 if (\Pimcore\Video::isAvailable()) {
  672.                     $tmpAsset['thumbnail'] = $this->getThumbnailUrl($asset, ['origin' => 'treeNode']);
  673.                 }
  674.             } catch (\Exception $e) {
  675.                 Logger::debug('Cannot get dimensions of video, seems to be broken.');
  676.             }
  677.         } elseif ($asset->getType() == 'document') {
  678.             try {
  679.                 // add the PDF check here, otherwise the preview layer in admin is shown without content
  680.                 if (\Pimcore\Document::isAvailable() && \Pimcore\Document::isFileTypeSupported($asset->getFilename())) {
  681.                     $tmpAsset['thumbnail'] = $this->getThumbnailUrl($asset, ['origin' => 'treeNode']);
  682.                 }
  683.             } catch (\Exception $e) {
  684.                 Logger::debug('Cannot get dimensions of video, seems to be broken.');
  685.             }
  686.         }
  687.         $tmpAsset['cls'] = '';
  688.         if ($asset->isLocked()) {
  689.             $tmpAsset['cls'] .= 'pimcore_treenode_locked ';
  690.         }
  691.         if ($asset->getLocked()) {
  692.             $tmpAsset['cls'] .= 'pimcore_treenode_lockOwner ';
  693.         }
  694.         return $tmpAsset;
  695.     }
  696.     /**
  697.      * @param Asset $asset
  698.      * @param array $params
  699.      *
  700.      * @return null|string
  701.      */
  702.     protected function getThumbnailUrl(Asset $asset, array $params = [])
  703.     {
  704.         $defaults = [
  705.             'id' => $asset->getId(),
  706.             'treepreview' => true,
  707.             '_dc' => $asset->getModificationDate(),
  708.         ];
  709.         $params array_merge($defaults$params);
  710.         if ($asset instanceof Asset\Image) {
  711.             return $this->generateUrl('pimcore_admin_asset_getimagethumbnail'$params);
  712.         }
  713.         if ($asset instanceof Asset\Folder) {
  714.             return $this->generateUrl('pimcore_admin_asset_getfolderthumbnail'$params);
  715.         }
  716.         if ($asset instanceof Asset\Video && \Pimcore\Video::isAvailable()) {
  717.             return $this->generateUrl('pimcore_admin_asset_getvideothumbnail'$params);
  718.         }
  719.         if ($asset instanceof Asset\Document && \Pimcore\Document::isAvailable() && $asset->getPageCount()) {
  720.             return $this->generateUrl('pimcore_admin_asset_getdocumentthumbnail'$params);
  721.         }
  722.         if ($asset instanceof Asset\Audio) {
  723.             return '/bundles/pimcoreadmin/img/flat-color-icons/speaker.svg';
  724.         }
  725.         if ($asset instanceof Asset) {
  726.             return '/bundles/pimcoreadmin/img/filetype-not-supported.svg';
  727.         }
  728.     }
  729.     /**
  730.      * @Route("/update", name="pimcore_admin_asset_update", methods={"PUT"})
  731.      *
  732.      * @param Request $request
  733.      *
  734.      * @return JsonResponse
  735.      *
  736.      * @throws \Exception
  737.      */
  738.     public function updateAction(Request $request)
  739.     {
  740.         $success false;
  741.         $allowUpdate true;
  742.         $updateData array_merge($request->request->all(), $request->query->all());
  743.         $asset Asset::getById((int) $request->get('id'));
  744.         if ($asset->isAllowed('settings')) {
  745.             $asset->setUserModification($this->getAdminUser()->getId());
  746.             // if the position is changed the path must be changed || also from the children
  747.             if ($parentId $request->get('parentId')) {
  748.                 $parentAsset Asset::getById((int) $parentId);
  749.                 //check if parent is changed i.e. asset is moved
  750.                 if ($asset->getParentId() != $parentAsset->getId()) {
  751.                     if (!$parentAsset->isAllowed('create')) {
  752.                         throw new \Exception('Prevented moving asset - no create permission on new parent ');
  753.                     }
  754.                     $intendedPath $parentAsset->getRealPath();
  755.                     $pKey $parentAsset->getKey();
  756.                     if (!empty($pKey)) {
  757.                         $intendedPath .= $parentAsset->getKey() . '/';
  758.                     }
  759.                     $assetWithSamePath Asset::getByPath($intendedPath $asset->getKey());
  760.                     if ($assetWithSamePath != null) {
  761.                         $allowUpdate false;
  762.                     }
  763.                     if ($asset->isLocked()) {
  764.                         $allowUpdate false;
  765.                     }
  766.                 }
  767.             }
  768.             if ($allowUpdate) {
  769.                 if ($request->get('filename') != $asset->getFilename() && !$asset->isAllowed('rename')) {
  770.                     unset($updateData['filename']);
  771.                     Logger::debug('prevented renaming asset because of missing permissions ');
  772.                 }
  773.                 $asset->setValues($updateData);
  774.                 try {
  775.                     $asset->save();
  776.                     $success true;
  777.                 } catch (\Exception $e) {
  778.                     return $this->adminJson(['success' => false'message' => $e->getMessage()]);
  779.                 }
  780.             } else {
  781.                 $msg 'prevented moving asset, asset with same path+key already exists at target location or the asset is locked. ID: ' $asset->getId();
  782.                 Logger::debug($msg);
  783.                 return $this->adminJson(['success' => $success'message' => $msg]);
  784.             }
  785.         } elseif ($asset->isAllowed('rename') && $request->get('filename')) {
  786.             //just rename
  787.             try {
  788.                 $asset->setFilename($request->get('filename'));
  789.                 $asset->save();
  790.                 $success true;
  791.             } catch (\Exception $e) {
  792.                 return $this->adminJson(['success' => false'message' => $e->getMessage()]);
  793.             }
  794.         } else {
  795.             Logger::debug('prevented update asset because of missing permissions ');
  796.         }
  797.         return $this->adminJson(['success' => $success]);
  798.     }
  799.     /**
  800.      * @Route("/webdav{path}", name="pimcore_admin_webdav", requirements={"path"=".*"})
  801.      */
  802.     public function webdavAction()
  803.     {
  804.         $homeDir Asset::getById(1);
  805.         try {
  806.             $publicDir = new Asset\WebDAV\Folder($homeDir);
  807.             $objectTree = new Asset\WebDAV\Tree($publicDir);
  808.             $server = new \Sabre\DAV\Server($objectTree);
  809.             $server->setBaseUri($this->generateUrl('pimcore_admin_webdav', ['path' => '/']));
  810.             // lock plugin
  811.             /** @var \Doctrine\DBAL\Driver\PDOConnection $pdo */
  812.             $pdo \Pimcore\Db::get()->getWrappedConnection();
  813.             $lockBackend = new \Sabre\DAV\Locks\Backend\PDO($pdo);
  814.             $lockBackend->tableName 'webdav_locks';
  815.             $lockPlugin = new \Sabre\DAV\Locks\Plugin($lockBackend);
  816.             $server->addPlugin($lockPlugin);
  817.             // browser plugin
  818.             $server->addPlugin(new \Sabre\DAV\Browser\Plugin());
  819.             $server->start();
  820.         } catch (\Exception $e) {
  821.             Logger::error((string) $e);
  822.         }
  823.         exit;
  824.     }
  825.     /**
  826.      * @Route("/save", name="pimcore_admin_asset_save", methods={"PUT","POST"})
  827.      *
  828.      * @param Request $request
  829.      * @param EventDispatcherInterface $eventDispatcher
  830.      *
  831.      * @return JsonResponse
  832.      *
  833.      * @throws \Exception
  834.      */
  835.     public function saveAction(Request $requestEventDispatcherInterface $eventDispatcher)
  836.     {
  837.         $asset Asset::getById((int) $request->get('id'));
  838.         if (!$asset) {
  839.             throw $this->createNotFoundException('Asset not found');
  840.         }
  841.         if ($asset->isAllowed('publish')) {
  842.             // metadata
  843.             if ($request->get('metadata')) {
  844.                 $metadata $this->decodeJson($request->get('metadata'));
  845.                 $metadataEvent = new GenericEvent($this, [
  846.                     'id' => $asset->getId(),
  847.                     'metadata' => $metadata,
  848.                 ]);
  849.                 $eventDispatcher->dispatch($metadataEventAdminEvents::ASSET_METADATA_PRE_SET);
  850.                 $metadata $metadataEvent->getArgument('metadata');
  851.                 $metadataValues $metadata['values'];
  852.                 $metadataValues Asset\Service::minimizeMetadata($metadataValues'editor');
  853.                 $asset->setMetadataRaw($metadataValues);
  854.             }
  855.             // properties
  856.             if ($request->get('properties')) {
  857.                 $properties = [];
  858.                 $propertiesData $this->decodeJson($request->get('properties'));
  859.                 if (is_array($propertiesData)) {
  860.                     foreach ($propertiesData as $propertyName => $propertyData) {
  861.                         $value $propertyData['data'];
  862.                         try {
  863.                             $property = new Model\Property();
  864.                             $property->setType($propertyData['type']);
  865.                             $property->setName($propertyName);
  866.                             $property->setCtype('asset');
  867.                             $property->setDataFromEditmode($value);
  868.                             $property->setInheritable($propertyData['inheritable']);
  869.                             $properties[$propertyName] = $property;
  870.                         } catch (\Exception $e) {
  871.                             Logger::err("Can't add " $propertyName ' to asset ' $asset->getRealFullPath());
  872.                         }
  873.                     }
  874.                     $asset->setProperties($properties);
  875.                 }
  876.             }
  877.             $this->applySchedulerDataToElement($request$asset);
  878.             if ($request->get('data')) {
  879.                 $asset->setData($request->get('data'));
  880.             }
  881.             // image specific data
  882.             if ($asset instanceof Asset\Image) {
  883.                 if ($request->get('image')) {
  884.                     $imageData $this->decodeJson($request->get('image'));
  885.                     if (isset($imageData['focalPoint'])) {
  886.                         $asset->setCustomSetting('focalPointX'$imageData['focalPoint']['x']);
  887.                         $asset->setCustomSetting('focalPointY'$imageData['focalPoint']['y']);
  888.                         $asset->removeCustomSetting('disableFocalPointDetection');
  889.                     }
  890.                 } else {
  891.                     // wipe all data
  892.                     $asset->removeCustomSetting('focalPointX');
  893.                     $asset->removeCustomSetting('focalPointY');
  894.                     $asset->setCustomSetting('disableFocalPointDetection'true);
  895.                 }
  896.             }
  897.             $asset->setUserModification($this->getAdminUser()->getId());
  898.             if ($request->get('task') === 'session') {
  899.                 // save to session only
  900.                 Asset\Service::saveElementToSession($asset);
  901.             } else {
  902.                 $asset->save();
  903.             }
  904.             $treeData $this->getTreeNodeConfig($asset);
  905.             return $this->adminJson([
  906.                 'success' => true,
  907.                 'data' => [
  908.                     'versionDate' => $asset->getModificationDate(),
  909.                     'versionCount' => $asset->getVersionCount(),
  910.                 ],
  911.                 'treeData' => $treeData,
  912.             ]);
  913.         } else {
  914.             throw $this->createAccessDeniedHttpException();
  915.         }
  916.     }
  917.     /**
  918.      * @Route("/publish-version", name="pimcore_admin_asset_publishversion", methods={"POST"})
  919.      *
  920.      * @param Request $request
  921.      *
  922.      * @return JsonResponse
  923.      */
  924.     public function publishVersionAction(Request $request)
  925.     {
  926.         $version Model\Version::getById((int) $request->get('id'));
  927.         $asset $version->loadData();
  928.         $currentAsset Asset::getById($asset->getId());
  929.         if ($currentAsset->isAllowed('publish')) {
  930.             try {
  931.                 $asset->setUserModification($this->getAdminUser()->getId());
  932.                 $asset->save();
  933.                 $treeData $this->getTreeNodeConfig($asset);
  934.                 return $this->adminJson(['success' => true'treeData' => $treeData]);
  935.             } catch (\Exception $e) {
  936.                 return $this->adminJson(['success' => false'message' => $e->getMessage()]);
  937.             }
  938.         }
  939.         throw $this->createAccessDeniedHttpException();
  940.     }
  941.     /**
  942.      * @Route("/show-version", name="pimcore_admin_asset_showversion", methods={"GET"})
  943.      *
  944.      * @param Request $request
  945.      *
  946.      * @return Response
  947.      */
  948.     public function showVersionAction(Request $request)
  949.     {
  950.         $id = (int)$request->get('id');
  951.         $version Model\Version::getById($id);
  952.         if (!$version) {
  953.             throw $this->createNotFoundException('Version not found');
  954.         }
  955.         $asset $version->loadData();
  956.         if (!$asset->isAllowed('versions')) {
  957.             throw $this->createAccessDeniedHttpException('Permission denied, version id [' $id ']');
  958.         }
  959.         $loader \Pimcore::getContainer()->get('pimcore.implementation_loader.asset.metadata.data');
  960.         return $this->render(
  961.             '@PimcoreAdmin/Admin/Asset/showVersion' ucfirst($asset->getType()) . '.html.twig',
  962.             [
  963.                 'asset' => $asset,
  964.                 'loader' => $loader,
  965.             ]
  966.         );
  967.     }
  968.     /**
  969.      * @Route("/download", name="pimcore_admin_asset_download", methods={"GET"})
  970.      *
  971.      * @param Request $request
  972.      *
  973.      * @return StreamedResponse
  974.      */
  975.     public function downloadAction(Request $request)
  976.     {
  977.         $asset Asset::getById((int) $request->get('id'));
  978.         if (!$asset) {
  979.             throw $this->createNotFoundException('Asset not found');
  980.         }
  981.         if (!$asset->isAllowed('view')) {
  982.             throw $this->createAccessDeniedException('not allowed to view asset');
  983.         }
  984.         $stream $asset->getStream();
  985.         return new StreamedResponse(function () use ($stream) {
  986.             fpassthru($stream);
  987.         }, 200, [
  988.             'Content-Type' => $asset->getMimeType(),
  989.             'Content-Disposition' => sprintf('attachment; filename="%s"'$asset->getFilename()),
  990.             'Content-Length' => $asset->getFileSize(),
  991.         ]);
  992.     }
  993.     /**
  994.      * @Route("/download-image-thumbnail", name="pimcore_admin_asset_downloadimagethumbnail", methods={"GET"})
  995.      *
  996.      * @param Request $request
  997.      *
  998.      * @return BinaryFileResponse
  999.      */
  1000.     public function downloadImageThumbnailAction(Request $request)
  1001.     {
  1002.         $image Asset\Image::getById((int) $request->get('id'));
  1003.         if (!$image) {
  1004.             throw $this->createNotFoundException('Asset not found');
  1005.         }
  1006.         if (!$image->isAllowed('view')) {
  1007.             throw $this->createAccessDeniedException('not allowed to view thumbnail');
  1008.         }
  1009.         $config null;
  1010.         $thumbnail null;
  1011.         $thumbnailName $request->get('thumbnail');
  1012.         $thumbnailFile null;
  1013.         $deleteThumbnail true;
  1014.         if ($request->get('config')) {
  1015.             $config $this->decodeJson($request->get('config'));
  1016.         } elseif ($request->get('type')) {
  1017.             $predefined = [
  1018.                 'web' => [
  1019.                     'resize_mode' => 'scaleByWidth',
  1020.                     'width' => 3500,
  1021.                     'dpi' => 72,
  1022.                     'format' => 'JPEG',
  1023.                     'quality' => 85,
  1024.                 ],
  1025.                 'print' => [
  1026.                     'resize_mode' => 'scaleByWidth',
  1027.                     'width' => 6000,
  1028.                     'dpi' => 300,
  1029.                     'format' => 'JPEG',
  1030.                     'quality' => 95,
  1031.                 ],
  1032.                 'office' => [
  1033.                     'resize_mode' => 'scaleByWidth',
  1034.                     'width' => 1190,
  1035.                     'dpi' => 144,
  1036.                     'format' => 'JPEG',
  1037.                     'quality' => 90,
  1038.                 ],
  1039.             ];
  1040.             $config $predefined[$request->get('type')];
  1041.         } elseif ($thumbnailName) {
  1042.             $thumbnail $image->getThumbnail($thumbnailName);
  1043.             $deleteThumbnail false;
  1044.         }
  1045.         if ($config) {
  1046.             $thumbnailConfig = new Asset\Image\Thumbnail\Config();
  1047.             $thumbnailConfig->setName('pimcore-download-' $image->getId() . '-' md5($request->get('config')));
  1048.             if ($config['resize_mode'] == 'scaleByWidth') {
  1049.                 $thumbnailConfig->addItem('scaleByWidth', [
  1050.                     'width' => $config['width'],
  1051.                 ]);
  1052.             } elseif ($config['resize_mode'] == 'scaleByHeight') {
  1053.                 $thumbnailConfig->addItem('scaleByHeight', [
  1054.                     'height' => $config['height'],
  1055.                 ]);
  1056.             } else {
  1057.                 $thumbnailConfig->addItem('resize', [
  1058.                     'width' => $config['width'],
  1059.                     'height' => $config['height'],
  1060.                 ]);
  1061.             }
  1062.             $thumbnailConfig->setQuality($config['quality']);
  1063.             $thumbnailConfig->setFormat($config['format']);
  1064.             $thumbnailConfig->setRasterizeSVG(true);
  1065.             if ($thumbnailConfig->getFormat() == 'JPEG') {
  1066.                 $thumbnailConfig->setPreserveMetaData(true);
  1067.                 if (empty($config['quality'])) {
  1068.                     $thumbnailConfig->setPreserveColor(true);
  1069.                 }
  1070.             }
  1071.             $thumbnail $image->getThumbnail($thumbnailConfig);
  1072.             $thumbnailFile $thumbnail->getLocalFile();
  1073.             $exiftool \Pimcore\Tool\Console::getExecutable('exiftool');
  1074.             if ($thumbnailConfig->getFormat() == 'JPEG' && $exiftool && isset($config['dpi']) && $config['dpi']) {
  1075.                 $process = new Process([$exiftool'-overwrite_original''-xresolution=' . (int)$config['dpi'], '-yresolution=' . (int)$config['dpi'], '-resolutionunit=inches'$thumbnailFile]);
  1076.                 $process->run();
  1077.             }
  1078.         }
  1079.         if ($thumbnail) {
  1080.             $thumbnailFile $thumbnailFile ?: $thumbnail->getLocalFile();
  1081.             $downloadFilename preg_replace(
  1082.                 '/\.' preg_quote(File::getFileExtension($image->getFilename())) . '$/i',
  1083.                 '.' $thumbnail->getFileExtension(),
  1084.                 $image->getFilename()
  1085.             );
  1086.             $downloadFilename strtolower($downloadFilename);
  1087.             clearstatcache();
  1088.             $response = new BinaryFileResponse($thumbnailFile);
  1089.             $response->headers->set('Content-Type'$thumbnail->getMimeType());
  1090.             $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT$downloadFilename);
  1091.             $this->addThumbnailCacheHeaders($response);
  1092.             $response->deleteFileAfterSend($deleteThumbnail);
  1093.             return $response;
  1094.         }
  1095.         throw $this->createNotFoundException('Thumbnail not found');
  1096.     }
  1097.     /**
  1098.      * @Route("/get-asset", name="pimcore_admin_asset_getasset", methods={"GET"})
  1099.      *
  1100.      * @param Request $request
  1101.      *
  1102.      * @return StreamedResponse
  1103.      */
  1104.     public function getAssetAction(Request $request)
  1105.     {
  1106.         $image Asset::getById((int)$request->get('id'));
  1107.         if (!$image) {
  1108.             throw $this->createNotFoundException('Asset not found');
  1109.         }
  1110.         if (!$image->isAllowed('view')) {
  1111.             throw $this->createAccessDeniedException('not allowed to view asset');
  1112.         }
  1113.         $stream $image->getStream();
  1114.         $response = new StreamedResponse(function () use ($stream) {
  1115.             fpassthru($stream);
  1116.         }, 200, [
  1117.             'Content-Type' => $image->getMimeType(),
  1118.             'Access-Control-Allow-Origin' => '*',
  1119.         ]);
  1120.         $this->addThumbnailCacheHeaders($response);
  1121.         return $response;
  1122.     }
  1123.     /**
  1124.      * @Route("/get-image-thumbnail", name="pimcore_admin_asset_getimagethumbnail", methods={"GET"})
  1125.      *
  1126.      * @param Request $request
  1127.      *
  1128.      * @return StreamedResponse|JsonResponse|BinaryFileResponse
  1129.      */
  1130.     public function getImageThumbnailAction(Request $request)
  1131.     {
  1132.         $fileinfo $request->get('fileinfo');
  1133.         $image Asset\Image::getById((int)$request->get('id'));
  1134.         if (!$image) {
  1135.             throw $this->createNotFoundException('Asset not found');
  1136.         }
  1137.         if (!$image->isAllowed('view')) {
  1138.             throw $this->createAccessDeniedException('not allowed to view thumbnail');
  1139.         }
  1140.         $thumbnailConfig null;
  1141.         if ($request->get('thumbnail')) {
  1142.             $thumbnailConfig $image->getThumbnailConfig($request->get('thumbnail'));
  1143.         }
  1144.         if (!$thumbnailConfig) {
  1145.             if ($request->get('config')) {
  1146.                 $thumbnailConfig $image->getThumbnailConfig($this->decodeJson($request->get('config')));
  1147.             } else {
  1148.                 $thumbnailConfig $image->getThumbnailConfig(array_merge($request->request->all(), $request->query->all()));
  1149.             }
  1150.         } else {
  1151.             // no high-res images in admin mode (editmode)
  1152.             // this is mostly because of the document's image editable, which doesn't know anything about the thumbnail
  1153.             // configuration, so the dimensions would be incorrect (double the size)
  1154.             $thumbnailConfig->setHighResolution(1);
  1155.         }
  1156.         $format strtolower($thumbnailConfig->getFormat());
  1157.         if ($format == 'source' || $format == 'print') {
  1158.             $thumbnailConfig->setFormat('PNG');
  1159.             $thumbnailConfig->setRasterizeSVG(true);
  1160.         }
  1161.         if ($request->get('treepreview')) {
  1162.             $thumbnailConfig Asset\Image\Thumbnail\Config::getPreviewConfig();
  1163.             if ($request->get('origin') === 'treeNode' && !$image->getThumbnail($thumbnailConfig)->exists()) {
  1164.                 \Pimcore::getContainer()->get('messenger.bus.pimcore-core')->dispatch(
  1165.                     new AssetPreviewImageMessage($image->getId())
  1166.                 );
  1167.                 throw $this->createNotFoundException(sprintf('Tree preview thumbnail not available for asset %s'$image->getId()));
  1168.             }
  1169.         }
  1170.         $cropPercent $request->get('cropPercent');
  1171.         if ($cropPercent && filter_var($cropPercentFILTER_VALIDATE_BOOLEAN)) {
  1172.             $thumbnailConfig->addItemAt(0'cropPercent', [
  1173.                 'width' => $request->get('cropWidth'),
  1174.                 'height' => $request->get('cropHeight'),
  1175.                 'y' => $request->get('cropTop'),
  1176.                 'x' => $request->get('cropLeft'),
  1177.             ]);
  1178.             $hash md5(Tool\Serialize::serialize(array_merge($request->request->all(), $request->query->all())));
  1179.             $thumbnailConfig->setName($thumbnailConfig->getName() . '_auto_' $hash);
  1180.         }
  1181.         $thumbnail $image->getThumbnail($thumbnailConfig);
  1182.         if ($fileinfo) {
  1183.             return $this->adminJson([
  1184.                 'width' => $thumbnail->getWidth(),
  1185.                 'height' => $thumbnail->getHeight(), ]);
  1186.         }
  1187.         $stream $thumbnail->getStream();
  1188.         if (!$stream) {
  1189.             return new BinaryFileResponse(PIMCORE_PATH '/bundles/AdminBundle/Resources/public/img/filetype-not-supported.svg');
  1190.         }
  1191.         $response = new StreamedResponse(function () use ($stream) {
  1192.             fpassthru($stream);
  1193.         }, 200, [
  1194.             'Content-Type' => $thumbnail->getMimeType(),
  1195.             'Access-Control-Allow-Origin''*',
  1196.         ]);
  1197.         $this->addThumbnailCacheHeaders($response);
  1198.         return $response;
  1199.     }
  1200.     /**
  1201.      * @Route("/get-folder-thumbnail", name="pimcore_admin_asset_getfolderthumbnail", methods={"GET"})
  1202.      *
  1203.      * @param Request $request
  1204.      *
  1205.      * @return StreamedResponse
  1206.      */
  1207.     public function getFolderThumbnailAction(Request $request)
  1208.     {
  1209.         $folder null;
  1210.         if ($request->get('id')) {
  1211.             $folder Asset\Folder::getById((int)$request->get('id'));
  1212.             if ($folder instanceof  Asset\Folder) {
  1213.                 if (!$folder->isAllowed('view')) {
  1214.                     throw $this->createAccessDeniedException('not allowed to view thumbnail');
  1215.                 }
  1216.                 $stream $folder->getPreviewImage();
  1217.                 if (!$stream) {
  1218.                     throw $this->createNotFoundException(sprintf('Tree preview thumbnail not available for asset %s'$folder->getId()));
  1219.                 } else {
  1220.                     $response = new StreamedResponse(function () use ($stream) {
  1221.                         fpassthru($stream);
  1222.                     }, 200, [
  1223.                         'Content-Type' => 'image/jpg',
  1224.                     ]);
  1225.                 }
  1226.                 $this->addThumbnailCacheHeaders($response);
  1227.                 return $response;
  1228.             }
  1229.         }
  1230.         throw $this->createNotFoundException('could not load asset folder');
  1231.     }
  1232.     /**
  1233.      * @Route("/get-video-thumbnail", name="pimcore_admin_asset_getvideothumbnail", methods={"GET"})
  1234.      *
  1235.      * @param Request $request
  1236.      *
  1237.      * @return StreamedResponse
  1238.      */
  1239.     public function getVideoThumbnailAction(Request $request)
  1240.     {
  1241.         $video null;
  1242.         if ($request->get('id')) {
  1243.             $video Asset\Video::getById((int)$request->get('id'));
  1244.         } elseif ($request->get('path')) {
  1245.             $video Asset\Video::getByPath($request->get('path'));
  1246.         }
  1247.         if (!$video) {
  1248.             throw $this->createNotFoundException('could not load video asset');
  1249.         }
  1250.         if (!$video->isAllowed('view')) {
  1251.             throw $this->createAccessDeniedException('not allowed to view thumbnail');
  1252.         }
  1253.         $thumbnail array_merge($request->request->all(), $request->query->all());
  1254.         if ($request->get('treepreview')) {
  1255.             $thumbnail Asset\Image\Thumbnail\Config::getPreviewConfig();
  1256.         }
  1257.         $time null;
  1258.         if (is_numeric($request->get('time'))) {
  1259.             $time = (int)$request->get('time');
  1260.         }
  1261.         if ($request->get('settime')) {
  1262.             $video->removeCustomSetting('image_thumbnail_asset');
  1263.             $video->setCustomSetting('image_thumbnail_time'$time);
  1264.             $video->save();
  1265.         }
  1266.         $image null;
  1267.         if ($request->get('image')) {
  1268.             $image Asset\Image::getById((int)$request->get('image'));
  1269.         }
  1270.         if ($request->get('setimage') && $image) {
  1271.             $video->removeCustomSetting('image_thumbnail_time');
  1272.             $video->setCustomSetting('image_thumbnail_asset'$image->getId());
  1273.             $video->save();
  1274.         }
  1275.         $thumb $video->getImageThumbnail($thumbnail$time$image);
  1276.         if ($request->get('origin') === 'treeNode' && !$thumb->exists()) {
  1277.             \Pimcore::getContainer()->get('messenger.bus.pimcore-core')->dispatch(
  1278.                 new AssetPreviewImageMessage($video->getId())
  1279.             );
  1280.             throw $this->createNotFoundException(sprintf('Tree preview thumbnail not available for asset %s'$video->getId()));
  1281.         }
  1282.         $stream $thumb->getStream();
  1283.         if (!$stream) {
  1284.             throw $this->createNotFoundException('Unable to get video thumbnail for video ' $video->getId());
  1285.         }
  1286.         $response = new StreamedResponse(function () use ($stream) {
  1287.             fpassthru($stream);
  1288.         }, 200, [
  1289.             'Content-Type' => 'image/' $thumb->getFileExtension(),
  1290.         ]);
  1291.         $this->addThumbnailCacheHeaders($response);
  1292.         return $response;
  1293.     }
  1294.     /**
  1295.      * @Route("/get-document-thumbnail", name="pimcore_admin_asset_getdocumentthumbnail", methods={"GET"})
  1296.      *
  1297.      * @param Request $request
  1298.      *
  1299.      * @return StreamedResponse|BinaryFileResponse
  1300.      */
  1301.     public function getDocumentThumbnailAction(Request $request)
  1302.     {
  1303.         $document Asset\Document::getById((int)$request->get('id'));
  1304.         if (!$document) {
  1305.             throw $this->createNotFoundException('could not load document asset');
  1306.         }
  1307.         if (!$document->isAllowed('view')) {
  1308.             throw $this->createAccessDeniedException('not allowed to view thumbnail');
  1309.         }
  1310.         $thumbnail Asset\Image\Thumbnail\Config::getByAutoDetect(array_merge($request->request->all(), $request->query->all()));
  1311.         $format strtolower($thumbnail->getFormat());
  1312.         if ($format == 'source') {
  1313.             $thumbnail->setFormat('jpeg'); // default format for documents is JPEG not PNG (=too big)
  1314.         }
  1315.         if ($request->get('treepreview')) {
  1316.             $thumbnail Asset\Image\Thumbnail\Config::getPreviewConfig();
  1317.         }
  1318.         $page 1;
  1319.         if (is_numeric($request->get('page'))) {
  1320.             $page = (int)$request->get('page');
  1321.         }
  1322.         $thumb $document->getImageThumbnail($thumbnail$page);
  1323.         if ($request->get('origin') === 'treeNode' && !$thumb->exists()) {
  1324.             \Pimcore::getContainer()->get('messenger.bus.pimcore-core')->dispatch(
  1325.                 new AssetPreviewImageMessage($document->getId())
  1326.             );
  1327.             throw $this->createNotFoundException(sprintf('Tree preview thumbnail not available for asset %s'$document->getId()));
  1328.         }
  1329.         $stream $thumb->getStream();
  1330.         if ($stream) {
  1331.             $response = new StreamedResponse(function () use ($stream) {
  1332.                 fpassthru($stream);
  1333.             }, 200, [
  1334.                 'Content-Type' => 'image/' $thumb->getFileExtension(),
  1335.             ]);
  1336.         } else {
  1337.             $response = new BinaryFileResponse(PIMCORE_PATH '/bundles/AdminBundle/Resources/public/img/filetype-not-supported.svg');
  1338.         }
  1339.         $this->addThumbnailCacheHeaders($response);
  1340.         return $response;
  1341.     }
  1342.     /**
  1343.      * @param Response $response
  1344.      */
  1345.     protected function addThumbnailCacheHeaders(Response $response)
  1346.     {
  1347.         $lifetime 300;
  1348.         $date = new \DateTime('now');
  1349.         $date->add(new \DateInterval('PT' $lifetime 'S'));
  1350.         $response->setMaxAge($lifetime);
  1351.         $response->setPublic();
  1352.         $response->setExpires($date);
  1353.         $response->headers->set('Pragma''');
  1354.     }
  1355.     /**
  1356.      * @Route("/get-preview-document", name="pimcore_admin_asset_getpreviewdocument", methods={"GET"})
  1357.      *
  1358.      * @param Request $request
  1359.      *
  1360.      * @return StreamedResponse
  1361.      */
  1362.     public function getPreviewDocumentAction(Request $request)
  1363.     {
  1364.         $asset Asset\Document::getById((int) $request->get('id'));
  1365.         if (!$asset) {
  1366.             throw $this->createNotFoundException('could not load document asset');
  1367.         }
  1368.         if ($asset->isAllowed('view')) {
  1369.             $stream $this->getDocumentPreviewPdf($asset);
  1370.             if ($stream) {
  1371.                 return new StreamedResponse(function () use ($stream) {
  1372.                     fpassthru($stream);
  1373.                 }, 200, [
  1374.                     'Content-Type' => 'application/pdf',
  1375.                 ]);
  1376.             } else {
  1377.                 throw $this->createNotFoundException('Unable to get preview for asset ' $asset->getId());
  1378.             }
  1379.         } else {
  1380.             throw $this->createAccessDeniedException('Access to asset ' $asset->getId() . ' denied');
  1381.         }
  1382.     }
  1383.     /**
  1384.      * @param Asset\Document $asset
  1385.      *
  1386.      * @return resource|null
  1387.      */
  1388.     protected function getDocumentPreviewPdf(Asset\Document $asset)
  1389.     {
  1390.         $stream null;
  1391.         if ($asset->getMimeType() == 'application/pdf') {
  1392.             $stream $asset->getStream();
  1393.         }
  1394.         if (!$stream && $asset->getPageCount() && \Pimcore\Document::isAvailable() && \Pimcore\Document::isFileTypeSupported($asset->getFilename())) {
  1395.             try {
  1396.                 $document \Pimcore\Document::getInstance();
  1397.                 $stream $document->getPdf($asset);
  1398.             } catch (\Exception $e) {
  1399.                 // nothing to do
  1400.             }
  1401.         }
  1402.         return $stream;
  1403.     }
  1404.     /**
  1405.      * @Route("/get-preview-video", name="pimcore_admin_asset_getpreviewvideo", methods={"GET"})
  1406.      *
  1407.      * @param Request $request
  1408.      *
  1409.      * @return Response
  1410.      */
  1411.     public function getPreviewVideoAction(Request $request)
  1412.     {
  1413.         $asset Asset\Video::getById((int) $request->get('id'));
  1414.         if (!$asset) {
  1415.             throw $this->createNotFoundException('could not load video asset');
  1416.         }
  1417.         if (!$asset->isAllowed('view')) {
  1418.             throw $this->createAccessDeniedException('not allowed to preview');
  1419.         }
  1420.         $previewData = ['asset' => $asset];
  1421.         $config Asset\Video\Thumbnail\Config::getPreviewConfig();
  1422.         $thumbnail $asset->getThumbnail($config, ['mp4']);
  1423.         if ($thumbnail) {
  1424.             $previewData['asset'] = $asset;
  1425.             $previewData['thumbnail'] = $thumbnail;
  1426.             if ($thumbnail['status'] == 'finished') {
  1427.                 return $this->render(
  1428.                     '@PimcoreAdmin/Admin/Asset/getPreviewVideoDisplay.html.twig',
  1429.                     $previewData
  1430.                 );
  1431.             } else {
  1432.                 return $this->render(
  1433.                     '@PimcoreAdmin/Admin/Asset/getPreviewVideoError.html.twig',
  1434.                     $previewData
  1435.                 );
  1436.             }
  1437.         } else {
  1438.             return $this->render(
  1439.                 '@PimcoreAdmin/Admin/Asset/getPreviewVideoError.html.twig',
  1440.                 $previewData
  1441.             );
  1442.         }
  1443.     }
  1444.     /**
  1445.      * @Route("/serve-video-preview", name="pimcore_admin_asset_servevideopreview", methods={"GET"})
  1446.      *
  1447.      * @param Request $request
  1448.      *
  1449.      * @return StreamedResponse
  1450.      */
  1451.     public function serveVideoPreviewAction(Request $request)
  1452.     {
  1453.         $asset Asset\Video::getById((int) $request->get('id'));
  1454.         if (!$asset) {
  1455.             throw $this->createNotFoundException('could not load video asset');
  1456.         }
  1457.         if (!$asset->isAllowed('view')) {
  1458.             throw $this->createAccessDeniedException('not allowed to preview');
  1459.         }
  1460.         $config Asset\Video\Thumbnail\Config::getPreviewConfig();
  1461.         $thumbnail $asset->getThumbnail($config, ['mp4']);
  1462.         $storagePath $asset->getRealPath() . '/' preg_replace('@^' preg_quote($asset->getPath(), '@') . '@'''urldecode($thumbnail['formats']['mp4']));
  1463.         $storage Tool\Storage::get('thumbnail');
  1464.         if ($storage->fileExists($storagePath)) {
  1465.             $fs $storage->fileSize($storagePath);
  1466.             $stream $storage->readStream($storagePath);
  1467.             return new StreamedResponse(function () use ($stream) {
  1468.                 fpassthru($stream);
  1469.             }, 200, [
  1470.                 'Content-Type' => 'video/mp4',
  1471.                 'Content-Length' => $fs,
  1472.                 'Accept-Ranges' => 'bytes',
  1473.             ]);
  1474.         } else {
  1475.             throw $this->createNotFoundException('Video thumbnail not found');
  1476.         }
  1477.     }
  1478.     /**
  1479.      * @Route("/image-editor", name="pimcore_admin_asset_imageeditor", methods={"GET"})
  1480.      *
  1481.      * @param Request $request
  1482.      *
  1483.      * @return Response
  1484.      */
  1485.     public function imageEditorAction(Request $request)
  1486.     {
  1487.         $asset Asset::getById((int) $request->get('id'));
  1488.         if (!$asset->isAllowed('view')) {
  1489.             throw $this->createAccessDeniedException('Not allowed to preview');
  1490.         }
  1491.         return $this->render(
  1492.             '@PimcoreAdmin/Admin/Asset/imageEditor.html.twig',
  1493.             ['asset' => $asset]
  1494.         );
  1495.     }
  1496.     /**
  1497.      * @Route("/image-editor-save", name="pimcore_admin_asset_imageeditorsave", methods={"PUT"})
  1498.      *
  1499.      * @param Request $request
  1500.      *
  1501.      * @return JsonResponse
  1502.      */
  1503.     public function imageEditorSaveAction(Request $request)
  1504.     {
  1505.         $asset Asset::getById((int) $request->get('id'));
  1506.         if (!$asset) {
  1507.             throw $this->createNotFoundException('Asset not found');
  1508.         }
  1509.         if (!$asset->isAllowed('publish')) {
  1510.             throw $this->createAccessDeniedException('not allowed to publish');
  1511.         }
  1512.         $data $request->get('dataUri');
  1513.         $data substr($datastrpos($data','));
  1514.         $data base64_decode($data);
  1515.         $asset->setData($data);
  1516.         $asset->setUserModification($this->getAdminUser()->getId());
  1517.         $asset->save();
  1518.         return $this->adminJson(['success' => true]);
  1519.     }
  1520.     /**
  1521.      * @Route("/get-folder-content-preview", name="pimcore_admin_asset_getfoldercontentpreview", methods={"GET"})
  1522.      *
  1523.      * @param Request $request
  1524.      *
  1525.      * @return JsonResponse
  1526.      */
  1527.     public function getFolderContentPreviewAction(Request $requestEventDispatcherInterface $eventDispatcher)
  1528.     {
  1529.         $allParams array_merge($request->request->all(), $request->query->all());
  1530.         $filterPrepareEvent = new GenericEvent($this, [
  1531.             'requestParams' => $allParams,
  1532.         ]);
  1533.         $eventDispatcher->dispatch($filterPrepareEventAdminEvents::ASSET_LIST_BEFORE_FILTER_PREPARE);
  1534.         $allParams $filterPrepareEvent->getArgument('requestParams');
  1535.         $folder Asset::getById($allParams['id']);
  1536.         $start 0;
  1537.         $limit 10;
  1538.         if ($allParams['limit']) {
  1539.             $limit $allParams['limit'];
  1540.         }
  1541.         if ($allParams['start']) {
  1542.             $start $allParams['start'];
  1543.         }
  1544.         $conditionFilters = [];
  1545.         $list = new Asset\Listing();
  1546.         $conditionFilters[] = 'path LIKE ' . ($folder->getRealFullPath() == '/' "'/%'" $list->quote(Helper::escapeLike($folder->getRealFullPath()) . '/%')) . " AND type != 'folder'";
  1547.         if (!$this->getAdminUser()->isAdmin()) {
  1548.             $userIds $this->getAdminUser()->getRoles();
  1549.             $userIds[] = $this->getAdminUser()->getId();
  1550.             $conditionFilters[] = ' (
  1551.                                                     (select list from users_workspaces_asset where userId in (' implode(','$userIds) . ') and LOCATE(CONCAT(path, filename),cpath)=1  ORDER BY LENGTH(cpath) DESC LIMIT 1)=1
  1552.                                                     OR
  1553.                                                     (select list from users_workspaces_asset where userId in (' implode(','$userIds) . ') and LOCATE(cpath,CONCAT(path, filename))=1  ORDER BY LENGTH(cpath) DESC LIMIT 1)=1
  1554.                                                  )';
  1555.         }
  1556.         $condition implode(' AND '$conditionFilters);
  1557.         $list->setCondition($condition);
  1558.         $list->setLimit($limit);
  1559.         $list->setOffset($start);
  1560.         $list->setOrderKey('CAST(filename AS CHAR CHARACTER SET utf8) COLLATE utf8_general_ci ASC'false);
  1561.         $beforeListLoadEvent = new GenericEvent($this, [
  1562.             'list' => $list,
  1563.             'context' => $allParams,
  1564.         ]);
  1565.         $eventDispatcher->dispatch($beforeListLoadEventAdminEvents::ASSET_LIST_BEFORE_LIST_LOAD);
  1566.         /** @var Asset\Listing $list */
  1567.         $list $beforeListLoadEvent->getArgument('list');
  1568.         $list->load();
  1569.         $assets = [];
  1570.         foreach ($list as $asset) {
  1571.             $filenameDisplay $asset->getFilename();
  1572.             if (strlen($filenameDisplay) > 32) {
  1573.                 $filenameDisplay substr($filenameDisplay025) . '...' \Pimcore\File::getFileExtension($filenameDisplay);
  1574.             }
  1575.             // Like for treeGetChildsByIdAction, so we respect isAllowed method which can be extended (object DI) for custom permissions, so relying only users_workspaces_asset is insufficient and could lead security breach
  1576.             if ($asset->isAllowed('list')) {
  1577.                 $assets[] = [
  1578.                     'id' => $asset->getId(),
  1579.                     'type' => $asset->getType(),
  1580.                     'filename' => $asset->getFilename(),
  1581.                     'filenameDisplay' => htmlspecialchars($filenameDisplay),
  1582.                     'url' => $this->getThumbnailUrl($asset),
  1583.                     'idPath' => $data['idPath'] = Element\Service::getIdPath($asset),
  1584.                 ];
  1585.             }
  1586.         }
  1587.         // We need to temporary use data key to be compatible with the ASSET_LIST_AFTER_LIST_LOAD global event
  1588.         $result = ['data' => $assets'success' => true'total' => $list->getTotalCount()];
  1589.         $afterListLoadEvent = new GenericEvent($this, [
  1590.             'list' => $result,
  1591.             'context' => $allParams,
  1592.         ]);
  1593.         $eventDispatcher->dispatch($afterListLoadEventAdminEvents::ASSET_LIST_AFTER_LIST_LOAD);
  1594.         $result $afterListLoadEvent->getArgument('list');
  1595.         // Here we revert to assets key
  1596.         return $this->adminJson(['assets' => $result['data'], 'success' => $result['success'], 'total' => $result['total']]);
  1597.     }
  1598.     /**
  1599.      * @Route("/copy-info", name="pimcore_admin_asset_copyinfo", methods={"GET"})
  1600.      *
  1601.      * @param Request $request
  1602.      *
  1603.      * @return JsonResponse
  1604.      */
  1605.     public function copyInfoAction(Request $request)
  1606.     {
  1607.         $transactionId time();
  1608.         $pasteJobs = [];
  1609.         Tool\Session::useSession(function (AttributeBagInterface $session) use ($transactionId) {
  1610.             $session->set((string) $transactionId, []);
  1611.         }, 'pimcore_copy');
  1612.         if ($request->get('type') == 'recursive') {
  1613.             $asset Asset::getById((int) $request->get('sourceId'));
  1614.             if (!$asset) {
  1615.                 throw $this->createNotFoundException('Source not found');
  1616.             }
  1617.             // first of all the new parent
  1618.             $pasteJobs[] = [[
  1619.                 'url' => $this->generateUrl('pimcore_admin_asset_copy'),
  1620.                 'method' => 'POST',
  1621.                 'params' => [
  1622.                     'sourceId' => $request->get('sourceId'),
  1623.                     'targetId' => $request->get('targetId'),
  1624.                     'type' => 'child',
  1625.                     'transactionId' => $transactionId,
  1626.                     'saveParentId' => true,
  1627.                 ],
  1628.             ]];
  1629.             if ($asset->hasChildren()) {
  1630.                 // get amount of children
  1631.                 $list = new Asset\Listing();
  1632.                 $list->setCondition('path LIKE ?', [$list->escapeLike($asset->getRealFullPath()) . '/%']);
  1633.                 $list->setOrderKey('LENGTH(path)'false);
  1634.                 $list->setOrder('ASC');
  1635.                 $childIds $list->loadIdList();
  1636.                 if (count($childIds) > 0) {
  1637.                     foreach ($childIds as $id) {
  1638.                         $pasteJobs[] = [[
  1639.                             'url' => $this->generateUrl('pimcore_admin_asset_copy'),
  1640.                             'method' => 'POST',
  1641.                             'params' => [
  1642.                                 'sourceId' => $id,
  1643.                                 'targetParentId' => $request->get('targetId'),
  1644.                                 'sourceParentId' => $request->get('sourceId'),
  1645.                                 'type' => 'child',
  1646.                                 'transactionId' => $transactionId,
  1647.                             ],
  1648.                         ]];
  1649.                     }
  1650.                 }
  1651.             }
  1652.         } elseif ($request->get('type') == 'child' || $request->get('type') == 'replace') {
  1653.             // the object itself is the last one
  1654.             $pasteJobs[] = [[
  1655.                 'url' => $this->generateUrl('pimcore_admin_asset_copy'),
  1656.                 'method' => 'POST',
  1657.                 'params' => [
  1658.                     'sourceId' => $request->get('sourceId'),
  1659.                     'targetId' => $request->get('targetId'),
  1660.                     'type' => $request->get('type'),
  1661.                     'transactionId' => $transactionId,
  1662.                 ],
  1663.             ]];
  1664.         }
  1665.         return $this->adminJson([
  1666.             'pastejobs' => $pasteJobs,
  1667.         ]);
  1668.     }
  1669.     /**
  1670.      * @Route("/copy", name="pimcore_admin_asset_copy", methods={"POST"})
  1671.      *
  1672.      * @param Request $request
  1673.      *
  1674.      * @return JsonResponse
  1675.      */
  1676.     public function copyAction(Request $request)
  1677.     {
  1678.         $success false;
  1679.         $sourceId = (int)$request->get('sourceId');
  1680.         $source Asset::getById($sourceId);
  1681.         $session Tool\Session::get('pimcore_copy');
  1682.         $sessionBag $session->get($request->get('transactionId'));
  1683.         $targetId = (int)$request->get('targetId');
  1684.         if ($request->get('targetParentId')) {
  1685.             $sourceParent Asset::getById((int) $request->get('sourceParentId'));
  1686.             // this is because the key can get the prefix "_copy" if the target does already exists
  1687.             if ($sessionBag['parentId']) {
  1688.                 $targetParent Asset::getById($sessionBag['parentId']);
  1689.             } else {
  1690.                 $targetParent Asset::getById((int) $request->get('targetParentId'));
  1691.             }
  1692.             $targetPath preg_replace('@^' $sourceParent->getRealFullPath() . '@'$targetParent '/'$source->getRealPath());
  1693.             $target Asset::getByPath($targetPath);
  1694.         } else {
  1695.             $target Asset::getById($targetId);
  1696.         }
  1697.         if (!$target) {
  1698.             throw $this->createNotFoundException('Target not found');
  1699.         }
  1700.         if ($target->isAllowed('create')) {
  1701.             $source Asset::getById($sourceId);
  1702.             if ($source != null) {
  1703.                 if ($request->get('type') == 'child') {
  1704.                     $newAsset $this->_assetService->copyAsChild($target$source);
  1705.                     // this is because the key can get the prefix "_copy" if the target does already exists
  1706.                     if ($request->get('saveParentId')) {
  1707.                         $sessionBag['parentId'] = $newAsset->getId();
  1708.                     }
  1709.                 } elseif ($request->get('type') == 'replace') {
  1710.                     $this->_assetService->copyContents($target$source);
  1711.                 }
  1712.                 $session->set($request->get('transactionId'), $sessionBag);
  1713.                 Tool\Session::writeClose();
  1714.                 $success true;
  1715.             } else {
  1716.                 Logger::debug('prevended copy/paste because asset with same path+key already exists in this location');
  1717.             }
  1718.         } else {
  1719.             Logger::error('could not execute copy/paste because of missing permissions on target [ ' $targetId ' ]');
  1720.             throw $this->createAccessDeniedHttpException();
  1721.         }
  1722.         Tool\Session::writeClose();
  1723.         return $this->adminJson(['success' => $success]);
  1724.     }
  1725.     /**
  1726.      * @Route("/download-as-zip-jobs", name="pimcore_admin_asset_downloadaszipjobs", methods={"GET"})
  1727.      *
  1728.      * @param Request $request
  1729.      *
  1730.      * @return JsonResponse
  1731.      */
  1732.     public function downloadAsZipJobsAction(Request $request)
  1733.     {
  1734.         $jobId uniqid();
  1735.         $filesPerJob 5;
  1736.         $jobs = [];
  1737.         $asset Asset::getById((int) $request->get('id'));
  1738.         if (!$asset) {
  1739.             throw $this->createNotFoundException('Asset not found');
  1740.         }
  1741.         if ($asset->isAllowed('view')) {
  1742.             $parentPath $asset->getRealFullPath();
  1743.             if ($asset->getId() == 1) {
  1744.                 $parentPath '';
  1745.             }
  1746.             $db \Pimcore\Db::get();
  1747.             $conditionFilters = [];
  1748.             $selectedIds explode(','$request->get('selectedIds'''));
  1749.             $quotedSelectedIds = [];
  1750.             foreach ($selectedIds as $selectedId) {
  1751.                 if ($selectedId) {
  1752.                     $quotedSelectedIds[] = $db->quote($selectedId);
  1753.                 }
  1754.             }
  1755.             if (!empty($quotedSelectedIds)) {
  1756.                 //add a condition if id numbers are specified
  1757.                 $conditionFilters[] = 'id IN (' implode(','$quotedSelectedIds) . ')';
  1758.             }
  1759.             $conditionFilters[] = 'path LIKE ' $db->quote(Helper::escapeLike($parentPath) . '/%') . ' AND type != ' $db->quote('folder');
  1760.             if (!$this->getAdminUser()->isAdmin()) {
  1761.                 $userIds $this->getAdminUser()->getRoles();
  1762.                 $userIds[] = $this->getAdminUser()->getId();
  1763.                 $conditionFilters[] = ' (
  1764.                                                     (select list from users_workspaces_asset where userId in (' implode(','$userIds) . ') and LOCATE(CONCAT(path, filename),cpath)=1  ORDER BY LENGTH(cpath) DESC LIMIT 1)=1
  1765.                                                     OR
  1766.                                                     (select list from users_workspaces_asset where userId in (' implode(','$userIds) . ') and LOCATE(cpath,CONCAT(path, filename))=1  ORDER BY LENGTH(cpath) DESC LIMIT 1)=1
  1767.                                                  )';
  1768.             }
  1769.             $condition implode(' AND '$conditionFilters);
  1770.             $assetList = new Asset\Listing();
  1771.             $assetList->setCondition($condition);
  1772.             $assetList->setOrderKey('LENGTH(path)'false);
  1773.             $assetList->setOrder('ASC');
  1774.             for ($i 0$i ceil($assetList->getTotalCount() / $filesPerJob); $i++) {
  1775.                 $jobs[] = [[
  1776.                     'url' => $this->generateUrl('pimcore_admin_asset_downloadaszipaddfiles'),
  1777.                     'method' => 'GET',
  1778.                     'params' => [
  1779.                         'id' => $asset->getId(),
  1780.                         'selectedIds' => implode(','$selectedIds),
  1781.                         'offset' => $i $filesPerJob,
  1782.                         'limit' => $filesPerJob,
  1783.                         'jobId' => $jobId,
  1784.                     ],
  1785.                 ]];
  1786.             }
  1787.         }
  1788.         return $this->adminJson([
  1789.             'success' => true,
  1790.             'jobs' => $jobs,
  1791.             'jobId' => $jobId,
  1792.         ]);
  1793.     }
  1794.     /**
  1795.      * @Route("/download-as-zip-add-files", name="pimcore_admin_asset_downloadaszipaddfiles", methods={"GET"})
  1796.      *
  1797.      * @param Request $request
  1798.      *
  1799.      * @return JsonResponse
  1800.      */
  1801.     public function downloadAsZipAddFilesAction(Request $request)
  1802.     {
  1803.         $zipFile PIMCORE_SYSTEM_TEMP_DIRECTORY '/download-zip-' $request->get('jobId') . '.zip';
  1804.         $asset Asset::getById((int) $request->get('id'));
  1805.         $success false;
  1806.         if (!$asset) {
  1807.             throw $this->createNotFoundException('Asset not found');
  1808.         }
  1809.         if ($asset->isAllowed('view')) {
  1810.             $zip = new \ZipArchive();
  1811.             if (!is_file($zipFile)) {
  1812.                 $zipState $zip->open($zipFile\ZipArchive::CREATE);
  1813.             } else {
  1814.                 $zipState $zip->open($zipFile);
  1815.             }
  1816.             if ($zipState === true) {
  1817.                 $parentPath $asset->getRealFullPath();
  1818.                 if ($asset->getId() == 1) {
  1819.                     $parentPath '';
  1820.                 }
  1821.                 $db \Pimcore\Db::get();
  1822.                 $conditionFilters = [];
  1823.                 $selectedIds $request->get('selectedIds', []);
  1824.                 if (!empty($selectedIds)) {
  1825.                     $selectedIds explode(','$selectedIds);
  1826.                     //add a condition if id numbers are specified
  1827.                     $conditionFilters[] = 'id IN (' implode(','$selectedIds) . ')';
  1828.                 }
  1829.                 $conditionFilters[] = "type != 'folder' AND path LIKE " $db->quote(Helper::escapeLike($parentPath) . '/%');
  1830.                 if (!$this->getAdminUser()->isAdmin()) {
  1831.                     $userIds $this->getAdminUser()->getRoles();
  1832.                     $userIds[] = $this->getAdminUser()->getId();
  1833.                     $conditionFilters[] = ' (
  1834.                                                     (select list from users_workspaces_asset where userId in (' implode(','$userIds) . ') and LOCATE(CONCAT(path, filename),cpath)=1  ORDER BY LENGTH(cpath) DESC LIMIT 1)=1
  1835.                                                     OR
  1836.                                                     (select list from users_workspaces_asset where userId in (' implode(','$userIds) . ') and LOCATE(cpath,CONCAT(path, filename))=1  ORDER BY LENGTH(cpath) DESC LIMIT 1)=1
  1837.                                                  )';
  1838.                 }
  1839.                 $condition implode(' AND '$conditionFilters);
  1840.                 $assetList = new Asset\Listing();
  1841.                 $assetList->setCondition($condition);
  1842.                 $assetList->setOrderKey('LENGTH(path) ASC, id ASC'false);
  1843.                 $assetList->setOffset((int)$request->get('offset'));
  1844.                 $assetList->setLimit((int)$request->get('limit'));
  1845.                 foreach ($assetList as $a) {
  1846.                     if ($a->isAllowed('view')) {
  1847.                         if (!$a instanceof Asset\Folder) {
  1848.                             // add the file with the relative path to the parent directory
  1849.                             $zip->addFile($a->getLocalFile(), preg_replace('@^' preg_quote($asset->getRealPath(), '@') . '@i'''$a->getRealFullPath()));
  1850.                         }
  1851.                     }
  1852.                 }
  1853.                 $zip->close();
  1854.                 $success true;
  1855.             }
  1856.         }
  1857.         return $this->adminJson([
  1858.             'success' => $success,
  1859.         ]);
  1860.     }
  1861.     /**
  1862.      * @Route("/download-as-zip", name="pimcore_admin_asset_downloadaszip", methods={"GET"})
  1863.      *
  1864.      * @param Request $request
  1865.      *
  1866.      * @return BinaryFileResponse
  1867.      * Download all assets contained in the folder with parameter id as ZIP file.
  1868.      * The suggested filename is either [folder name].zip or assets.zip for the root folder.
  1869.      */
  1870.     public function downloadAsZipAction(Request $request)
  1871.     {
  1872.         $asset Asset::getById((int) $request->get('id'));
  1873.         if (!$asset) {
  1874.             throw $this->createNotFoundException('Asset not found');
  1875.         }
  1876.         $zipFile PIMCORE_SYSTEM_TEMP_DIRECTORY '/download-zip-' $request->get('jobId') . '.zip';
  1877.         $suggestedFilename $asset->getFilename();
  1878.         if (empty($suggestedFilename)) {
  1879.             $suggestedFilename 'assets';
  1880.         }
  1881.         $response = new BinaryFileResponse($zipFile);
  1882.         $response->headers->set('Content-Type''application/zip');
  1883.         $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT$suggestedFilename '.zip');
  1884.         $response->deleteFileAfterSend(true);
  1885.         return $response;
  1886.     }
  1887.     /**
  1888.      * @Route("/import-zip", name="pimcore_admin_asset_importzip", methods={"POST"})
  1889.      *
  1890.      * @param Request $request
  1891.      *
  1892.      * @return Response
  1893.      */
  1894.     public function importZipAction(Request $request)
  1895.     {
  1896.         $jobId uniqid();
  1897.         $filesPerJob 5;
  1898.         $jobs = [];
  1899.         $asset Asset::getById((int) $request->get('parentId'));
  1900.         if (!is_file($_FILES['Filedata']['tmp_name'])) {
  1901.             return $this->adminJson([
  1902.                 'success' => false,
  1903.                 'message' => 'Something went wrong, please check upload_max_filesize and post_max_size in your php.ini as well as the write permissions on the file system',
  1904.             ]);
  1905.         }
  1906.         if (!$asset) {
  1907.             throw $this->createNotFoundException('Parent asset not found');
  1908.         }
  1909.         if (!$asset->isAllowed('create')) {
  1910.             throw $this->createAccessDeniedException('not allowed to create');
  1911.         }
  1912.         $zipFile PIMCORE_SYSTEM_TEMP_DIRECTORY '/' $jobId '.zip';
  1913.         copy($_FILES['Filedata']['tmp_name'], $zipFile);
  1914.         $zip = new \ZipArchive;
  1915.         $retCode $zip->open($zipFile);
  1916.         if ($retCode === true) {
  1917.             $jobAmount ceil($zip->numFiles $filesPerJob);
  1918.             for ($i 0$i $jobAmount$i++) {
  1919.                 $jobs[] = [[
  1920.                     'url' => $this->generateUrl('pimcore_admin_asset_importzipfiles'),
  1921.                     'method' => 'POST',
  1922.                     'params' => [
  1923.                         'parentId' => $asset->getId(),
  1924.                         'offset' => $i $filesPerJob,
  1925.                         'limit' => $filesPerJob,
  1926.                         'jobId' => $jobId,
  1927.                         'last' => (($i 1) >= $jobAmount) ? 'true' '',
  1928.                     ],
  1929.                 ]];
  1930.             }
  1931.             $zip->close();
  1932.             // here we have to use this method and not the JSON action helper ($this->_helper->json()) because this will add
  1933.             // Content-Type: application/json which fires a download window in most browsers, because this is a normal POST
  1934.             // request and not XHR where the content-type doesn't matter
  1935.             $responseJson $this->encodeJson([
  1936.                 'success' => true,
  1937.                 'jobs' => $jobs,
  1938.                 'jobId' => $jobId,
  1939.             ]);
  1940.             return new Response($responseJson);
  1941.         } else {
  1942.             return $this->adminJson([
  1943.                 'success' => false,
  1944.                 'message' => $this->trans('could_not_open_zip_file'),
  1945.             ]);
  1946.         }
  1947.     }
  1948.     /**
  1949.      * @Route("/import-zip-files", name="pimcore_admin_asset_importzipfiles", methods={"POST"})
  1950.      *
  1951.      * @param Request $request
  1952.      *
  1953.      * @return JsonResponse
  1954.      */
  1955.     public function importZipFilesAction(Request $request)
  1956.     {
  1957.         $jobId $request->get('jobId');
  1958.         $limit = (int)$request->get('limit');
  1959.         $offset = (int)$request->get('offset');
  1960.         $importAsset Asset::getById((int) $request->get('parentId'));
  1961.         $zipFile PIMCORE_SYSTEM_TEMP_DIRECTORY '/' $jobId '.zip';
  1962.         $tmpDir PIMCORE_SYSTEM_TEMP_DIRECTORY '/zip-import';
  1963.         if (!is_dir($tmpDir)) {
  1964.             File::mkdir($tmpDir0777true);
  1965.         }
  1966.         $zip = new \ZipArchive;
  1967.         if ($zip->open($zipFile) === true) {
  1968.             for ($i $offset$i < ($offset $limit); $i++) {
  1969.                 $path $zip->getNameIndex($i);
  1970.                 if (str_starts_with($path'__MACOSX/')) {
  1971.                     continue;
  1972.                 }
  1973.                 if ($path !== false) {
  1974.                     if ($zip->extractTo($tmpDir '/'$path)) {
  1975.                         $tmpFile $tmpDir '/' preg_replace('@^/@'''$path);
  1976.                         $filename Element\Service::getValidKey(basename($path), 'asset');
  1977.                         $relativePath '';
  1978.                         if (dirname($path) != '.') {
  1979.                             $relativePath dirname($path);
  1980.                         }
  1981.                         $parentPath $importAsset->getRealFullPath() . '/' preg_replace('@^/@'''$relativePath);
  1982.                         $parent Asset\Service::createFolderByPath($parentPath);
  1983.                         // check for duplicate filename
  1984.                         $filename $this->getSafeFilename($parent->getRealFullPath(), $filename);
  1985.                         if ($parent->isAllowed('create')) {
  1986.                             $asset Asset::create($parent->getId(), [
  1987.                                 'filename' => $filename,
  1988.                                 'sourcePath' => $tmpFile,
  1989.                                 'userOwner' => $this->getAdminUser()->getId(),
  1990.                                 'userModification' => $this->getAdminUser()->getId(),
  1991.                             ]);
  1992.                             @unlink($tmpFile);
  1993.                         } else {
  1994.                             Logger::debug('prevented creating asset because of missing permissions');
  1995.                         }
  1996.                     }
  1997.                 }
  1998.             }
  1999.             $zip->close();
  2000.         }
  2001.         if ($request->get('last')) {
  2002.             unlink($zipFile);
  2003.         }
  2004.         return $this->adminJson([
  2005.             'success' => true,
  2006.         ]);
  2007.     }
  2008.     /**
  2009.      * @Route("/import-server", name="pimcore_admin_asset_importserver", methods={"POST"})
  2010.      *
  2011.      * @param Request $request
  2012.      *
  2013.      * @return JsonResponse
  2014.      */
  2015.     public function importServerAction(Request $request)
  2016.     {
  2017.         $success true;
  2018.         $filesPerJob 5;
  2019.         $jobs = [];
  2020.         $importDirectory str_replace('/fileexplorer'PIMCORE_PROJECT_ROOT$request->get('serverPath'));
  2021.         if (preg_match('@^' preg_quote(PIMCORE_PROJECT_ROOT'@') . '@'$importDirectory) && is_dir($importDirectory)) {
  2022.             $this->checkForPharStreamWrapper($importDirectory);
  2023.             $files rscandir($importDirectory '/');
  2024.             $count count($files);
  2025.             $jobFiles = [];
  2026.             for ($i 0$i $count$i++) {
  2027.                 if (is_dir($files[$i])) {
  2028.                     continue;
  2029.                 }
  2030.                 $jobFiles[] = preg_replace('@^' preg_quote($importDirectory'@') . '@'''$files[$i]);
  2031.                 if (count($jobFiles) >= $filesPerJob || $i >= ($count 1)) {
  2032.                     $relativeImportDirectory preg_replace('@^' preg_quote(PIMCORE_PROJECT_ROOT'@') . '@'''$importDirectory);
  2033.                     $jobs[] = [[
  2034.                         'url' => $this->generateUrl('pimcore_admin_asset_importserverfiles'),
  2035.                         'method' => 'POST',
  2036.                         'params' => [
  2037.                             'parentId' => $request->get('parentId'),
  2038.                             'serverPath' => $relativeImportDirectory,
  2039.                             'files' => implode('::'$jobFiles),
  2040.                         ],
  2041.                     ]];
  2042.                     $jobFiles = [];
  2043.                 }
  2044.             }
  2045.         }
  2046.         return $this->adminJson([
  2047.             'success' => $success,
  2048.             'jobs' => $jobs,
  2049.         ]);
  2050.     }
  2051.     /**
  2052.      * @Route("/import-server-files", name="pimcore_admin_asset_importserverfiles", methods={"POST"})
  2053.      *
  2054.      * @param Request $request
  2055.      *
  2056.      * @return JsonResponse
  2057.      */
  2058.     public function importServerFilesAction(Request $request)
  2059.     {
  2060.         $assetFolder Asset::getById((int) $request->get('parentId'));
  2061.         if (!$assetFolder) {
  2062.             throw $this->createNotFoundException('Parent asset not found');
  2063.         }
  2064.         $serverPath PIMCORE_PROJECT_ROOT $request->get('serverPath');
  2065.         $files explode('::'$request->get('files'));
  2066.         foreach ($files as $file) {
  2067.             $absolutePath $serverPath $file;
  2068.             $this->checkForPharStreamWrapper($absolutePath);
  2069.             if (is_file($absolutePath)) {
  2070.                 $relFolderPath str_replace('\\''/'dirname($file));
  2071.                 $folder Asset\Service::createFolderByPath($assetFolder->getRealFullPath() . $relFolderPath);
  2072.                 $filename basename($file);
  2073.                 // check for duplicate filename
  2074.                 $filename Element\Service::getValidKey($filename'asset');
  2075.                 $filename $this->getSafeFilename($folder->getRealFullPath(), $filename);
  2076.                 if ($assetFolder->isAllowed('create')) {
  2077.                     $asset Asset::create($folder->getId(), [
  2078.                         'filename' => $filename,
  2079.                         'sourcePath' => $absolutePath,
  2080.                         'userOwner' => $this->getAdminUser()->getId(),
  2081.                         'userModification' => $this->getAdminUser()->getId(),
  2082.                     ]);
  2083.                 } else {
  2084.                     Logger::debug('prevented creating asset because of missing permissions ');
  2085.                 }
  2086.             }
  2087.         }
  2088.         return $this->adminJson([
  2089.             'success' => true,
  2090.         ]);
  2091.     }
  2092.     protected function checkForPharStreamWrapper($path)
  2093.     {
  2094.         if (stripos($path'phar://') !== false) {
  2095.             throw $this->createAccessDeniedException('Using PHAR files is not allowed!');
  2096.         }
  2097.     }
  2098.     /**
  2099.      * @Route("/import-url", name="pimcore_admin_asset_importurl", methods={"POST"})
  2100.      *
  2101.      * @param Request $request
  2102.      *
  2103.      * @return JsonResponse
  2104.      *
  2105.      * @throws \Exception
  2106.      */
  2107.     public function importUrlAction(Request $request)
  2108.     {
  2109.         $success true;
  2110.         $data Tool::getHttpData($request->get('url'));
  2111.         $filename basename($request->get('url'));
  2112.         $parentId $request->get('id');
  2113.         $parentAsset Asset::getById((int)$parentId);
  2114.         if (!$parentAsset) {
  2115.             throw $this->createNotFoundException('Parent asset not found');
  2116.         }
  2117.         $filename Element\Service::getValidKey($filename'asset');
  2118.         $filename $this->getSafeFilename($parentAsset->getRealFullPath(), $filename);
  2119.         if (empty($filename)) {
  2120.             throw new \Exception('The filename of the asset is empty');
  2121.         }
  2122.         // check for duplicate filename
  2123.         $filename $this->getSafeFilename($parentAsset->getRealFullPath(), $filename);
  2124.         if ($parentAsset->isAllowed('create')) {
  2125.             $asset Asset::create($parentId, [
  2126.                 'filename' => $filename,
  2127.                 'data' => $data,
  2128.                 'userOwner' => $this->getAdminUser()->getId(),
  2129.                 'userModification' => $this->getAdminUser()->getId(),
  2130.             ]);
  2131.             $success true;
  2132.         } else {
  2133.             Logger::debug('prevented creating asset because of missing permissions');
  2134.         }
  2135.         return $this->adminJson(['success' => $success]);
  2136.     }
  2137.     /**
  2138.      * @Route("/clear-thumbnail", name="pimcore_admin_asset_clearthumbnail", methods={"POST"})
  2139.      *
  2140.      * @param Request $request
  2141.      *
  2142.      * @return JsonResponse
  2143.      */
  2144.     public function clearThumbnailAction(Request $request)
  2145.     {
  2146.         $success false;
  2147.         if ($asset Asset::getById((int) $request->get('id'))) {
  2148.             if (method_exists($asset'clearThumbnails')) {
  2149.                 if (!$asset->isAllowed('publish')) {
  2150.                     throw $this->createAccessDeniedException('not allowed to publish');
  2151.                 }
  2152.                 $asset->clearThumbnails(true); // force clear
  2153.                 $asset->save();
  2154.                 $success true;
  2155.             }
  2156.         }
  2157.         return $this->adminJson(['success' => $success]);
  2158.     }
  2159.     /**
  2160.      * @Route("/grid-proxy", name="pimcore_admin_asset_gridproxy", methods={"GET", "POST", "PUT"})
  2161.      *
  2162.      * @param Request $request
  2163.      * @param EventDispatcherInterface $eventDispatcher
  2164.      * @param GridHelperService $gridHelperService
  2165.      * @param CsrfProtectionHandler $csrfProtection
  2166.      *
  2167.      * @return JsonResponse
  2168.      */
  2169.     public function gridProxyAction(Request $requestEventDispatcherInterface $eventDispatcherGridHelperService $gridHelperServiceCsrfProtectionHandler $csrfProtection)
  2170.     {
  2171.         $allParams array_merge($request->request->all(), $request->query->all());
  2172.         $filterPrepareEvent = new GenericEvent($this, [
  2173.             'requestParams' => $allParams,
  2174.         ]);
  2175.         $language $request->get('language') != 'default' $request->get('language') : null;
  2176.         $eventDispatcher->dispatch($filterPrepareEventAdminEvents::ASSET_LIST_BEFORE_FILTER_PREPARE);
  2177.         $allParams $filterPrepareEvent->getArgument('requestParams');
  2178.         $loader \Pimcore::getContainer()->get('pimcore.implementation_loader.asset.metadata.data');
  2179.         if (isset($allParams['data']) && $allParams['data']) {
  2180.             $csrfProtection->checkCsrfToken($request);
  2181.             if ($allParams['xaction'] == 'update') {
  2182.                 try {
  2183.                     $data $this->decodeJson($allParams['data']);
  2184.                     $updateEvent = new GenericEvent($this, [
  2185.                         'data' => $data,
  2186.                         'processed' => false,
  2187.                     ]);
  2188.                     $eventDispatcher->dispatch($updateEventAdminEvents::ASSET_LIST_BEFORE_UPDATE);
  2189.                     $processed $updateEvent->getArgument('processed');
  2190.                     if ($processed) {
  2191.                         // update already processed by event handler
  2192.                         return $this->adminJson(['success' => true]);
  2193.                     }
  2194.                     $data $updateEvent->getArgument('data');
  2195.                     // save
  2196.                     $asset Asset::getById($data['id']);
  2197.                     if (!$asset) {
  2198.                         throw $this->createNotFoundException('Asset not found');
  2199.                     }
  2200.                     if (!$asset->isAllowed('publish')) {
  2201.                         throw $this->createAccessDeniedException("Permission denied. You don't have the rights to save this asset.");
  2202.                     }
  2203.                     $metadata $asset->getMetadata(nullnullfalsetrue);
  2204.                     $dirty false;
  2205.                     unset($data['id']);
  2206.                     foreach ($data as $key => $value) {
  2207.                         $fieldDef explode('~'$key);
  2208.                         $key $fieldDef[0];
  2209.                         if (isset($fieldDef[1])) {
  2210.                             $language = ($fieldDef[1] == 'none' '' $fieldDef[1]);
  2211.                         }
  2212.                         foreach ($metadata as $idx => &$em) {
  2213.                             if ($em['name'] == $key && $em['language'] == $language) {
  2214.                                 try {
  2215.                                     $dataImpl $loader->build($em['type']);
  2216.                                     $value $dataImpl->getDataFromListfolderGrid($value$em);
  2217.                                 } catch (UnsupportedException $le) {
  2218.                                     Logger::error('could not resolve metadata implementation for ' $em['type']);
  2219.                                 }
  2220.                                 $em['data'] = $value;
  2221.                                 $dirty true;
  2222.                                 break;
  2223.                             }
  2224.                         }
  2225.                         if (!$dirty) {
  2226.                             $defaulMetadata = ['title''alt''copyright'];
  2227.                             if (in_array($key$defaulMetadata)) {
  2228.                                 $newEm = [
  2229.                                     'name' => $key,
  2230.                                     'language' => $language,
  2231.                                     'type' => 'input',
  2232.                                     'data' => $value,
  2233.                                 ];
  2234.                                 try {
  2235.                                     $dataImpl $loader->build($newEm['type']);
  2236.                                     $newEm['data'] = $dataImpl->getDataFromListfolderGrid($value$newEm);
  2237.                                 } catch (UnsupportedException $le) {
  2238.                                     Logger::error('could not resolve metadata implementation for ' $newEm['type']);
  2239.                                 }
  2240.                                 $metadata[] = $newEm;
  2241.                                 $dirty true;
  2242.                             } else {
  2243.                                 $predefined Model\Metadata\Predefined::getByName($key);
  2244.                                 if ($predefined && (empty($predefined->getTargetSubtype())
  2245.                                         || $predefined->getTargetSubtype() == $asset->getType())) {
  2246.                                     $newEm = [
  2247.                                         'name' => $key,
  2248.                                         'language' => $language,
  2249.                                         'type' => $predefined->getType(),
  2250.                                         'data' => $value,
  2251.                                     ];
  2252.                                     try {
  2253.                                         $dataImpl $loader->build($newEm['type']);
  2254.                                         $newEm['data'] = $dataImpl->getDataFromListfolderGrid($value$newEm);
  2255.                                     } catch (UnsupportedException $le) {
  2256.                                         Logger::error('could not resolve metadata implementation for ' $newEm['type']);
  2257.                                     }
  2258.                                     $metadata[] = $newEm;
  2259.                                     $dirty true;
  2260.                                 }
  2261.                             }
  2262.                         }
  2263.                     }
  2264.                     if ($dirty) {
  2265.                         // $metadata = Asset\Service::minimizeMetadata($metadata, "grid");
  2266.                         $asset->setMetadataRaw($metadata);
  2267.                         $asset->save();
  2268.                         return $this->adminJson(['success' => true]);
  2269.                     }
  2270.                     return $this->adminJson(['success' => false'message' => 'something went wrong.']);
  2271.                 } catch (\Exception $e) {
  2272.                     return $this->adminJson(['success' => false'message' => $e->getMessage()]);
  2273.                 }
  2274.             }
  2275.         } else {
  2276.             $list $gridHelperService->prepareAssetListingForGrid($allParams$this->getAdminUser());
  2277.             $beforeListLoadEvent = new GenericEvent($this, [
  2278.                 'list' => $list,
  2279.                 'context' => $allParams,
  2280.             ]);
  2281.             $eventDispatcher->dispatch($beforeListLoadEventAdminEvents::ASSET_LIST_BEFORE_LIST_LOAD);
  2282.             /** @var Asset\Listing $list */
  2283.             $list $beforeListLoadEvent->getArgument('list');
  2284.             $list->load();
  2285.             $assets = [];
  2286.             foreach ($list->getAssets() as $index => $asset) {
  2287.                 // Like for treeGetChildsByIdAction, so we respect isAllowed method which can be extended (object DI) for custom permissions, so relying only users_workspaces_asset is insufficient and could lead security breach
  2288.                 if ($asset->isAllowed('list')) {
  2289.                     $a Asset\Service::gridAssetData($asset$allParams['fields'], $allParams['language'] ?? '');
  2290.                     $assets[] = $a;
  2291.                 }
  2292.             }
  2293.             $result = ['data' => $assets'success' => true'total' => $list->getTotalCount()];
  2294.             $afterListLoadEvent = new GenericEvent($this, [
  2295.                 'list' => $result,
  2296.                 'context' => $allParams,
  2297.             ]);
  2298.             $eventDispatcher->dispatch($afterListLoadEventAdminEvents::ASSET_LIST_AFTER_LIST_LOAD);
  2299.             $result $afterListLoadEvent->getArgument('list');
  2300.             return $this->adminJson($result);
  2301.         }
  2302.         return $this->adminJson(['success' => false]);
  2303.     }
  2304.     /**
  2305.      * @Route("/get-text", name="pimcore_admin_asset_gettext", methods={"GET"})
  2306.      *
  2307.      * @param Request $request
  2308.      *
  2309.      * @return JsonResponse
  2310.      */
  2311.     public function getTextAction(Request $request)
  2312.     {
  2313.         $asset Asset::getById((int) $request->get('id'));
  2314.         if (!$asset) {
  2315.             throw $this->createNotFoundException('Asset not found');
  2316.         }
  2317.         if (!$asset->isAllowed('view')) {
  2318.             throw $this->createAccessDeniedException('not allowed to view');
  2319.         }
  2320.         $page $request->get('page');
  2321.         $text null;
  2322.         if ($asset instanceof Asset\Document) {
  2323.             $text $asset->getText($page);
  2324.         }
  2325.         return $this->adminJson(['success' => 'true''text' => $text]);
  2326.     }
  2327.     /**
  2328.      * @Route("/detect-image-features", name="pimcore_admin_asset_detectimagefeatures", methods={"GET"})
  2329.      *
  2330.      * @param Request $request
  2331.      *
  2332.      * @return JsonResponse
  2333.      */
  2334.     public function detectImageFeaturesAction(Request $request)
  2335.     {
  2336.         $asset Asset\Image::getById((int)$request->get('id'));
  2337.         if (!$asset instanceof Asset) {
  2338.             return $this->adminJson(['success' => false'message' => "asset doesn't exist"]);
  2339.         }
  2340.         if ($asset->isAllowed('publish')) {
  2341.             $asset->detectFaces();
  2342.             $asset->removeCustomSetting('disableImageFeatureAutoDetection');
  2343.             $asset->save();
  2344.             return $this->adminJson(['success' => true]);
  2345.         }
  2346.         throw $this->createAccessDeniedHttpException();
  2347.     }
  2348.     /**
  2349.      * @Route("/delete-image-features", name="pimcore_admin_asset_deleteimagefeatures", methods={"GET"})
  2350.      *
  2351.      * @param Request $request
  2352.      *
  2353.      * @return JsonResponse
  2354.      */
  2355.     public function deleteImageFeaturesAction(Request $request)
  2356.     {
  2357.         $asset Asset::getById((int)$request->get('id'));
  2358.         if (!$asset instanceof Asset) {
  2359.             return $this->adminJson(['success' => false'message' => "asset doesn't exist"]);
  2360.         }
  2361.         if ($asset->isAllowed('publish')) {
  2362.             $asset->removeCustomSetting('faceCoordinates');
  2363.             $asset->setCustomSetting('disableImageFeatureAutoDetection'true);
  2364.             $asset->save();
  2365.             return $this->adminJson(['success' => true]);
  2366.         }
  2367.         throw $this->createAccessDeniedHttpException();
  2368.     }
  2369.     /**
  2370.      * @param ControllerEvent $event
  2371.      */
  2372.     public function onKernelControllerEvent(ControllerEvent $event)
  2373.     {
  2374.         if (!$event->isMainRequest()) {
  2375.             return;
  2376.         }
  2377.         $this->checkActionPermission($event'assets', [
  2378.             'getImageThumbnailAction''getVideoThumbnailAction''getDocumentThumbnailAction',
  2379.         ]);
  2380.         $this->_assetService = new Asset\Service($this->getAdminUser());
  2381.     }
  2382. }