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

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