vendor/pimcore/pimcore/bundles/AdminBundle/Controller/Admin/SettingsController.php line 72

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;
  15. use Pimcore\Bundle\AdminBundle\Controller\AdminController;
  16. use Pimcore\Cache;
  17. use Pimcore\Cache\Core\CoreCacheHandler;
  18. use Pimcore\Cache\Symfony\CacheClearer;
  19. use Pimcore\Config;
  20. use Pimcore\Db;
  21. use Pimcore\Event\SystemEvents;
  22. use Pimcore\File;
  23. use Pimcore\Helper\StopMessengerWorkersTrait;
  24. use Pimcore\Localization\LocaleServiceInterface;
  25. use Pimcore\Model;
  26. use Pimcore\Model\Asset;
  27. use Pimcore\Model\Document;
  28. use Pimcore\Model\Element;
  29. use Pimcore\Model\Exception\ConfigWriteException;
  30. use Pimcore\Model\Glossary;
  31. use Pimcore\Model\Metadata;
  32. use Pimcore\Model\Property;
  33. use Pimcore\Model\Staticroute;
  34. use Pimcore\Model\Tool\SettingsStore;
  35. use Pimcore\Model\WebsiteSetting;
  36. use Pimcore\Tool;
  37. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  38. use Symfony\Component\EventDispatcher\GenericEvent;
  39. use Symfony\Component\Filesystem\Filesystem;
  40. use Symfony\Component\HttpFoundation\File\UploadedFile;
  41. use Symfony\Component\HttpFoundation\JsonResponse;
  42. use Symfony\Component\HttpFoundation\Request;
  43. use Symfony\Component\HttpFoundation\Response;
  44. use Symfony\Component\HttpFoundation\StreamedResponse;
  45. use Symfony\Component\HttpKernel\Event\TerminateEvent;
  46. use Symfony\Component\HttpKernel\KernelEvents;
  47. use Symfony\Component\HttpKernel\KernelInterface;
  48. use Symfony\Component\Routing\Annotation\Route;
  49. use Symfony\Component\Yaml\Yaml;
  50. /**
  51.  * @Route("/settings")
  52.  *
  53.  * @internal
  54.  */
  55. class SettingsController extends AdminController
  56. {
  57.     use StopMessengerWorkersTrait;
  58.     private const CUSTOM_LOGO_PATH 'custom-logo.image';
  59.     /**
  60.      * @Route("/display-custom-logo", name="pimcore_settings_display_custom_logo", methods={"GET"})
  61.      *
  62.      * @param Request $request
  63.      *
  64.      * @return StreamedResponse
  65.      */
  66.     public function displayCustomLogoAction(Request $request)
  67.     {
  68.         $mime 'image/svg+xml';
  69.         if ($request->get('white')) {
  70.             $logo PIMCORE_WEB_ROOT '/bundles/pimcoreadmin/img/logo-claim-white.svg';
  71.         } else {
  72.             $logo PIMCORE_WEB_ROOT '/bundles/pimcoreadmin/img/logo-claim-gray.svg';
  73.         }
  74.         $stream fopen($logo'rb');
  75.         $storage Tool\Storage::get('admin');
  76.         if ($storage->fileExists(self::CUSTOM_LOGO_PATH)) {
  77.             try {
  78.                 $mime $storage->mimeType(self::CUSTOM_LOGO_PATH);
  79.                 $stream $storage->readStream(self::CUSTOM_LOGO_PATH);
  80.             } catch (\Exception $e) {
  81.                 // do nothing
  82.             }
  83.         }
  84.         return new StreamedResponse(function () use ($stream) {
  85.             fpassthru($stream);
  86.         }, 200, [
  87.             'Content-Type' => $mime,
  88.             'Content-Security-Policy' => "script-src 'none'",
  89.         ]);
  90.     }
  91.     /**
  92.      * @Route("/upload-custom-logo", name="pimcore_admin_settings_uploadcustomlogo", methods={"POST"})
  93.      *
  94.      * @param Request $request
  95.      *
  96.      * @return JsonResponse
  97.      *
  98.      * @throws \Exception
  99.      */
  100.     public function uploadCustomLogoAction(Request $request)
  101.     {
  102.         $logoFile $request->files->get('Filedata');
  103.         if (!$logoFile instanceof UploadedFile
  104.             || !in_array($logoFile->guessExtension(), ['svg''png''jpg'])
  105.         ) {
  106.             throw new \Exception('Unsupported file format.');
  107.         }
  108.         $storage Tool\Storage::get('admin');
  109.         $storage->writeStream(self::CUSTOM_LOGO_PATHfopen($logoFile->getPathname(), 'rb'));
  110.         // set content-type to text/html, otherwise (when application/json is sent) chrome will complain in
  111.         // Ext.form.Action.Submit and mark the submission as failed
  112.         $response $this->adminJson(['success' => true]);
  113.         $response->headers->set('Content-Type''text/html');
  114.         return $response;
  115.     }
  116.     /**
  117.      * @Route("/delete-custom-logo", name="pimcore_admin_settings_deletecustomlogo", methods={"DELETE"})
  118.      *
  119.      * @param Request $request
  120.      *
  121.      * @return JsonResponse
  122.      */
  123.     public function deleteCustomLogoAction(Request $request)
  124.     {
  125.         if (Tool\Storage::get('admin')->fileExists(self::CUSTOM_LOGO_PATH)) {
  126.             Tool\Storage::get('admin')->delete(self::CUSTOM_LOGO_PATH);
  127.         }
  128.         return $this->adminJson(['success' => true]);
  129.     }
  130.     /**
  131.      * Used by the predefined metadata grid
  132.      *
  133.      * @Route("/predefined-metadata", name="pimcore_admin_settings_metadata", methods={"POST"})
  134.      *
  135.      * @param Request $request
  136.      *
  137.      * @return JsonResponse
  138.      */
  139.     public function metadataAction(Request $request)
  140.     {
  141.         $this->checkPermission('asset_metadata');
  142.         if ($request->get('data')) {
  143.             if ($request->get('xaction') == 'destroy') {
  144.                 $data $this->decodeJson($request->get('data'));
  145.                 $id $data['id'];
  146.                 $metadata Metadata\Predefined::getById($id);
  147.                 if (!$metadata->isWriteable()) {
  148.                     throw new ConfigWriteException();
  149.                 }
  150.                 $metadata->delete();
  151.                 return $this->adminJson(['success' => true'data' => []]);
  152.             } elseif ($request->get('xaction') == 'update') {
  153.                 $data $this->decodeJson($request->get('data'));
  154.                 // save type
  155.                 $metadata Metadata\Predefined::getById($data['id']);
  156.                 if (!$metadata->isWriteable()) {
  157.                     throw new ConfigWriteException();
  158.                 }
  159.                 $metadata->setValues($data);
  160.                 $existingItem Metadata\Predefined\Listing::getByKeyAndLanguage($metadata->getName(), $metadata->getLanguage(), $metadata->getTargetSubtype());
  161.                 if ($existingItem && $existingItem->getId() != $metadata->getId()) {
  162.                     return $this->adminJson(['message' => 'rule_violation''success' => false]);
  163.                 }
  164.                 $metadata->minimize();
  165.                 $metadata->save();
  166.                 $metadata->expand();
  167.                 $responseData $metadata->getObjectVars();
  168.                 $responseData['writeable'] = $metadata->isWriteable();
  169.                 return $this->adminJson(['data' => $responseData'success' => true]);
  170.             } elseif ($request->get('xaction') == 'create') {
  171.                 if (!(new Metadata\Predefined())->isWriteable()) {
  172.                     throw new ConfigWriteException();
  173.                 }
  174.                 $data $this->decodeJson($request->get('data'));
  175.                 unset($data['id']);
  176.                 // save type
  177.                 $metadata Metadata\Predefined::create();
  178.                 $metadata->setValues($data);
  179.                 $existingItem Metadata\Predefined\Listing::getByKeyAndLanguage($metadata->getName(), $metadata->getLanguage(), $metadata->getTargetSubtype());
  180.                 if ($existingItem) {
  181.                     return $this->adminJson(['message' => 'rule_violation''success' => false]);
  182.                 }
  183.                 $metadata->save();
  184.                 $responseData $metadata->getObjectVars();
  185.                 $responseData['writeable'] = $metadata->isWriteable();
  186.                 return $this->adminJson(['data' => $responseData'success' => true]);
  187.             }
  188.         } else {
  189.             // get list of types
  190.             $list = new Metadata\Predefined\Listing();
  191.             if ($filter $request->get('filter')) {
  192.                 $list->setFilter(function (Metadata\Predefined $predefined) use ($filter) {
  193.                     foreach ($predefined->getObjectVars() as $value) {
  194.                         if (stripos($value$filter) !== false) {
  195.                             return true;
  196.                         }
  197.                     }
  198.                     return false;
  199.                 });
  200.             }
  201.             $properties = [];
  202.             foreach ($list->getDefinitions() as $metadata) {
  203.                 $metadata->expand();
  204.                 $data $metadata->getObjectVars();
  205.                 $data['writeable'] = $metadata->isWriteable();
  206.                 $properties[] = $data;
  207.             }
  208.             return $this->adminJson(['data' => $properties'success' => true'total' => $list->getTotalCount()]);
  209.         }
  210.         return $this->adminJson(['success' => false]);
  211.     }
  212.     /**
  213.      * @Route("/get-predefined-metadata", name="pimcore_admin_settings_getpredefinedmetadata", methods={"GET"})
  214.      *
  215.      * @param Request $request
  216.      *
  217.      * @return JsonResponse
  218.      */
  219.     public function getPredefinedMetadataAction(Request $request)
  220.     {
  221.         $type $request->get('type');
  222.         $subType $request->get('subType');
  223.         $group $request->get('group');
  224.         $list Metadata\Predefined\Listing::getByTargetType($type, [$subType]);
  225.         $result = [];
  226.         foreach ($list as $item) {
  227.             $itemGroup $item->getGroup() ?? '';
  228.             if ($group === 'default' || $group === $itemGroup) {
  229.                 $item->expand();
  230.                 $data $item->getObjectVars();
  231.                 $data['writeable'] = $item->isWriteable();
  232.                 $result[] = $data;
  233.             }
  234.         }
  235.         return $this->adminJson(['data' => $result'success' => true]);
  236.     }
  237.     /**
  238.      * @Route("/properties", name="pimcore_admin_settings_properties", methods={"POST"})
  239.      *
  240.      * @param Request $request
  241.      *
  242.      * @return JsonResponse
  243.      */
  244.     public function propertiesAction(Request $request)
  245.     {
  246.         if ($request->get('data')) {
  247.             $this->checkPermission('predefined_properties');
  248.             if ($request->get('xaction') == 'destroy') {
  249.                 $data $this->decodeJson($request->get('data'));
  250.                 $id $data['id'];
  251.                 $property Property\Predefined::getById($id);
  252.                 if (!$property->isWriteable()) {
  253.                     throw new ConfigWriteException();
  254.                 }
  255.                 $property->delete();
  256.                 return $this->adminJson(['success' => true'data' => []]);
  257.             } elseif ($request->get('xaction') == 'update') {
  258.                 $data $this->decodeJson($request->get('data'));
  259.                 // save type
  260.                 $property Property\Predefined::getById($data['id']);
  261.                 if (!$property->isWriteable()) {
  262.                     throw new ConfigWriteException();
  263.                 }
  264.                 if (is_array($data['ctype'])) {
  265.                     $data['ctype'] = implode(','$data['ctype']);
  266.                 }
  267.                 $property->setValues($data);
  268.                 $property->save();
  269.                 $responseData $property->getObjectVars();
  270.                 $responseData['writeable'] = $property->isWriteable();
  271.                 return $this->adminJson(['data' => $responseData'success' => true]);
  272.             } elseif ($request->get('xaction') == 'create') {
  273.                 if (!(new Property\Predefined())->isWriteable()) {
  274.                     throw new ConfigWriteException();
  275.                 }
  276.                 $data $this->decodeJson($request->get('data'));
  277.                 unset($data['id']);
  278.                 // save type
  279.                 $property Property\Predefined::create();
  280.                 $property->setValues($data);
  281.                 $property->save();
  282.                 $responseData $property->getObjectVars();
  283.                 $responseData['writeable'] = $property->isWriteable();
  284.                 return $this->adminJson(['data' => $responseData'success' => true]);
  285.             }
  286.         } else {
  287.             // get list of types
  288.             $list = new Property\Predefined\Listing();
  289.             if ($filter $request->get('filter')) {
  290.                 $list->setFilter(function (Property\Predefined $predefined) use ($filter) {
  291.                     foreach ($predefined->getObjectVars() as $value) {
  292.                         if ($value) {
  293.                             $cellValues is_array($value) ? $value : [$value];
  294.                             foreach ($cellValues as $cellValue) {
  295.                                 if (stripos($cellValue$filter) !== false) {
  296.                                     return true;
  297.                                 }
  298.                             }
  299.                         }
  300.                     }
  301.                     return false;
  302.                 });
  303.             }
  304.             $properties = [];
  305.             foreach ($list->getProperties() as $property) {
  306.                 $data $property->getObjectVars();
  307.                 $data['writeable'] = $property->isWriteable();
  308.                 $properties[] = $data;
  309.             }
  310.             return $this->adminJson(['data' => $properties'success' => true'total' => $list->getTotalCount()]);
  311.         }
  312.         return $this->adminJson(['success' => false]);
  313.     }
  314.     /**
  315.      * @Route("/get-system", name="pimcore_admin_settings_getsystem", methods={"GET"})
  316.      *
  317.      * @param Request $request
  318.      * @param Config $config
  319.      *
  320.      * @return JsonResponse
  321.      */
  322.     public function getSystemAction(Request $requestConfig $config)
  323.     {
  324.         $this->checkPermission('system_settings');
  325.         $valueArray = [
  326.             'general' => $config['general'],
  327.             'documents' => $config['documents'],
  328.             'assets' => $config['assets'],
  329.             'objects' => $config['objects'],
  330.             'branding' => $config['branding'],
  331.             'email' => $config['email'],
  332.         ];
  333.         $locales Tool::getSupportedLocales();
  334.         $languageOptions = [];
  335.         $validLanguages = [];
  336.         foreach ($locales as $short => $translation) {
  337.             if (!empty($short)) {
  338.                 $languageOptions[] = [
  339.                     'language' => $short,
  340.                     'display' => $translation " ($short)",
  341.                 ];
  342.                 $validLanguages[] = $short;
  343.             }
  344.         }
  345.         $valueArray['general']['valid_language'] = explode(','$valueArray['general']['valid_languages']);
  346.         //for "wrong" legacy values
  347.         if (is_array($valueArray['general']['valid_language'])) {
  348.             foreach ($valueArray['general']['valid_language'] as $existingValue) {
  349.                 if (!in_array($existingValue$validLanguages)) {
  350.                     $languageOptions[] = [
  351.                         'language' => $existingValue,
  352.                         'display' => $existingValue,
  353.                     ];
  354.                 }
  355.             }
  356.         }
  357.         $response = [
  358.             'values' => $valueArray,
  359.             'config' => [
  360.                 'languages' => $languageOptions,
  361.             ],
  362.         ];
  363.         return $this->adminJson($response);
  364.     }
  365.     /**
  366.      * @Route("/set-system", name="pimcore_admin_settings_setsystem", methods={"PUT"})
  367.      *
  368.      * @param Request $request
  369.      * @param LocaleServiceInterface $localeService
  370.      *
  371.      * @return JsonResponse
  372.      */
  373.     public function setSystemAction(
  374.         LocaleServiceInterface $localeService,
  375.         Request $request,
  376.         KernelInterface $kernel,
  377.         EventDispatcherInterface $eventDispatcher,
  378.         CoreCacheHandler $cache,
  379.         Filesystem $filesystem,
  380.         CacheClearer $symfonyCacheClearer
  381.     ) {
  382.         $this->checkPermission('system_settings');
  383.         $values $this->decodeJson($request->get('data'));
  384.         $existingValues = [];
  385.         try {
  386.             $file Config::locateConfigFile('system.yml');
  387.             $existingValues Config::getConfigInstance($filetrue);
  388.         } catch (\Exception $e) {
  389.             // nothing to do
  390.         }
  391.         // localized error pages
  392.         $localizedErrorPages = [];
  393.         // fallback languages
  394.         $fallbackLanguages = [];
  395.         $existingValues['pimcore']['general']['fallback_languages'] = [];
  396.         $languages explode(','$values['general.validLanguages']);
  397.         $filteredLanguages = [];
  398.         foreach ($languages as $language) {
  399.             if (isset($values['general.fallbackLanguages.' $language])) {
  400.                 $fallbackLanguages[$language] = str_replace(' '''$values['general.fallbackLanguages.' $language]);
  401.             }
  402.             // localized error pages
  403.             if (isset($values['documents.error_pages.localized.' $language])) {
  404.                 $localizedErrorPages[$language] = $values['documents.error_pages.localized.' $language];
  405.             }
  406.             if ($localeService->isLocale($language)) {
  407.                 $filteredLanguages[] = $language;
  408.             }
  409.         }
  410.         // check if there's a fallback language endless loop
  411.         foreach ($fallbackLanguages as $sourceLang => $targetLang) {
  412.             $this->checkFallbackLanguageLoop($sourceLang$fallbackLanguages);
  413.         }
  414.         $settings['pimcore'] = [
  415.             'general' => [
  416.                 'domain' => $values['general.domain'],
  417.                 'redirect_to_maindomain' => $values['general.redirect_to_maindomain'],
  418.                 'language' => $values['general.language'],
  419.                 'valid_languages' => implode(','$filteredLanguages),
  420.                 'fallback_languages' => $fallbackLanguages,
  421.                 'default_language' => $values['general.defaultLanguage'],
  422.                 'debug_admin_translations' => $values['general.debug_admin_translations'],
  423.             ],
  424.             'documents' => [
  425.                 'versions' => [
  426.                     'days' => $values['documents.versions.days'] ?? null,
  427.                     'steps' => $values['documents.versions.steps'] ?? null,
  428.                 ],
  429.                 'error_pages' => [
  430.                     'default' => $values['documents.error_pages.default'],
  431.                     'localized' => $localizedErrorPages,
  432.                 ],
  433.             ],
  434.             'objects' => [
  435.                 'versions' => [
  436.                     'days' => $values['objects.versions.days'] ?? null,
  437.                     'steps' => $values['objects.versions.steps'] ?? null,
  438.                 ],
  439.             ],
  440.             'assets' => [
  441.                 'versions' => [
  442.                     'days' => $values['assets.versions.days'] ?? null,
  443.                     'steps' => $values['assets.versions.steps'] ?? null,
  444.                 ],
  445.                 'hide_edit_image' => $values['assets.hide_edit_image'],
  446.                 'disable_tree_preview' => $values['assets.disable_tree_preview'],
  447.             ],
  448.         ];
  449.         //branding
  450.         $settings['pimcore_admin'] = [
  451.             'branding' =>
  452.                 [
  453.                     'login_screen_invert_colors' => $values['branding.login_screen_invert_colors'],
  454.                     'color_login_screen' => $values['branding.color_login_screen'],
  455.                     'color_admin_interface' => $values['branding.color_admin_interface'],
  456.                     'color_admin_interface_background' => $values['branding.color_admin_interface_background'],
  457.                     'login_screen_custom_image' => $values['branding.login_screen_custom_image'],
  458.                 ],
  459.         ];
  460.         if (array_key_exists('email.debug.emailAddresses'$values) && $values['email.debug.emailAddresses']) {
  461.             $settings['pimcore']['email']['debug']['email_addresses'] = $values['email.debug.emailAddresses'];
  462.         }
  463.         $settingsYml Yaml::dump($settings5);
  464.         $configFile Config::locateConfigFile('system.yml');
  465.         File::put($configFile$settingsYml);
  466.         // clear all caches
  467.         $this->clearSymfonyCache($request$kernel$eventDispatcher$symfonyCacheClearer);
  468.         $this->stopMessengerWorkers();
  469.         $eventDispatcher->addListener(KernelEvents::TERMINATE, function (TerminateEvent $event) use (
  470.             $cache$eventDispatcher$filesystem
  471.         ) {
  472.             // we need to clear the cache with a delay, because the cache is used by messenger:stop-workers
  473.             // to send the stop signal to all worker processes
  474.             sleep(2);
  475.             $this->clearPimcoreCache($cache$eventDispatcher$filesystem);
  476.         });
  477.         return $this->adminJson(['success' => true]);
  478.     }
  479.     /**
  480.      * @param string $source
  481.      * @param array $definitions
  482.      * @param array $fallbacks
  483.      *
  484.      * @throws \Exception
  485.      */
  486.     protected function checkFallbackLanguageLoop($source$definitions$fallbacks = [])
  487.     {
  488.         if (isset($definitions[$source])) {
  489.             $targets explode(','$definitions[$source]);
  490.             foreach ($targets as $l) {
  491.                 $target trim($l);
  492.                 if ($target) {
  493.                     if (in_array($target$fallbacks)) {
  494.                         throw new \Exception("Language `$source` | `$target` causes an infinte loop.");
  495.                     }
  496.                     $fallbacks[] = $target;
  497.                     $this->checkFallbackLanguageLoop($target$definitions$fallbacks);
  498.                 }
  499.             }
  500.         } else {
  501.             throw new \Exception("Language `$source` doesn't exist");
  502.         }
  503.     }
  504.     /**
  505.      * @Route("/get-web2print", name="pimcore_admin_settings_getweb2print", methods={"GET"})
  506.      *
  507.      * @param Request $request
  508.      *
  509.      * @return JsonResponse
  510.      */
  511.     public function getWeb2printAction(Request $request)
  512.     {
  513.         $this->checkPermission('web2print_settings');
  514.         $values Config::getWeb2PrintConfig();
  515.         $valueArray $values->toArray();
  516.         $optionsString = [];
  517.         if ($valueArray['wkhtml2pdfOptions'] ?? false) {
  518.             foreach ($valueArray['wkhtml2pdfOptions'] as $key => $value) {
  519.                 $tmpStr '--'.$key;
  520.                 if ($value !== null && $value !== '') {
  521.                     $tmpStr .= ' '.$value;
  522.                 }
  523.                 $optionsString[] = $tmpStr;
  524.             }
  525.         }
  526.         $valueArray['wkhtml2pdfOptions'] = implode("\n"$optionsString);
  527.         $response = [
  528.             'values' => $valueArray,
  529.         ];
  530.         return $this->adminJson($response);
  531.     }
  532.     /**
  533.      * @Route("/set-web2print", name="pimcore_admin_settings_setweb2print", methods={"PUT"})
  534.      *
  535.      * @param Request $request
  536.      *
  537.      * @return JsonResponse
  538.      */
  539.     public function setWeb2printAction(Request $request)
  540.     {
  541.         $this->checkPermission('web2print_settings');
  542.         $values $this->decodeJson($request->get('data'));
  543.         unset($values['documentation']);
  544.         unset($values['additions']);
  545.         unset($values['json_converter']);
  546.         if ($values['wkhtml2pdfOptions']) {
  547.             $optionArray = [];
  548.             $lines explode("\n"$values['wkhtml2pdfOptions']);
  549.             foreach ($lines as $line) {
  550.                 $parts explode(' 'substr($line2));
  551.                 $key trim($parts[0]);
  552.                 if ($key) {
  553.                     $value trim($parts[1] ?? '');
  554.                     $optionArray[$key] = $value;
  555.                 }
  556.             }
  557.             $values['wkhtml2pdfOptions'] = $optionArray;
  558.         }
  559.         \Pimcore\Web2Print\Config::save($values);
  560.         return $this->adminJson(['success' => true]);
  561.     }
  562.     /**
  563.      * @Route("/clear-cache", name="pimcore_admin_settings_clearcache", methods={"DELETE"})
  564.      *
  565.      * @param Request $request
  566.      * @param KernelInterface $kernel
  567.      * @param EventDispatcherInterface $eventDispatcher
  568.      * @param CoreCacheHandler $cache
  569.      * @param Filesystem $filesystem
  570.      * @param CacheClearer $symfonyCacheClearer
  571.      *
  572.      * @return JsonResponse
  573.      */
  574.     public function clearCacheAction(
  575.         Request $request,
  576.         KernelInterface $kernel,
  577.         EventDispatcherInterface $eventDispatcher,
  578.         CoreCacheHandler $cache,
  579.         Filesystem $filesystem,
  580.         CacheClearer $symfonyCacheClearer
  581.     ) {
  582.         $this->checkPermissionsHasOneOf(['clear_cache''system_settings']);
  583.         $result = [
  584.             'success' => true,
  585.         ];
  586.         $clearPimcoreCache = !(bool)$request->get('only_symfony_cache');
  587.         $clearSymfonyCache = !(bool)$request->get('only_pimcore_cache');
  588.         if ($clearPimcoreCache) {
  589.             $this->clearPimcoreCache($cache$eventDispatcher$filesystem);
  590.         }
  591.         if ($clearSymfonyCache) {
  592.             $this->clearSymfonyCache($request$kernel$eventDispatcher$symfonyCacheClearer);
  593.         }
  594.         $response = new JsonResponse($result);
  595.         if ($clearSymfonyCache) {
  596.             // we send the response directly here and exit to make sure no code depending on the stale container
  597.             // is running after this
  598.             $response->sendHeaders();
  599.             $response->sendContent();
  600.             exit;
  601.         }
  602.         return $response;
  603.     }
  604.     private function clearPimcoreCache(
  605.         CoreCacheHandler $cache,
  606.         EventDispatcherInterface $eventDispatcher,
  607.         Filesystem $filesystem,
  608.     ): void {
  609.         // empty document cache
  610.         $cache->clearAll();
  611.         if ($filesystem->exists(PIMCORE_CACHE_DIRECTORY)) {
  612.             $filesystem->remove(PIMCORE_CACHE_DIRECTORY);
  613.         }
  614.         // PIMCORE-1854 - recreate .dummy file => should remain
  615.         File::put(PIMCORE_CACHE_DIRECTORY '/.gitkeep''');
  616.         $eventDispatcher->dispatch(new GenericEvent(), SystemEvents::CACHE_CLEAR);
  617.     }
  618.     private function clearSymfonyCache(
  619.         Request $request,
  620.         KernelInterface $kernel,
  621.         EventDispatcherInterface $eventDispatcher,
  622.         CacheClearer $symfonyCacheClearer,
  623.     ): void {
  624.         // pass one or move env parameters to clear multiple envs
  625.         // if no env is passed it will use the current one
  626.         $environments $request->get('env'$kernel->getEnvironment());
  627.         if (!is_array($environments)) {
  628.             $environments trim((string)$environments);
  629.             if (empty($environments)) {
  630.                 $environments = [];
  631.             } else {
  632.                 $environments = [$environments];
  633.             }
  634.         }
  635.         if (empty($environments)) {
  636.             $environments = [$kernel->getEnvironment()];
  637.         }
  638.         $result['environments'] = $environments;
  639.         if (in_array($kernel->getEnvironment(), $environments)) {
  640.             // remove terminate and exception event listeners for the current env as they break with a
  641.             // cleared container - see #2434
  642.             foreach ($eventDispatcher->getListeners(KernelEvents::TERMINATE) as $listener) {
  643.                 $eventDispatcher->removeListener(KernelEvents::TERMINATE$listener);
  644.             }
  645.             foreach ($eventDispatcher->getListeners(KernelEvents::EXCEPTION) as $listener) {
  646.                 $eventDispatcher->removeListener(KernelEvents::EXCEPTION$listener);
  647.             }
  648.         }
  649.         foreach ($environments as $environment) {
  650.             try {
  651.                 $symfonyCacheClearer->clear($environment);
  652.             } catch (\Throwable $e) {
  653.                 $errors $result['errors'] ?? [];
  654.                 $errors[] = $e->getMessage();
  655.                 $result array_merge($result, [
  656.                     'success' => false,
  657.                     'errors' => $errors,
  658.                 ]);
  659.             }
  660.         }
  661.     }
  662.     /**
  663.      * @Route("/clear-output-cache", name="pimcore_admin_settings_clearoutputcache", methods={"DELETE"})
  664.      *
  665.      * @param EventDispatcherInterface $eventDispatcher
  666.      *
  667.      * @return JsonResponse
  668.      */
  669.     public function clearOutputCacheAction(EventDispatcherInterface $eventDispatcher)
  670.     {
  671.         $this->checkPermission('clear_fullpage_cache');
  672.         // remove "output" out of the ignored tags, if a cache lifetime is specified
  673.         Cache::removeIgnoredTagOnClear('output');
  674.         // empty document cache
  675.         Cache::clearTags(['output''output_lifetime']);
  676.         $eventDispatcher->dispatch(new GenericEvent(), SystemEvents::CACHE_CLEAR_FULLPAGE_CACHE);
  677.         return $this->adminJson(['success' => true]);
  678.     }
  679.     /**
  680.      * @Route("/clear-temporary-files", name="pimcore_admin_settings_cleartemporaryfiles", methods={"DELETE"})
  681.      *
  682.      * @param EventDispatcherInterface $eventDispatcher
  683.      *
  684.      * @return JsonResponse
  685.      */
  686.     public function clearTemporaryFilesAction(EventDispatcherInterface $eventDispatcher)
  687.     {
  688.         $this->checkPermission('clear_temp_files');
  689.         // public files
  690.         Tool\Storage::get('thumbnail')->deleteDirectory('/');
  691.         Db::get()->query('TRUNCATE TABLE assets_image_thumbnail_cache');
  692.         Tool\Storage::get('asset_cache')->deleteDirectory('/');
  693.         // system files
  694.         recursiveDelete(PIMCORE_SYSTEM_TEMP_DIRECTORYfalse);
  695.         $eventDispatcher->dispatch(new GenericEvent(), SystemEvents::CACHE_CLEAR_TEMPORARY_FILES);
  696.         return $this->adminJson(['success' => true]);
  697.     }
  698.     /**
  699.      * @Route("/staticroutes", name="pimcore_admin_settings_staticroutes", methods={"POST"})
  700.      *
  701.      * @param Request $request
  702.      *
  703.      * @return JsonResponse
  704.      */
  705.     public function staticroutesAction(Request $request)
  706.     {
  707.         if ($request->get('data')) {
  708.             $this->checkPermission('routes');
  709.             $data $this->decodeJson($request->get('data'));
  710.             if (is_array($data)) {
  711.                 foreach ($data as &$value) {
  712.                     if (is_string($value)) {
  713.                         $value trim($value);
  714.                     }
  715.                 }
  716.             }
  717.             if ($request->get('xaction') == 'destroy') {
  718.                 $data $this->decodeJson($request->get('data'));
  719.                 $id $data['id'];
  720.                 $route Staticroute::getById($id);
  721.                 if (!$route->isWriteable()) {
  722.                     throw new ConfigWriteException();
  723.                 }
  724.                 $route->delete();
  725.                 return $this->adminJson(['success' => true'data' => []]);
  726.             } elseif ($request->get('xaction') == 'update') {
  727.                 // save routes
  728.                 $route Staticroute::getById($data['id']);
  729.                 if (!$route->isWriteable()) {
  730.                     throw new ConfigWriteException();
  731.                 }
  732.                 $route->setValues($data);
  733.                 $route->save();
  734.                 return $this->adminJson(['data' => $route->getObjectVars(), 'success' => true]);
  735.             } elseif ($request->get('xaction') == 'create') {
  736.                 if (!(new Staticroute())->isWriteable()) {
  737.                     throw new ConfigWriteException();
  738.                 }
  739.                 unset($data['id']);
  740.                 // save route
  741.                 $route = new Staticroute();
  742.                 $route->setValues($data);
  743.                 $route->save();
  744.                 $responseData $route->getObjectVars();
  745.                 $responseData['writeable'] = $route->isWriteable();
  746.                 return $this->adminJson(['data' => $responseData'success' => true]);
  747.             }
  748.         } else {
  749.             // get list of routes
  750.             $list = new Staticroute\Listing();
  751.             if ($filter $request->get('filter')) {
  752.                 $list->setFilter(function (Staticroute $staticRoute) use ($filter) {
  753.                     foreach ($staticRoute->getObjectVars() as $value) {
  754.                         if (!is_scalar($value)) {
  755.                             continue;
  756.                         }
  757.                         if (stripos((string)$value$filter) !== false) {
  758.                             return true;
  759.                         }
  760.                     }
  761.                     return false;
  762.                 });
  763.             }
  764.             $routes = [];
  765.             foreach ($list->getRoutes() as $routeFromList) {
  766.                 $route $routeFromList->getObjectVars();
  767.                 $route['writeable'] = $routeFromList->isWriteable();
  768.                 if (is_array($routeFromList->getSiteId())) {
  769.                     $route['siteId'] = implode(','$routeFromList->getSiteId());
  770.                 }
  771.                 $routes[] = $route;
  772.             }
  773.             return $this->adminJson(['data' => $routes'success' => true'total' => $list->getTotalCount()]);
  774.         }
  775.         return $this->adminJson(['success' => false]);
  776.     }
  777.     /**
  778.      * @Route("/get-available-admin-languages", name="pimcore_admin_settings_getavailableadminlanguages", methods={"GET"})
  779.      *
  780.      * @param Request $request
  781.      *
  782.      * @return JsonResponse
  783.      */
  784.     public function getAvailableAdminLanguagesAction(Request $request)
  785.     {
  786.         $langs = [];
  787.         $availableLanguages Tool\Admin::getLanguages();
  788.         $locales Tool::getSupportedLocales();
  789.         foreach ($availableLanguages as $lang) {
  790.             if (array_key_exists($lang$locales)) {
  791.                 $langs[] = [
  792.                     'language' => $lang,
  793.                     'display' => $locales[$lang],
  794.                 ];
  795.             }
  796.         }
  797.         usort($langs, function ($a$b) {
  798.             return strcmp($a['display'], $b['display']);
  799.         });
  800.         return $this->adminJson($langs);
  801.     }
  802.     /**
  803.      * @Route("/glossary", name="pimcore_admin_settings_glossary", methods={"POST"})
  804.      *
  805.      * @param Request $request
  806.      *
  807.      * @return JsonResponse
  808.      */
  809.     public function glossaryAction(Request $request)
  810.     {
  811.         if ($request->get('data')) {
  812.             $this->checkPermission('glossary');
  813.             Cache::clearTag('glossary');
  814.             if ($request->get('xaction') == 'destroy') {
  815.                 $data $this->decodeJson($request->get('data'));
  816.                 $id $data['id'];
  817.                 $glossary Glossary::getById($id);
  818.                 $glossary->delete();
  819.                 return $this->adminJson(['success' => true'data' => []]);
  820.             } elseif ($request->get('xaction') == 'update') {
  821.                 $data $this->decodeJson($request->get('data'));
  822.                 // save glossary
  823.                 $glossary Glossary::getById($data['id']);
  824.                 if (!empty($data['link'])) {
  825.                     if ($doc Document::getByPath($data['link'])) {
  826.                         $data['link'] = $doc->getId();
  827.                     }
  828.                 }
  829.                 $glossary->setValues($data);
  830.                 $glossary->save();
  831.                 if ($link $glossary->getLink()) {
  832.                     if ((int)$link 0) {
  833.                         if ($doc Document::getById((int)$link)) {
  834.                             $glossary->setLink($doc->getRealFullPath());
  835.                         }
  836.                     }
  837.                 }
  838.                 return $this->adminJson(['data' => $glossary'success' => true]);
  839.             } elseif ($request->get('xaction') == 'create') {
  840.                 $data $this->decodeJson($request->get('data'));
  841.                 unset($data['id']);
  842.                 // save glossary
  843.                 $glossary = new Glossary();
  844.                 if (!empty($data['link'])) {
  845.                     if ($doc Document::getByPath($data['link'])) {
  846.                         $data['link'] = $doc->getId();
  847.                     }
  848.                 }
  849.                 $glossary->setValues($data);
  850.                 $glossary->save();
  851.                 if ($link $glossary->getLink()) {
  852.                     if ((int)$link 0) {
  853.                         if ($doc Document::getById((int)$link)) {
  854.                             $glossary->setLink($doc->getRealFullPath());
  855.                         }
  856.                     }
  857.                 }
  858.                 return $this->adminJson(['data' => $glossary->getObjectVars(), 'success' => true]);
  859.             }
  860.         } else {
  861.             // get list of glossaries
  862.             $list = new Glossary\Listing();
  863.             $list->setLimit($request->get('limit'));
  864.             $list->setOffset($request->get('start'));
  865.             $sortingSettings \Pimcore\Bundle\AdminBundle\Helper\QueryParams::extractSortingSettings(array_merge($request->request->all(), $request->query->all()));
  866.             if ($sortingSettings['orderKey']) {
  867.                 $list->setOrderKey($sortingSettings['orderKey']);
  868.                 $list->setOrder($sortingSettings['order']);
  869.             }
  870.             if ($request->get('filter')) {
  871.                 $list->setCondition('`text` LIKE ' $list->quote('%'.$request->get('filter').'%'));
  872.             }
  873.             $list->load();
  874.             $glossaries = [];
  875.             foreach ($list->getGlossary() as $glossary) {
  876.                 if ($link $glossary->getLink()) {
  877.                     if ((int)$link 0) {
  878.                         if ($doc Document::getById((int)$link)) {
  879.                             $glossary->setLink($doc->getRealFullPath());
  880.                         }
  881.                     }
  882.                 }
  883.                 $glossaries[] = $glossary->getObjectVars();
  884.             }
  885.             return $this->adminJson(['data' => $glossaries'success' => true'total' => $list->getTotalCount()]);
  886.         }
  887.         return $this->adminJson(['success' => false]);
  888.     }
  889.     /**
  890.      * @Route("/get-available-sites", name="pimcore_admin_settings_getavailablesites", methods={"GET"})
  891.      *
  892.      * @param Request $request
  893.      *
  894.      * @return JsonResponse
  895.      */
  896.     public function getAvailableSitesAction(Request $request)
  897.     {
  898.         $excludeMainSite $request->get('excludeMainSite');
  899.         $sitesList = new Model\Site\Listing();
  900.         $sitesObjects $sitesList->load();
  901.         $sites = [];
  902.         if (!$excludeMainSite) {
  903.             $sites[] = [
  904.                 'id' => 'default',
  905.                 'rootId' => 1,
  906.                 'domains' => '',
  907.                 'rootPath' => '/',
  908.                 'domain' => $this->trans('main_site'),
  909.             ];
  910.         }
  911.         foreach ($sitesObjects as $site) {
  912.             if ($site->getRootDocument()) {
  913.                 if ($site->getMainDomain()) {
  914.                     $sites[] = [
  915.                         'id' => $site->getId(),
  916.                         'rootId' => $site->getRootId(),
  917.                         'domains' => implode(','$site->getDomains()),
  918.                         'rootPath' => $site->getRootPath(),
  919.                         'domain' => $site->getMainDomain(),
  920.                     ];
  921.                 }
  922.             } else {
  923.                 // site is useless, parent doesn't exist anymore
  924.                 $site->delete();
  925.             }
  926.         }
  927.         return $this->adminJson($sites);
  928.     }
  929.     /**
  930.      * @Route("/get-available-countries", name="pimcore_admin_settings_getavailablecountries", methods={"GET"})
  931.      *
  932.      * @param LocaleServiceInterface $localeService
  933.      *
  934.      * @return JsonResponse
  935.      */
  936.     public function getAvailableCountriesAction(LocaleServiceInterface $localeService)
  937.     {
  938.         $countries $localeService->getDisplayRegions();
  939.         asort($countries);
  940.         $options = [];
  941.         foreach ($countries as $short => $translation) {
  942.             if (strlen($short) == 2) {
  943.                 $options[] = [
  944.                     'key' => $translation ' (' $short ')',
  945.                     'value' => $short,
  946.                 ];
  947.             }
  948.         }
  949.         $result = ['data' => $options'success' => true'total' => count($options)];
  950.         return $this->adminJson($result);
  951.     }
  952.     /**
  953.      * @Route("/thumbnail-adapter-check", name="pimcore_admin_settings_thumbnailadaptercheck", methods={"GET"})
  954.      *
  955.      * @param Request $request
  956.      *
  957.      * @return Response
  958.      */
  959.     public function thumbnailAdapterCheckAction(Request $request)
  960.     {
  961.         $content '';
  962.         $instance \Pimcore\Image::getInstance();
  963.         if ($instance instanceof \Pimcore\Image\Adapter\GD) {
  964.             $content '<span style="color: red; font-weight: bold;padding: 10px;margin:0 0 20px 0;border:1px solid red;display:block;">' .
  965.                 $this->trans('important_use_imagick_pecl_extensions_for_best_results_gd_is_just_a_fallback_with_less_quality') .
  966.                 '</span>';
  967.         }
  968.         return new Response($content);
  969.     }
  970.     /**
  971.      * @Route("/thumbnail-tree", name="pimcore_admin_settings_thumbnailtree", methods={"GET", "POST"})
  972.      *
  973.      * @return JsonResponse
  974.      */
  975.     public function thumbnailTreeAction()
  976.     {
  977.         $this->checkPermission('thumbnails');
  978.         $thumbnails = [];
  979.         $list = new Asset\Image\Thumbnail\Config\Listing();
  980.         $groups = [];
  981.         foreach ($list->getThumbnails() as $item) {
  982.             if ($item->getGroup()) {
  983.                 if (empty($groups[$item->getGroup()])) {
  984.                     $groups[$item->getGroup()] = [
  985.                         'id' => 'group_' $item->getName(),
  986.                         'text' => htmlspecialchars($item->getGroup()),
  987.                         'expandable' => true,
  988.                         'leaf' => false,
  989.                         'allowChildren' => true,
  990.                         'iconCls' => 'pimcore_icon_folder',
  991.                         'group' => $item->getGroup(),
  992.                         'children' => [],
  993.                     ];
  994.                 }
  995.                 $groups[$item->getGroup()]['children'][] =
  996.                     [
  997.                         'id' => $item->getName(),
  998.                         'text' => $item->getName(),
  999.                         'leaf' => true,
  1000.                         'iconCls' => 'pimcore_icon_thumbnails',
  1001.                         'cls' => 'pimcore_treenode_disabled',
  1002.                         'writeable' => $item->isWriteable(),
  1003.                     ];
  1004.             } else {
  1005.                 $thumbnails[] = [
  1006.                     'id' => $item->getName(),
  1007.                     'text' => $item->getName(),
  1008.                     'leaf' => true,
  1009.                     'iconCls' => 'pimcore_icon_thumbnails',
  1010.                     'cls' => 'pimcore_treenode_disabled',
  1011.                     'writeable' => $item->isWriteable(),
  1012.                 ];
  1013.             }
  1014.         }
  1015.         foreach ($groups as $group) {
  1016.             $thumbnails[] = $group;
  1017.         }
  1018.         return $this->adminJson($thumbnails);
  1019.     }
  1020.     /**
  1021.      * @Route("/thumbnail-downloadable", name="pimcore_admin_settings_thumbnaildownloadable", methods={"GET"})
  1022.      *
  1023.      * @return JsonResponse
  1024.      */
  1025.     public function thumbnailDownloadableAction()
  1026.     {
  1027.         $thumbnails = [];
  1028.         $list = new Asset\Image\Thumbnail\Config\Listing();
  1029.         $list->setFilter(function (Asset\Image\Thumbnail\Config $config) {
  1030.             return $config->isDownloadable();
  1031.         });
  1032.         foreach ($list->getThumbnails() as $item) {
  1033.             $thumbnails[] = [
  1034.                 'id' => $item->getName(),
  1035.                 'text' => $item->getName(),
  1036.             ];
  1037.         }
  1038.         return $this->adminJson($thumbnails);
  1039.     }
  1040.     /**
  1041.      * @Route("/thumbnail-add", name="pimcore_admin_settings_thumbnailadd", methods={"POST"})
  1042.      *
  1043.      * @param Request $request
  1044.      *
  1045.      * @return JsonResponse
  1046.      */
  1047.     public function thumbnailAddAction(Request $request)
  1048.     {
  1049.         $this->checkPermission('thumbnails');
  1050.         $success false;
  1051.         $pipe Asset\Image\Thumbnail\Config::getByName($request->get('name'));
  1052.         if (!$pipe) {
  1053.             $pipe = new Asset\Image\Thumbnail\Config();
  1054.             if (!$pipe->isWriteable()) {
  1055.                 throw new ConfigWriteException();
  1056.             }
  1057.             $pipe->setName($request->get('name'));
  1058.             $pipe->save();
  1059.             $success true;
  1060.         } else {
  1061.             if (!$pipe->isWriteable()) {
  1062.                 throw new ConfigWriteException();
  1063.             }
  1064.         }
  1065.         return $this->adminJson(['success' => $success'id' => $pipe->getName()]);
  1066.     }
  1067.     /**
  1068.      * @Route("/thumbnail-delete", name="pimcore_admin_settings_thumbnaildelete", methods={"DELETE"})
  1069.      *
  1070.      * @param Request $request
  1071.      *
  1072.      * @return JsonResponse
  1073.      */
  1074.     public function thumbnailDeleteAction(Request $request)
  1075.     {
  1076.         $this->checkPermission('thumbnails');
  1077.         $pipe Asset\Image\Thumbnail\Config::getByName($request->get('name'));
  1078.         if (!$pipe->isWriteable()) {
  1079.             throw new ConfigWriteException();
  1080.         }
  1081.         $pipe->delete();
  1082.         return $this->adminJson(['success' => true]);
  1083.     }
  1084.     /**
  1085.      * @Route("/thumbnail-get", name="pimcore_admin_settings_thumbnailget", methods={"GET"})
  1086.      *
  1087.      * @param Request $request
  1088.      *
  1089.      * @return JsonResponse
  1090.      */
  1091.     public function thumbnailGetAction(Request $request)
  1092.     {
  1093.         $this->checkPermission('thumbnails');
  1094.         $pipe Asset\Image\Thumbnail\Config::getByName($request->get('name'));
  1095.         $data $pipe->getObjectVars();
  1096.         $data['writeable'] = $pipe->isWriteable();
  1097.         return $this->adminJson($data);
  1098.     }
  1099.     /**
  1100.      * @Route("/thumbnail-update", name="pimcore_admin_settings_thumbnailupdate", methods={"PUT"})
  1101.      *
  1102.      * @param Request $request
  1103.      *
  1104.      * @return JsonResponse
  1105.      */
  1106.     public function thumbnailUpdateAction(Request $request)
  1107.     {
  1108.         $this->checkPermission('thumbnails');
  1109.         $pipe Asset\Image\Thumbnail\Config::getByName($request->get('name'));
  1110.         if (!$pipe->isWriteable()) {
  1111.             throw new ConfigWriteException();
  1112.         }
  1113.         $settingsData $this->decodeJson($request->get('settings'));
  1114.         $mediaData $this->decodeJson($request->get('medias'));
  1115.         $mediaOrder $this->decodeJson($request->get('mediaOrder'));
  1116.         foreach ($settingsData as $key => $value) {
  1117.             $setter 'set' ucfirst($key);
  1118.             if (method_exists($pipe$setter)) {
  1119.                 $pipe->$setter($value);
  1120.             }
  1121.         }
  1122.         $pipe->resetItems();
  1123.         uksort($mediaData, function ($a$b) use ($mediaOrder) {
  1124.             if ($a === 'default') {
  1125.                 return -1;
  1126.             }
  1127.             return ($mediaOrder[$a] < $mediaOrder[$b]) ? -1;
  1128.         });
  1129.         foreach ($mediaData as $mediaName => $items) {
  1130.             if (preg_match('/["<>]/'$mediaName)) {
  1131.                 throw new \Exception('Invalid media query name');
  1132.             }
  1133.             foreach ($items as $item) {
  1134.                 $type $item['type'];
  1135.                 unset($item['type']);
  1136.                 $pipe->addItem($type$item$mediaName);
  1137.             }
  1138.         }
  1139.         $pipe->save();
  1140.         return $this->adminJson(['success' => true]);
  1141.     }
  1142.     /**
  1143.      * @Route("/video-thumbnail-adapter-check", name="pimcore_admin_settings_videothumbnailadaptercheck", methods={"GET"})
  1144.      *
  1145.      * @param Request $request
  1146.      *
  1147.      * @return Response
  1148.      */
  1149.     public function videoThumbnailAdapterCheckAction(Request $request)
  1150.     {
  1151.         $content '';
  1152.         if (!\Pimcore\Video::isAvailable()) {
  1153.             $content '<span style="color: red; font-weight: bold;padding: 10px;margin:0 0 20px 0;border:1px solid red;display:block;">' .
  1154.                 $this->trans('php_cli_binary_and_or_ffmpeg_binary_setting_is_missing') .
  1155.                 '</span>';
  1156.         }
  1157.         return new Response($content);
  1158.     }
  1159.     /**
  1160.      * @Route("/video-thumbnail-tree", name="pimcore_admin_settings_videothumbnailtree", methods={"GET", "POST"})
  1161.      *
  1162.      * @return JsonResponse
  1163.      */
  1164.     public function videoThumbnailTreeAction()
  1165.     {
  1166.         $this->checkPermission('thumbnails');
  1167.         $thumbnails = [];
  1168.         $list = new Asset\Video\Thumbnail\Config\Listing();
  1169.         $groups = [];
  1170.         foreach ($list->getThumbnails() as $item) {
  1171.             if ($item->getGroup()) {
  1172.                 if (empty($groups[$item->getGroup()])) {
  1173.                     $groups[$item->getGroup()] = [
  1174.                         'id' => 'group_' $item->getName(),
  1175.                         'text' => htmlspecialchars($item->getGroup()),
  1176.                         'expandable' => true,
  1177.                         'leaf' => false,
  1178.                         'allowChildren' => true,
  1179.                         'iconCls' => 'pimcore_icon_folder',
  1180.                         'group' => $item->getGroup(),
  1181.                         'children' => [],
  1182.                     ];
  1183.                 }
  1184.                 $groups[$item->getGroup()]['children'][] =
  1185.                     [
  1186.                         'id' => $item->getName(),
  1187.                         'text' => $item->getName(),
  1188.                         'leaf' => true,
  1189.                         'iconCls' => 'pimcore_icon_videothumbnails',
  1190.                         'cls' => 'pimcore_treenode_disabled',
  1191.                         'writeable' => $item->isWriteable(),
  1192.                     ];
  1193.             } else {
  1194.                 $thumbnails[] = [
  1195.                     'id' => $item->getName(),
  1196.                     'text' => $item->getName(),
  1197.                     'leaf' => true,
  1198.                     'iconCls' => 'pimcore_icon_videothumbnails',
  1199.                     'cls' => 'pimcore_treenode_disabled',
  1200.                     'writeable' => $item->isWriteable(),
  1201.                 ];
  1202.             }
  1203.         }
  1204.         foreach ($groups as $group) {
  1205.             $thumbnails[] = $group;
  1206.         }
  1207.         return $this->adminJson($thumbnails);
  1208.     }
  1209.     /**
  1210.      * @Route("/video-thumbnail-add", name="pimcore_admin_settings_videothumbnailadd", methods={"POST"})
  1211.      *
  1212.      * @param Request $request
  1213.      *
  1214.      * @return JsonResponse
  1215.      */
  1216.     public function videoThumbnailAddAction(Request $request)
  1217.     {
  1218.         $this->checkPermission('thumbnails');
  1219.         $success false;
  1220.         $pipe Asset\Video\Thumbnail\Config::getByName($request->get('name'));
  1221.         if (!$pipe) {
  1222.             $pipe = new Asset\Video\Thumbnail\Config();
  1223.             if (!$pipe->isWriteable()) {
  1224.                 throw new ConfigWriteException();
  1225.             }
  1226.             $pipe->setName($request->get('name'));
  1227.             $pipe->save();
  1228.             $success true;
  1229.         } else {
  1230.             if (!$pipe->isWriteable()) {
  1231.                 throw new ConfigWriteException();
  1232.             }
  1233.         }
  1234.         return $this->adminJson(['success' => $success'id' => $pipe->getName()]);
  1235.     }
  1236.     /**
  1237.      * @Route("/video-thumbnail-delete", name="pimcore_admin_settings_videothumbnaildelete", methods={"DELETE"})
  1238.      *
  1239.      * @param Request $request
  1240.      *
  1241.      * @return JsonResponse
  1242.      */
  1243.     public function videoThumbnailDeleteAction(Request $request)
  1244.     {
  1245.         $this->checkPermission('thumbnails');
  1246.         $pipe Asset\Video\Thumbnail\Config::getByName($request->get('name'));
  1247.         if (!$pipe->isWriteable()) {
  1248.             throw new ConfigWriteException();
  1249.         }
  1250.         $pipe->delete();
  1251.         return $this->adminJson(['success' => true]);
  1252.     }
  1253.     /**
  1254.      * @Route("/video-thumbnail-get", name="pimcore_admin_settings_videothumbnailget", methods={"GET"})
  1255.      *
  1256.      * @param Request $request
  1257.      *
  1258.      * @return JsonResponse
  1259.      */
  1260.     public function videoThumbnailGetAction(Request $request)
  1261.     {
  1262.         $this->checkPermission('thumbnails');
  1263.         $pipe Asset\Video\Thumbnail\Config::getByName($request->get('name'));
  1264.         $data $pipe->getObjectVars();
  1265.         $data['writeable'] = $pipe->isWriteable();
  1266.         return $this->adminJson($data);
  1267.     }
  1268.     /**
  1269.      * @Route("/video-thumbnail-update", name="pimcore_admin_settings_videothumbnailupdate", methods={"PUT"})
  1270.      *
  1271.      * @param Request $request
  1272.      *
  1273.      * @return JsonResponse
  1274.      */
  1275.     public function videoThumbnailUpdateAction(Request $request)
  1276.     {
  1277.         $this->checkPermission('thumbnails');
  1278.         $pipe Asset\Video\Thumbnail\Config::getByName($request->get('name'));
  1279.         if (!$pipe->isWriteable()) {
  1280.             throw new ConfigWriteException();
  1281.         }
  1282.         $settingsData $this->decodeJson($request->get('settings'));
  1283.         $mediaData $this->decodeJson($request->get('medias'));
  1284.         $mediaOrder $this->decodeJson($request->get('mediaOrder'));
  1285.         foreach ($settingsData as $key => $value) {
  1286.             $setter 'set' ucfirst($key);
  1287.             if (method_exists($pipe$setter)) {
  1288.                 $pipe->$setter($value);
  1289.             }
  1290.         }
  1291.         $pipe->resetItems();
  1292.         uksort($mediaData, function ($a$b) use ($mediaOrder) {
  1293.             if ($a === 'default') {
  1294.                 return -1;
  1295.             }
  1296.             return ($mediaOrder[$a] < $mediaOrder[$b]) ? -1;
  1297.         });
  1298.         foreach ($mediaData as $mediaName => $items) {
  1299.             foreach ($items as $item) {
  1300.                 $type $item['type'];
  1301.                 unset($item['type']);
  1302.                 $pipe->addItem($type$item$mediaName);
  1303.             }
  1304.         }
  1305.         $pipe->save();
  1306.         return $this->adminJson(['success' => true]);
  1307.     }
  1308.     /**
  1309.      * @Route("/robots-txt", name="pimcore_admin_settings_robotstxtget", methods={"GET"})
  1310.      *
  1311.      * @return JsonResponse
  1312.      */
  1313.     public function robotsTxtGetAction()
  1314.     {
  1315.         $this->checkPermission('robots.txt');
  1316.         $config Config::getRobotsConfig();
  1317.         $config $config->toArray();
  1318.         return $this->adminJson([
  1319.             'success' => true,
  1320.             'data' => $config,
  1321.             'onFileSystem' => file_exists(PIMCORE_WEB_ROOT '/robots.txt'),
  1322.         ]);
  1323.     }
  1324.     /**
  1325.      * @Route("/robots-txt", name="pimcore_admin_settings_robotstxtput", methods={"PUT"})
  1326.      *
  1327.      * @param Request $request
  1328.      *
  1329.      * @return JsonResponse
  1330.      */
  1331.     public function robotsTxtPutAction(Request $request)
  1332.     {
  1333.         $this->checkPermission('robots.txt');
  1334.         $values $request->get('data');
  1335.         if (!is_array($values)) {
  1336.             $values = [];
  1337.         }
  1338.         foreach ($values as $siteId => $robotsContent) {
  1339.             SettingsStore::set('robots.txt-' $siteId$robotsContent'string''robots.txt');
  1340.         }
  1341.         return $this->adminJson([
  1342.             'success' => true,
  1343.         ]);
  1344.     }
  1345.     /**
  1346.      * @Route("/website-settings", name="pimcore_admin_settings_websitesettings", methods={"POST"})
  1347.      *
  1348.      * @param Request $request
  1349.      *
  1350.      * @return JsonResponse
  1351.      *
  1352.      * @throws \Exception
  1353.      */
  1354.     public function websiteSettingsAction(Request $request)
  1355.     {
  1356.         $this->checkPermission('website_settings');
  1357.         if ($request->get('data')) {
  1358.             $data $this->decodeJson($request->get('data'));
  1359.             if (is_array($data)) {
  1360.                 foreach ($data as &$value) {
  1361.                     $value trim($value);
  1362.                 }
  1363.             }
  1364.             if ($request->get('xaction') == 'destroy') {
  1365.                 $id $data['id'];
  1366.                 $setting WebsiteSetting::getById($id);
  1367.                 if ($setting instanceof WebsiteSetting) {
  1368.                     $setting->delete();
  1369.                     return $this->adminJson(['success' => true'data' => []]);
  1370.                 }
  1371.             } elseif ($request->get('xaction') == 'update') {
  1372.                 // save routes
  1373.                 $setting WebsiteSetting::getById($data['id']);
  1374.                 if ($setting instanceof WebsiteSetting) {
  1375.                     switch ($setting->getType()) {
  1376.                         case 'document':
  1377.                         case 'asset':
  1378.                         case 'object':
  1379.                             if (isset($data['data'])) {
  1380.                                 $element Element\Service::getElementByPath($setting->getType(), $data['data']);
  1381.                                 $data['data'] = $element;
  1382.                             }
  1383.                             break;
  1384.                     }
  1385.                     $setting->setValues($data);
  1386.                     $setting->save();
  1387.                     $data $this->getWebsiteSettingForEditMode($setting);
  1388.                     return $this->adminJson(['data' => $data'success' => true]);
  1389.                 }
  1390.             } elseif ($request->get('xaction') == 'create') {
  1391.                 unset($data['id']);
  1392.                 // save route
  1393.                 $setting = new WebsiteSetting();
  1394.                 $setting->setValues($data);
  1395.                 $setting->save();
  1396.                 return $this->adminJson(['data' => $setting->getObjectVars(), 'success' => true]);
  1397.             }
  1398.         } else {
  1399.             $list = new WebsiteSetting\Listing();
  1400.             $list->setLimit($request->get('limit'));
  1401.             $list->setOffset($request->get('start'));
  1402.             $sortingSettings \Pimcore\Bundle\AdminBundle\Helper\QueryParams::extractSortingSettings(array_merge($request->request->all(), $request->query->all()));
  1403.             if ($sortingSettings['orderKey']) {
  1404.                 $list->setOrderKey($sortingSettings['orderKey']);
  1405.                 $list->setOrder($sortingSettings['order']);
  1406.             } else {
  1407.                 $list->setOrderKey('name');
  1408.                 $list->setOrder('asc');
  1409.             }
  1410.             if ($request->get('filter')) {
  1411.                 $list->setCondition('`name` LIKE ' $list->quote('%'.$request->get('filter').'%'));
  1412.             }
  1413.             $totalCount $list->getTotalCount();
  1414.             $list $list->load();
  1415.             $settings = [];
  1416.             foreach ($list as $item) {
  1417.                 $resultItem $this->getWebsiteSettingForEditMode($item);
  1418.                 $settings[] = $resultItem;
  1419.             }
  1420.             return $this->adminJson(['data' => $settings'success' => true'total' => $totalCount]);
  1421.         }
  1422.         return $this->adminJson(['success' => false]);
  1423.     }
  1424.     /**
  1425.      * @param WebsiteSetting $item
  1426.      *
  1427.      * @return array
  1428.      */
  1429.     private function getWebsiteSettingForEditMode($item)
  1430.     {
  1431.         $resultItem = [
  1432.             'id' => $item->getId(),
  1433.             'name' => $item->getName(),
  1434.             'language' => $item->getLanguage(),
  1435.             'type' => $item->getType(),
  1436.             'data' => null,
  1437.             'siteId' => $item->getSiteId(),
  1438.             'creationDate' => $item->getCreationDate(),
  1439.             'modificationDate' => $item->getModificationDate(),
  1440.         ];
  1441.         switch ($item->getType()) {
  1442.             case 'document':
  1443.             case 'asset':
  1444.             case 'object':
  1445.                 $element $item->getData();
  1446.                 if ($element) {
  1447.                     $resultItem['data'] = $element->getRealFullPath();
  1448.                 }
  1449.                 break;
  1450.             default:
  1451.                 $resultItem['data'] = $item->getData();
  1452.                 break;
  1453.         }
  1454.         return $resultItem;
  1455.     }
  1456.     /**
  1457.      * @Route("/get-available-algorithms", name="pimcore_admin_settings_getavailablealgorithms", methods={"GET"})
  1458.      *
  1459.      * @param Request $request
  1460.      *
  1461.      * @return JsonResponse
  1462.      */
  1463.     public function getAvailableAlgorithmsAction(Request $request)
  1464.     {
  1465.         $options = [
  1466.             [
  1467.                 'key' => 'password_hash',
  1468.                 'value' => 'password_hash',
  1469.             ],
  1470.         ];
  1471.         $algorithms hash_algos();
  1472.         foreach ($algorithms as $algorithm) {
  1473.             $options[] = [
  1474.                 'key' => $algorithm,
  1475.                 'value' => $algorithm,
  1476.             ];
  1477.         }
  1478.         $result = ['data' => $options'success' => true'total' => count($options)];
  1479.         return $this->adminJson($result);
  1480.     }
  1481.     /**
  1482.      * deleteViews
  1483.      * delete views for localized fields when languages are removed to
  1484.      * prevent mysql errors
  1485.      *
  1486.      * @param string $language
  1487.      * @param string $dbName
  1488.      */
  1489.     protected function deleteViews($language$dbName)
  1490.     {
  1491.         $db \Pimcore\Db::get();
  1492.         $views $db->fetchAll('SHOW FULL TABLES IN ' $db->quoteIdentifier($dbName) . " WHERE TABLE_TYPE LIKE 'VIEW'");
  1493.         foreach ($views as $view) {
  1494.             if (preg_match('/^object_localized_[0-9]+_' $language '$/'$view['Tables_in_' $dbName])) {
  1495.                 $sql 'DROP VIEW ' $db->quoteIdentifier($view['Tables_in_' $dbName]);
  1496.                 $db->query($sql);
  1497.             }
  1498.         }
  1499.     }
  1500.     /**
  1501.      * @Route("/test-web2print", name="pimcore_admin_settings_testweb2print", methods={"GET"})
  1502.      *
  1503.      * @param Request $request
  1504.      *
  1505.      * @return Response
  1506.      */
  1507.     public function testWeb2printAction(Request $request)
  1508.     {
  1509.         $this->checkPermission('web2print_settings');
  1510.         $response $this->render('@PimcoreAdmin/Admin/Settings/testWeb2print.html.twig');
  1511.         $html $response->getContent();
  1512.         $adapter \Pimcore\Web2Print\Processor::getInstance();
  1513.         $params = [];
  1514.         if ($adapter instanceof \Pimcore\Web2Print\Processor\WkHtmlToPdf) {
  1515.             $params['adapterConfig'] = '-O landscape';
  1516.         } elseif ($adapter instanceof \Pimcore\Web2Print\Processor\PdfReactor) {
  1517.             $params['adapterConfig'] = [
  1518.                 'javaScriptMode' => 0,
  1519.                 'addLinks' => true,
  1520.                 'appendLog' => true,
  1521.                 'enableDebugMode' => true,
  1522.             ];
  1523.         }
  1524.         $responseOptions = [
  1525.             'Content-Type' => 'application/pdf',
  1526.         ];
  1527.         $pdfData $adapter->getPdfFromString($html$params);
  1528.         return new \Symfony\Component\HttpFoundation\Response(
  1529.             $pdfData,
  1530.             200,
  1531.             $responseOptions
  1532.         );
  1533.     }
  1534. }