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

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