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

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