vendor/pimcore/pimcore/lib/Kernel.php line 322

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;
  15. use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
  16. use Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle;
  17. use FOS\JsRoutingBundle\FOSJsRoutingBundle;
  18. use League\FlysystemBundle\FlysystemBundle;
  19. use Pimcore\Bundle\AdminBundle\PimcoreAdminBundle;
  20. use Pimcore\Bundle\CoreBundle\PimcoreCoreBundle;
  21. use Pimcore\Cache\RuntimeCache;
  22. use Pimcore\Config\BundleConfigLocator;
  23. use Pimcore\Event\SystemEvents;
  24. use Pimcore\Extension\Bundle\Config\StateConfig;
  25. use Pimcore\HttpKernel\BundleCollection\BundleCollection;
  26. use Pimcore\HttpKernel\BundleCollection\ItemInterface;
  27. use Pimcore\HttpKernel\BundleCollection\LazyLoadedItem;
  28. use Presta\SitemapBundle\PrestaSitemapBundle;
  29. use Scheb\TwoFactorBundle\SchebTwoFactorBundle;
  30. use Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle;
  31. use Symfony\Bundle\DebugBundle\DebugBundle;
  32. use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
  33. use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
  34. use Symfony\Bundle\MonologBundle\MonologBundle;
  35. use Symfony\Bundle\SecurityBundle\SecurityBundle;
  36. use Symfony\Bundle\TwigBundle\TwigBundle;
  37. use Symfony\Bundle\WebProfilerBundle\WebProfilerBundle;
  38. use Symfony\Cmf\Bundle\RoutingBundle\CmfRoutingBundle;
  39. use Symfony\Component\Config\Definition\Processor;
  40. use Symfony\Component\Config\Loader\LoaderInterface;
  41. use Symfony\Component\Config\Resource\FileExistenceResource;
  42. use Symfony\Component\Config\Resource\FileResource;
  43. use Symfony\Component\DependencyInjection\ContainerBuilder;
  44. use Symfony\Component\DependencyInjection\ContainerInterface;
  45. use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
  46. use Symfony\Component\EventDispatcher\GenericEvent;
  47. use Symfony\Component\HttpKernel\Bundle\BundleInterface;
  48. use Symfony\Component\HttpKernel\Kernel as SymfonyKernel;
  49. use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
  50. use Twig\Extra\TwigExtraBundle\TwigExtraBundle;
  51. abstract class Kernel extends SymfonyKernel
  52. {
  53.     use MicroKernelTrait {
  54.         registerContainerConfiguration as microKernelRegisterContainerConfiguration;
  55.         registerBundles as microKernelRegisterBundles;
  56.     }
  57.     private const CONFIG_LOCATION 'config_location';
  58.     /**
  59.      * @deprecated will be removed in Pimcore 11
  60.      *
  61.      * @var Extension\Config
  62.      */
  63.     protected $extensionConfig;
  64.     /**
  65.      * @var BundleCollection
  66.      */
  67.     private $bundleCollection;
  68.     /**
  69.      * @deprecated
  70.      */
  71.     public function getRootDir()
  72.     {
  73.         trigger_deprecation(
  74.             'pimcore/pimcore',
  75.             '10.3',
  76.             'Kernel::getRootDir() is deprecated and will be removed in Pimcore 11. Use Kernel::getProjectDir() instead.',
  77.         );
  78.         return PIMCORE_PROJECT_ROOT;
  79.     }
  80.     /**
  81.      * {@inheritdoc}
  82.      *
  83.      * @return string
  84.      */
  85.     #[\ReturnTypeWillChange]
  86.     public function getProjectDir()// : string
  87.     {
  88.         return PIMCORE_PROJECT_ROOT;
  89.     }
  90.     /**
  91.      * {@inheritdoc}
  92.      *
  93.      * @return string
  94.      */
  95.     #[\ReturnTypeWillChange]
  96.     public function getCacheDir()// : string
  97.     {
  98.         if (isset($_SERVER['APP_CACHE_DIR'])) {
  99.             return $_SERVER['APP_CACHE_DIR'].'/'.$this->environment;
  100.         }
  101.         return PIMCORE_SYMFONY_CACHE_DIRECTORY '/' $this->environment;
  102.     }
  103.     /**
  104.      * {@inheritdoc}
  105.      *
  106.      * @return string
  107.      */
  108.     #[\ReturnTypeWillChange]
  109.     public function getLogDir()// : string
  110.     {
  111.         return PIMCORE_LOG_DIRECTORY;
  112.     }
  113.     /**
  114.      * {@inheritdoc}
  115.      */
  116.     protected function configureContainer(ContainerConfigurator $container): void
  117.     {
  118.         $projectDir realpath($this->getProjectDir());
  119.         $container->import($projectDir '/config/{packages}/*.yaml');
  120.         $container->import($projectDir '/config/{packages}/'.$this->environment.'/*.yaml');
  121.         if (is_file($projectDir '/config/services.yaml')) {
  122.             $container->import($projectDir '/config/services.yaml');
  123.             $container->import($projectDir '/config/{services}_'.$this->environment.'.yaml');
  124.         } elseif (is_file($path $projectDir '/config/services.php')) {
  125.             (require $path)($container->withPath($path), $this);
  126.         }
  127.     }
  128.     /**
  129.      * {@inheritdoc}
  130.      */
  131.     protected function configureRoutes(RoutingConfigurator $routes): void
  132.     {
  133.         $projectDir realpath($this->getProjectDir());
  134.         $routes->import($projectDir '/config/{routes}/'.$this->environment.'/*.yaml');
  135.         $routes->import($projectDir '/config/{routes}/*.yaml');
  136.         if (is_file($projectDir '/config/routes.yaml')) {
  137.             $routes->import($projectDir '/config/routes.yaml');
  138.         } elseif (is_file($path $projectDir '/config/routes.php')) {
  139.             (require $path)($routes->withPath($path), $this);
  140.         }
  141.     }
  142.     /**
  143.      * {@inheritdoc}
  144.      */
  145.     public function registerContainerConfiguration(LoaderInterface $loader)
  146.     {
  147.         $loader->load(function (ContainerBuilder $container) {
  148.             $this->registerExtensionConfigFileResources($container);
  149.         });
  150.         $bundleConfigLocator = new BundleConfigLocator($this);
  151.         foreach ($bundleConfigLocator->locate('config') as $bundleConfig) {
  152.             $loader->load($bundleConfig);
  153.         }
  154.         $this->microKernelRegisterContainerConfiguration($loader);
  155.         //load system configuration
  156.         $systemConfigFile Config::locateConfigFile('system.yml');
  157.         if (file_exists($systemConfigFile)) {
  158.             $loader->load($systemConfigFile);
  159.         }
  160.         $configArray = [
  161.             [
  162.                 'storageDirectoryEnvVariableName' => 'PIMCORE_CONFIG_STORAGE_DIR_IMAGE_THUMBNAILS',
  163.                 'defaultStorageDirectoryName' => 'image_thumbnails',
  164.             ],
  165.             [
  166.                 'storageDirectoryEnvVariableName' => 'PIMCORE_CONFIG_STORAGE_DIR_VIDEO_THUMBNAILS',
  167.                 'defaultStorageDirectoryName' => 'video_thumbnails',
  168.             ],
  169.             [
  170.                 'storageDirectoryEnvVariableName' => 'PIMCORE_CONFIG_STORAGE_DIR_CUSTOM_REPORTS',
  171.                 'defaultStorageDirectoryName' => 'custom_reports',
  172.             ],
  173.             [
  174.                 'storageDirectoryEnvVariableName' => 'PIMCORE_CONFIG_STORAGE_DIR_DOCUMENT_TYPES',
  175.                 'defaultStorageDirectoryName' => 'document_types',
  176.             ],
  177.             [
  178.                 'storageDirectoryEnvVariableName' => 'PIMCORE_CONFIG_STORAGE_DIR_WEB_TO_PRINT',
  179.                 'defaultStorageDirectoryName' => 'web_to_print',
  180.             ],
  181.             [
  182.                 'storageDirectoryEnvVariableName' => 'PIMCORE_CONFIG_STORAGE_DIR_PREDEFINED_PROPERTIES',
  183.                 'defaultStorageDirectoryName' => 'predefined_properties',
  184.             ],
  185.             [
  186.                 'storageDirectoryEnvVariableName' => 'PIMCORE_CONFIG_STORAGE_DIR_PREDEFINED_ASSET_METADATA',
  187.                 'defaultStorageDirectoryName' => 'predefined_asset_metadata',
  188.             ],
  189.             [
  190.                 'storageDirectoryEnvVariableName' => 'PIMCORE_CONFIG_STORAGE_DIR_STATICROUTES',
  191.                 'defaultStorageDirectoryName' => 'staticroutes',
  192.             ],
  193.             [
  194.                 'storageDirectoryEnvVariableName' => 'PIMCORE_CONFIG_STORAGE_DIR_PERSPECTIVES',
  195.                 'defaultStorageDirectoryName' => 'perspectives',
  196.             ],
  197.             [
  198.                 'storageDirectoryEnvVariableName' => 'PIMCORE_CONFIG_STORAGE_DIR_CUSTOM_VIEWS',
  199.                 'defaultStorageDirectoryName' => 'custom_views',
  200.             ],
  201.         ];
  202.         $loader->load(function (ContainerBuilder $container) use ($loader$configArray) {
  203.             $containerConfig $container->getExtensionConfig('pimcore');
  204.             $containerConfig array_merge(...$containerConfig);
  205.             $processor = new Processor();
  206.             // @phpstan-ignore-next-line
  207.             $configuration $container->getExtension('pimcore')->getConfiguration($containerConfig$container);
  208.             $containerConfig $processor->processConfiguration($configuration, ['pimcore' => $containerConfig]);
  209.             $resolvingBag $container->getParameterBag();
  210.             $containerConfig $resolvingBag->resolveValue($containerConfig);
  211.             if (!array_key_exists(self::CONFIG_LOCATION$containerConfig)) {
  212.                 return;
  213.             }
  214.             foreach ($configArray as $config) {
  215.                 $configKey $config['defaultStorageDirectoryName'];
  216.                 if (!isset($containerConfig[self::CONFIG_LOCATION][$configKey])) {
  217.                     continue;
  218.                 }
  219.                 $configDir rtrim(self::getStorageDirectoryFromSymfonyConfig($containerConfig$configKey$config['storageDirectoryEnvVariableName']), '/\\');
  220.                 $configDir "$configDir/";
  221.                 if (is_dir($configDir)) {
  222.                     // @phpstan-ignore-next-line
  223.                     $loader->import($configDir);
  224.                 }
  225.             }
  226.         });
  227.     }
  228.     private static function getStorageDirectoryFromSymfonyConfig(array $configstring $configKeystring $storageDir): string
  229.     {
  230.         if (isset($_SERVER[$storageDir])) {
  231.             trigger_deprecation('pimcore/pimcore''10.6',
  232.                 sprintf('Setting storage directory (%s) in the .env file is deprecated, instead use the symfony config. It will be removed in Pimcore 11.'$storageDir));
  233.             return $_SERVER[$storageDir];
  234.         }
  235.         return $config[self::CONFIG_LOCATION][$configKey]['write_target']['options']['directory'];
  236.     }
  237.     /**
  238.      * @param ContainerBuilder $container
  239.      *
  240.      * @return void
  241.      *
  242.      * @deprecated Remove in Pimcore 11
  243.      */
  244.     private function registerExtensionConfigFileResources(ContainerBuilder $container)
  245.     {
  246.         $filenames = [
  247.             'extensions.php',
  248.             sprintf('extensions_%s.php'$this->getEnvironment()),
  249.         ];
  250.         $directories = [
  251.             PIMCORE_CUSTOM_CONFIGURATION_DIRECTORY,
  252.             PIMCORE_CONFIGURATION_DIRECTORY,
  253.         ];
  254.         // add possible extensions.php files as file existence resources (only for the current env)
  255.         foreach ($directories as $directory) {
  256.             foreach ($filenames as $filename) {
  257.                 $container->addResource(new FileExistenceResource($directory '/' $filename));
  258.             }
  259.         }
  260.         // add extensions.php as container resource
  261.         if ($this->extensionConfig->configFileExists()) {
  262.             $container->addResource(new FileResource($this->extensionConfig->locateConfigFile()));
  263.         }
  264.     }
  265.     /**
  266.      * {@inheritdoc}
  267.      */
  268.     public function boot()
  269.     {
  270.         if (true === $this->booted) {
  271.             // make sure container reset is handled properly
  272.             parent::boot();
  273.             return;
  274.         }
  275.         // handle system requirements
  276.         $this->setSystemRequirements();
  277.         // initialize extension manager config
  278.         $this->extensionConfig = new Extension\Config();
  279.         parent::boot();
  280.     }
  281.     /**
  282.      * {@inheritdoc}
  283.      */
  284.     public function shutdown()
  285.     {
  286.         if (true === $this->booted) {
  287.             // cleanup runtime cache, doctrine, monolog ... to free some memory and avoid locking issues
  288.             $this->container->get(\Pimcore\Helper\LongRunningHelper::class)->cleanUp();
  289.         }
  290.         parent::shutdown();
  291.     }
  292.     /**
  293.      * {@inheritdoc}
  294.      */
  295.     protected function initializeContainer()
  296.     {
  297.         parent::initializeContainer();
  298.         // initialize runtime cache (defined as synthetic service)
  299.         RuntimeCache::getInstance();
  300.         // set the extension config on the container
  301.         $this->getContainer()->set(Extension\Config::class, $this->extensionConfig);
  302.         \Pimcore::initLogger();
  303.         \Pimcore\Cache::init();
  304.         // on pimcore shutdown
  305.         register_shutdown_function(function () {
  306.             // check if container still exists at this point as it could already
  307.             // be cleared (e.g. when running tests which boot multiple containers)
  308.             try {
  309.                 $container $this->getContainer();
  310.             } catch (\LogicException) {
  311.                 // Container is cleared. Allow tests to finish.
  312.             }
  313.             if (isset($container) && $container instanceof ContainerInterface) {
  314.                 $container->get('event_dispatcher')->dispatch(new GenericEvent(), SystemEvents::SHUTDOWN);
  315.             }
  316.             \Pimcore::shutdown();
  317.         });
  318.     }
  319.     /**
  320.      * Returns an array of bundles to register.
  321.      *
  322.      * @return BundleInterface[] An array of bundle instances
  323.      */
  324.     public function registerBundles(): array
  325.     {
  326.         $collection $this->createBundleCollection();
  327.         if (is_file($this->getProjectDir().'/config/bundles.php')) {
  328.             $flexBundles = [];
  329.             array_push($flexBundles, ...$this->microKernelRegisterBundles());
  330.             $collection->addBundles($flexBundles);
  331.         }
  332.         // core bundles (Symfony, Pimcore)
  333.         $this->registerCoreBundlesToCollection($collection);
  334.         // custom bundles
  335.         $this->registerBundlesToCollection($collection);
  336.         // bundles registered in extensions.php
  337.         $this->registerExtensionManagerBundles($collection);
  338.         $bundles $collection->getBundles($this->getEnvironment());
  339.         $this->bundleCollection $collection;
  340.         return $bundles;
  341.     }
  342.     /**
  343.      * Creates bundle collection. Use this method to set bundles on the collection
  344.      * early.
  345.      *
  346.      * @return BundleCollection
  347.      */
  348.     protected function createBundleCollection(): BundleCollection
  349.     {
  350.         return new BundleCollection();
  351.     }
  352.     /**
  353.      * Returns the bundle collection which was used to build the set of used bundles
  354.      *
  355.      * @return BundleCollection
  356.      */
  357.     public function getBundleCollection(): BundleCollection
  358.     {
  359.         return $this->bundleCollection;
  360.     }
  361.     /**
  362.      * Registers "core" bundles
  363.      *
  364.      * @param BundleCollection $collection
  365.      */
  366.     protected function registerCoreBundlesToCollection(BundleCollection $collection)
  367.     {
  368.         $collection->addBundles([
  369.             // symfony "core"/standard
  370.             new FrameworkBundle(),
  371.             new SecurityBundle(),
  372.             new TwigBundle(),
  373.             new TwigExtraBundle(),
  374.             new MonologBundle(),
  375.             new DoctrineBundle(),
  376.             new DoctrineMigrationsBundle(),
  377.             new SensioFrameworkExtraBundle(),
  378.             new CmfRoutingBundle(),
  379.             new PrestaSitemapBundle(),
  380.             new SchebTwoFactorBundle(),
  381.             new FOSJsRoutingBundle(),
  382.             new FlysystemBundle(),
  383.         ], 100);
  384.         // pimcore bundles
  385.         $collection->addBundles([
  386.             new PimcoreCoreBundle(),
  387.             new PimcoreAdminBundle(),
  388.         ], 60);
  389.         // load development bundles only in matching environments
  390.         if (in_array($this->getEnvironment(), $this->getEnvironmentsForDevBundles(), true)) {
  391.             $collection->addBundles([
  392.                 new DebugBundle(),
  393.                 new WebProfilerBundle(),
  394.             ], 80);
  395.         }
  396.     }
  397.     protected function getEnvironmentsForDevBundles(): array
  398.     {
  399.         return ['dev''test'];
  400.     }
  401.     /**
  402.      * Registers bundles enabled via extension manager
  403.      *
  404.      * @deprecated will be removed in Pimcore 11
  405.      *
  406.      * @param BundleCollection $collection
  407.      */
  408.     protected function registerExtensionManagerBundles(BundleCollection $collection)
  409.     {
  410.         $stateConfig = new StateConfig($this->extensionConfig);
  411.         foreach ($stateConfig->getEnabledBundles() as $className => $options) {
  412.             if (!class_exists($className)) {
  413.                 continue;
  414.             }
  415.             // do not register bundles twice - skip if it was already loaded manually
  416.             if ($collection->hasItem($className)) {
  417.                 continue;
  418.             }
  419.             // use lazy loaded item to instantiate the bundle only if environment matches
  420.             $collection->add(new LazyLoadedItem(
  421.                 $className,
  422.                 $options['priority'],
  423.                 $options['environments'],
  424.                 ItemInterface::SOURCE_EXTENSION_MANAGER_CONFIG
  425.             ));
  426.         }
  427.     }
  428.     /**
  429.      * Adds bundles to register to the bundle collection. The collection is able
  430.      * to handle priorities and environment specific bundles.
  431.      *
  432.      * To be implemented in child classes
  433.      *
  434.      * @param BundleCollection $collection
  435.      */
  436.     public function registerBundlesToCollection(BundleCollection $collection)
  437.     {
  438.     }
  439.     /**
  440.      * Handle system settings and requirements
  441.      */
  442.     protected function setSystemRequirements()
  443.     {
  444.         // try to set system-internal variables
  445.         $maxExecutionTime 240;
  446.         if (php_sapi_name() === 'cli') {
  447.             $maxExecutionTime 0;
  448.         }
  449.         //@ini_set("memory_limit", "1024M");
  450.         @ini_set('max_execution_time', (string) $maxExecutionTime);
  451.         @set_time_limit($maxExecutionTime);
  452.         ini_set('default_charset''UTF-8');
  453.         // set internal character encoding to UTF-8
  454.         mb_internal_encoding('UTF-8');
  455.         // zlib.output_compression conflicts with while (@ob_end_flush()) ;
  456.         // see also: https://github.com/pimcore/pimcore/issues/291
  457.         if (ini_get('zlib.output_compression')) {
  458.             @ini_set('zlib.output_compression''Off');
  459.         }
  460.         // set dummy timezone if no tz is specified / required for example by the logger, ...
  461.         $defaultTimezone = @date_default_timezone_get();
  462.         if (!$defaultTimezone) {
  463.             date_default_timezone_set('UTC'); // UTC -> default timezone
  464.         }
  465.     }
  466.     /**
  467.      * {@inheritdoc}
  468.      */
  469.     public function locateResource(string $name)
  470.     {
  471.         // BC layer for supporting both presta/sitemap-bundle": "^2.1 || ^3.2
  472.         // @TODO to be removed in Pimcore 11
  473.         if ($name === '@PrestaSitemapBundle/Resources/config/routing.yml') {
  474.             try {
  475.                 // try the new location of v3 first, as most probably this is used
  476.                 return parent::locateResource('@PrestaSitemapBundle/config/routing.yml');
  477.             } catch (\InvalidArgumentException $e) {
  478.                 // if the file doesnt exist in the new location, try the v2 location
  479.                 return parent::locateResource($name);
  480.             }
  481.         }
  482.         return parent::locateResource($name);
  483.     }
  484. }