2 namespace TYPO3\CMS\Core\Core
;
5 * This file is part of the TYPO3 CMS project.
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
14 * The TYPO3 project - inspiring people to share!
17 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility
;
18 use TYPO3\CMS\Core\Utility\GeneralUtility
;
19 use TYPO3\CMS\Core\Utility\MathUtility
;
22 * This class encapsulates bootstrap related methods.
23 * It is required directly as the very first thing in entry scripts and
24 * used to define all base things like constants and pathes and so on.
26 * Most methods in this class have dependencies to each other. They can
27 * not be called in arbitrary order. The methods are ordered top down, so
28 * a method at the beginning has lower dependencies than a method further
29 * down. Do not fiddle with the load order in own scripts except you know
30 * exactly what you are doing!
35 * @var \TYPO3\CMS\Core\Core\Bootstrap
37 protected static $instance = null;
47 * The application context
49 * @var \TYPO3\CMS\Core\Core\ApplicationContext
51 protected $applicationContext;
54 * @var array List of early instances
56 protected $earlyInstances = array();
59 * @var string Path to install tool
61 protected $installToolPath;
64 * A list of all registered request handlers, see the Application class / entry points for the registration
65 * @var \TYPO3\CMS\Core\Http\RequestHandlerInterface[]|\TYPO3\CMS\Core\Console\RequestHandlerInterface[]
67 protected $availableRequestHandlers = array();
70 * The Response object when using Request/Response logic
71 * @var \Psr\Http\Message\ResponseInterface
79 protected static $usesComposerClassLoading = false;
82 * Disable direct creation of this object.
83 * Set unique requestId and the application context
85 * @var string Application context
87 protected function __construct($applicationContext)
89 $this->requestId
= substr(md5(uniqid('', true)), 0, 13);
90 $this->applicationContext
= new ApplicationContext($applicationContext);
96 public static function usesComposerClassLoading()
98 return self
::$usesComposerClassLoading;
102 * Disable direct cloning of this object.
104 protected function __clone()
109 * Return 'this' as singleton
112 * @internal This is not a public API method, do not use in own extensions
114 public static function getInstance()
116 if (is_null(static::$instance)) {
117 $applicationContext = getenv('TYPO3_CONTEXT') ?
: (getenv('REDIRECT_TYPO3_CONTEXT') ?
: 'Production');
118 self
::$instance = new static($applicationContext);
119 self
::$instance->defineTypo3RequestTypes();
121 return static::$instance;
125 * Gets the request's unique ID
127 * @return string Unique request ID
128 * @internal This is not a public API method, do not use in own extensions
130 public function getRequestId()
132 return $this->requestId
;
136 * Returns the application context this bootstrap was started in.
138 * @return \TYPO3\CMS\Core\Core\ApplicationContext The application context encapsulated in an object
139 * @internal This is not a public API method, do not use in own extensions.
140 * Use \TYPO3\CMS\Core\Utility\GeneralUtility::getApplicationContext() instead
142 public function getApplicationContext()
144 return $this->applicationContext
;
148 * Prevent any unwanted output that may corrupt AJAX/compression.
149 * This does not interfere with "die()" or "echo"+"exit()" messages!
152 * @internal This is not a public API method, do not use in own extensions
154 public function startOutputBuffering()
161 * Main entry point called at every request usually from Global scope. Checks if everything is correct,
162 * and loads the Configuration.
164 * Make sure that the baseSetup() is called before and the class loader is present
168 public function configure()
170 $this->startOutputBuffering()
171 ->loadConfigurationAndInitialize()
172 ->loadTypo3LoadedExtAndExtLocalconf(true)
173 ->setFinalCachingFrameworkCacheConfiguration()
174 ->defineLoggingAndExceptionConstants()
175 ->unsetReservedGlobalVariables()
176 ->initializeTypo3DbGlobal();
182 * Run the base setup that checks server environment, determines pathes,
183 * populates base files and sets common configuration.
185 * Script execution will be aborted if something fails here.
187 * @param string $relativePathPart Relative path of entry script back to document root
189 * @throws \RuntimeException when TYPO3_REQUESTTYPE was not set before, setRequestType() needs to be called before
190 * @internal This is not a public API method, do not use in own extensions
192 public function baseSetup($relativePathPart = '')
194 if (!defined('TYPO3_REQUESTTYPE')) {
195 throw new \
RuntimeException('No Request Type was set, TYPO3 does not know in which context it is run.', 1450561838);
197 SystemEnvironmentBuilder
::run($relativePathPart);
198 if (!self
::$usesComposerClassLoading && ClassLoadingInformation
::isClassLoadingInformationAvailable()) {
199 ClassLoadingInformation
::registerClassLoadingInformation();
201 GeneralUtility
::presetApplicationContext($this->applicationContext
);
206 * Sets the class loader to the bootstrap
208 * @param \Composer\Autoload\ClassLoader $classLoader an instance of the class loader
210 * @internal This is not a public API method, do not use in own extensions
212 public function initializeClassLoader($classLoader)
214 $this->setEarlyInstance(\Composer\Autoload\ClassLoader
::class, $classLoader);
215 if (defined('TYPO3_COMPOSER_MODE') && TYPO3_COMPOSER_MODE
) {
216 self
::$usesComposerClassLoading = true;
222 * checks if LocalConfiguration.php or PackageStates.php is missing,
223 * used to see if a redirect to the install tool is needed
225 * @return bool TRUE when the essential configuration is available, otherwise FALSE
226 * @internal This is not a public API method, do not use in own extensions
228 public function checkIfEssentialConfigurationExists()
230 $configurationManager = new \TYPO3\CMS\Core\Configuration\ConfigurationManager
;
231 $this->setEarlyInstance(\TYPO3\CMS\Core\Configuration\ConfigurationManager
::class, $configurationManager);
232 return file_exists($configurationManager->getLocalConfigurationFileLocation()) && file_exists(PATH_typo3conf
. 'PackageStates.php');
236 * Redirect to install tool if LocalConfiguration.php is missing.
238 * @internal This is not a public API method, do not use in own extensions
240 public function redirectToInstallTool($relativePathPart = '')
242 $backPathToSiteRoot = str_repeat('../', count(explode('/', $relativePathPart)) - 1);
243 header('Location: ' . $backPathToSiteRoot . 'typo3/sysext/install/Start/Install.php');
248 * Adds available request handlers usually done via an application from the outside.
250 * @param string $requestHandler class which implements the request handler interface
252 * @internal This is not a public API method, do not use in own extensions
254 public function registerRequestHandlerImplementation($requestHandler)
256 $this->availableRequestHandlers
[] = $requestHandler;
261 * Fetches the request handler that suits the best based on the priority and the interface
262 * Be sure to always have the constants that are defined in $this->defineTypo3RequestTypes() are set,
263 * so most RequestHandlers can check if they can handle the request.
265 * @param \Psr\Http\Message\ServerRequestInterface|\Symfony\Component\Console\Input\InputInterface $request
266 * @return \TYPO3\CMS\Core\Http\RequestHandlerInterface|\TYPO3\CMS\Core\Console\RequestHandlerInterface
267 * @throws \TYPO3\CMS\Core\Exception
268 * @internal This is not a public API method, do not use in own extensions
270 protected function resolveRequestHandler($request)
272 $suitableRequestHandlers = array();
273 foreach ($this->availableRequestHandlers
as $requestHandlerClassName) {
274 /** @var \TYPO3\CMS\Core\Http\RequestHandlerInterface|\TYPO3\CMS\Core\Console\RequestHandlerInterface $requestHandler */
275 $requestHandler = GeneralUtility
::makeInstance($requestHandlerClassName, $this);
276 if ($requestHandler->canHandleRequest($request)) {
277 $priority = $requestHandler->getPriority();
278 if (isset($suitableRequestHandlers[$priority])) {
279 throw new \TYPO3\CMS\Core\
Exception('More than one request handler with the same priority can handle the request, but only one handler may be active at a time!', 1176471352);
281 $suitableRequestHandlers[$priority] = $requestHandler;
284 if (empty($suitableRequestHandlers)) {
285 throw new \TYPO3\CMS\Core\
Exception('No suitable request handler found.', 1225418233);
287 ksort($suitableRequestHandlers);
288 return array_pop($suitableRequestHandlers);
292 * Builds a Request instance from the current process, and then resolves the request
293 * through the request handlers depending on Frontend, Backend, CLI etc.
295 * @param \Psr\Http\Message\RequestInterface|\Symfony\Component\Console\Input\InputInterface $request
297 * @throws \TYPO3\CMS\Core\Exception
298 * @internal This is not a public API method, do not use in own extensions
300 public function handleRequest($request)
303 // Resolve request handler that were registered based on the Application
304 $requestHandler = $this->resolveRequestHandler($request);
306 // Execute the command which returns a Response object or NULL
307 $this->response
= $requestHandler->handleRequest($request);
312 * Outputs content if there is a proper Response object.
316 protected function sendResponse()
318 if ($this->response
instanceof \Psr\Http\Message\ResponseInterface
) {
319 if (!headers_sent()) {
320 foreach ($this->response
->getHeaders() as $name => $values) {
321 header($name . ': ' . implode(', ', $values));
323 // If the response code was not changed by legacy code (still is 200)
324 // then allow the PSR-7 response object to explicitly set it.
325 // Otherwise let legacy code take precedence.
326 // This code path can be deprecated once we expose the response object to third party code
327 if (http_response_code() === 200) {
328 header('HTTP/' . $this->response
->getProtocolVersion() . ' ' . $this->response
->getStatusCode() . ' ' . $this->response
->getReasonPhrase());
331 echo $this->response
->getBody()->__toString();
337 * Registers the instance of the specified object for an early boot stage.
338 * On finalizing the Object Manager initialization, all those instances will
339 * be transferred to the Object Manager's registry.
341 * @param string $objectName Object name, as later used by the Object Manager
342 * @param object $instance The instance to register
344 * @internal This is not a public API method, do not use in own extensions
346 public function setEarlyInstance($objectName, $instance)
348 $this->earlyInstances
[$objectName] = $instance;
352 * Returns an instance which was registered earlier through setEarlyInstance()
354 * @param string $objectName Object name of the registered instance
356 * @throws \TYPO3\CMS\Core\Exception
357 * @internal This is not a public API method, do not use in own extensions
359 public function getEarlyInstance($objectName)
361 if (!isset($this->earlyInstances
[$objectName])) {
362 throw new \TYPO3\CMS\Core\
Exception('Unknown early instance "' . $objectName . '"', 1365167380);
364 return $this->earlyInstances
[$objectName];
368 * Returns all registered early instances indexed by object name
371 * @internal This is not a public API method, do not use in own extensions
373 public function getEarlyInstances()
375 return $this->earlyInstances
;
379 * Includes LocalConfiguration.php and sets several
380 * global settings depending on configuration.
382 * @param bool $allowCaching Whether to allow caching - affects cache_core (autoloader)
383 * @param string $packageManagerClassName Define an alternative package manager implementation (usually for the installer)
385 * @internal This is not a public API method, do not use in own extensions
387 public function loadConfigurationAndInitialize($allowCaching = true, $packageManagerClassName = \TYPO3\CMS\Core\Package\PackageManager
::class)
389 $this->populateLocalConfiguration()
390 ->initializeErrorHandling();
391 if (!$allowCaching) {
392 $this->disableCoreCache();
394 $this->initializeCachingFramework()
395 ->initializePackageManagement($packageManagerClassName)
396 ->initializeRuntimeActivatedPackagesFromConfiguration()
397 ->defineDatabaseConstants()
398 ->defineUserAgentConstant()
399 ->registerExtDirectComponents()
400 ->setCacheHashOptions()
401 ->setDefaultTimezone()
402 ->initializeL10nLocales()
403 ->convertPageNotFoundHandlingToBoolean()
406 $this->ensureClassLoadingInformationExists();
412 * Initializes the package system and loads the package configuration and settings
413 * provided by the packages.
415 * @param string $packageManagerClassName Define an alternative package manager implementation (usually for the installer)
417 * @internal This is not a public API method, do not use in own extensions
419 public function initializePackageManagement($packageManagerClassName)
421 /** @var \TYPO3\CMS\Core\Package\PackageManager $packageManager */
422 $packageManager = new $packageManagerClassName();
423 $this->setEarlyInstance(\TYPO3\CMS\Core\Package\PackageManager
::class, $packageManager);
424 ExtensionManagementUtility
::setPackageManager($packageManager);
425 $packageManager->injectCoreCache($this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager
::class)->getCache('cache_core'));
426 $dependencyResolver = GeneralUtility
::makeInstance(\TYPO3\CMS\Core\Package\DependencyResolver
::class);
427 $dependencyResolver->injectDependencyOrderingService(GeneralUtility
::makeInstance(\TYPO3\CMS\Core\Service\DependencyOrderingService
::class));
428 $packageManager->injectDependencyResolver($dependencyResolver);
429 $packageManager->initialize($this);
430 GeneralUtility
::setSingletonInstance(\TYPO3\CMS\Core\Package\PackageManager
::class, $packageManager);
435 * Writes class loading information if not yet present
438 * @internal This is not a public API method, do not use in own extensions
440 public function ensureClassLoadingInformationExists()
442 if (!self
::$usesComposerClassLoading && !ClassLoadingInformation
::isClassLoadingInformationAvailable()) {
443 ClassLoadingInformation
::dumpClassLoadingInformation();
444 ClassLoadingInformation
::registerClassLoadingInformation();
450 * Activates a package during runtime. This is used in AdditionalConfiguration.php
451 * to enable extensions under conditions.
455 protected function initializeRuntimeActivatedPackagesFromConfiguration()
457 if (!empty($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages']) && is_array($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages'])) {
458 /** @var \TYPO3\CMS\Core\Package\PackageManager $packageManager */
459 $packageManager = $this->getEarlyInstance(\TYPO3\CMS\Core\Package\PackageManager
::class);
460 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages'] as $runtimeAddedPackageKey) {
461 $packageManager->activatePackageDuringRuntime($runtimeAddedPackageKey);
468 * Load ext_localconf of extensions
470 * @param bool $allowCaching
472 * @internal This is not a public API method, do not use in own extensions
474 public function loadTypo3LoadedExtAndExtLocalconf($allowCaching = true)
476 ExtensionManagementUtility
::loadExtLocalconf($allowCaching);
481 * We need an early instance of the configuration manager.
482 * Since makeInstance relies on the object configuration, we create it here with new instead.
485 * @internal This is not a public API method, do not use in own extensions
487 public function populateLocalConfiguration()
490 $configurationManager = $this->getEarlyInstance(\TYPO3\CMS\Core\Configuration\ConfigurationManager
::class);
491 } catch (\TYPO3\CMS\Core\Exception
$exception) {
492 $configurationManager = new \TYPO3\CMS\Core\Configuration\
ConfigurationManager();
493 $this->setEarlyInstance(\TYPO3\CMS\Core\Configuration\ConfigurationManager
::class, $configurationManager);
495 $configurationManager->exportConfiguration();
500 * Set cache_core to null backend, effectively disabling eg. the cache for ext_localconf and PackageManager etc.
502 * @return \TYPO3\CMS\Core\Core\Bootstrap
503 * @internal This is not a public API method, do not use in own extensions
505 public function disableCoreCache()
507 $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['cache_core']['backend']
508 = \TYPO3\CMS\Core\Cache\Backend\NullBackend
::class;
509 unset($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['cache_core']['options']);
514 * Define database constants
516 * @return \TYPO3\CMS\Core\Core\Bootstrap
518 protected function defineDatabaseConstants()
520 define('TYPO3_db', $GLOBALS['TYPO3_CONF_VARS']['DB']['database']);
521 define('TYPO3_db_username', $GLOBALS['TYPO3_CONF_VARS']['DB']['username']);
522 define('TYPO3_db_password', $GLOBALS['TYPO3_CONF_VARS']['DB']['password']);
523 define('TYPO3_db_host', $GLOBALS['TYPO3_CONF_VARS']['DB']['host']);
528 * Define user agent constant
530 * @return \TYPO3\CMS\Core\Core\Bootstrap
532 protected function defineUserAgentConstant()
534 define('TYPO3_user_agent', 'User-Agent: ' . $GLOBALS['TYPO3_CONF_VARS']['HTTP']['userAgent']);
539 * Register default ExtDirect components
543 protected function registerExtDirectComponents()
545 if (TYPO3_MODE
=== 'BE') {
546 ExtensionManagementUtility
::registerExtDirectComponent(
547 'TYPO3.Components.PageTree.DataProvider',
548 \TYPO3\CMS\Backend\Tree\Pagetree\ExtdirectTreeDataProvider
::class
550 ExtensionManagementUtility
::registerExtDirectComponent(
551 'TYPO3.Components.PageTree.Commands',
552 \TYPO3\CMS\Backend\Tree\Pagetree\ExtdirectTreeCommands
::class
554 ExtensionManagementUtility
::registerExtDirectComponent(
555 'TYPO3.Components.PageTree.ContextMenuDataProvider',
556 \TYPO3\CMS\Backend\ContextMenu\Pagetree\Extdirect\ContextMenuConfiguration
::class
558 ExtensionManagementUtility
::registerExtDirectComponent(
559 'TYPO3.ExtDirectStateProvider.ExtDirect',
560 \TYPO3\CMS\Backend\InterfaceState\ExtDirect\DataProvider
::class
567 * Initialize caching framework, and re-initializes it (e.g. in the install tool) by recreating the instances
568 * again despite the Singleton instance
571 * @internal This is not a public API method, do not use in own extensions
573 public function initializeCachingFramework()
575 $cacheManager = new \TYPO3\CMS\Core\Cache\
CacheManager();
576 $cacheManager->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
577 GeneralUtility
::setSingletonInstance(\TYPO3\CMS\Core\Cache\CacheManager
::class, $cacheManager);
579 $cacheFactory = new \TYPO3\CMS\Core\Cache\
CacheFactory('production', $cacheManager);
580 GeneralUtility
::setSingletonInstance(\TYPO3\CMS\Core\Cache\CacheFactory
::class, $cacheFactory);
582 $this->setEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager
::class, $cacheManager);
587 * Set cacheHash options
591 protected function setCacheHashOptions()
593 $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash'] = array(
594 'cachedParametersWhiteList' => GeneralUtility
::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashOnlyForParameters'], true),
595 'excludedParameters' => GeneralUtility
::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParameters'], true),
596 'requireCacheHashPresenceParameters' => GeneralUtility
::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashRequiredParameters'], true)
598 if (trim($GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParametersIfEmpty']) === '*') {
599 $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludeAllEmptyParameters'] = true;
601 $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludedParametersIfEmpty'] = GeneralUtility
::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParametersIfEmpty'], true);
607 * Set default timezone
611 protected function setDefaultTimezone()
613 $timeZone = $GLOBALS['TYPO3_CONF_VARS']['SYS']['phpTimeZone'];
614 if (empty($timeZone)) {
615 // Time zone from the server environment (TZ env or OS query)
616 $defaultTimeZone = @date_default_timezone_get
();
617 if ($defaultTimeZone !== '') {
618 $timeZone = $defaultTimeZone;
623 // Set default to avoid E_WARNINGs with PHP > 5.3
624 date_default_timezone_set($timeZone);
629 * Initialize the locales handled by TYPO3
633 protected function initializeL10nLocales()
635 \TYPO3\CMS\Core\Localization\Locales
::initialize();
640 * Convert type of "pageNotFound_handling" setting in case it was written as a
641 * string (e.g. if edited in Install Tool)
643 * @TODO : Remove, if the Install Tool handles such data types correctly
646 protected function convertPageNotFoundHandlingToBoolean()
648 if (!strcasecmp($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], 'TRUE')) {
649 $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] = true;
655 * Configure and set up exception and error handling
658 * @throws \RuntimeException
660 protected function initializeErrorHandling()
662 $productionExceptionHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['productionExceptionHandler'];
663 $debugExceptionHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['debugExceptionHandler'];
665 $errorHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandler'];
666 $errorHandlerErrors = $GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandlerErrors'];
667 $exceptionalErrors = $GLOBALS['TYPO3_CONF_VARS']['SYS']['exceptionalErrors'];
669 $displayErrorsSetting = (int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['displayErrors'];
670 switch ($displayErrorsSetting) {
672 $ipMatchesDevelopmentSystem = GeneralUtility
::cmpIP(GeneralUtility
::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']);
673 $exceptionHandlerClassName = $ipMatchesDevelopmentSystem ?
$debugExceptionHandlerClassName : $productionExceptionHandlerClassName;
674 $displayErrors = $ipMatchesDevelopmentSystem ?
1 : 0;
675 $exceptionalErrors = $ipMatchesDevelopmentSystem ?
$exceptionalErrors : 0;
678 $exceptionHandlerClassName = $productionExceptionHandlerClassName;
682 $exceptionHandlerClassName = $debugExceptionHandlerClassName;
686 // Throw exception if an invalid option is set.
687 throw new \
RuntimeException('The option $TYPO3_CONF_VARS[SYS][displayErrors] is not set to "-1", "0" or "1".');
689 @ini_set
('display_errors', $displayErrors);
691 if (!empty($errorHandlerClassName)) {
692 // Register an error handler for the given errorHandlerError
693 $errorHandler = GeneralUtility
::makeInstance($errorHandlerClassName, $errorHandlerErrors);
694 $errorHandler->setExceptionalErrors($exceptionalErrors);
695 if (is_callable(array($errorHandler, 'setDebugMode'))) {
696 $errorHandler->setDebugMode($displayErrors === 1);
699 if (!empty($exceptionHandlerClassName)) {
700 // Registering the exception handler is done in the constructor
701 GeneralUtility
::makeInstance($exceptionHandlerClassName);
707 * Set PHP memory limit depending on value of
708 * $GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit']
712 protected function setMemoryLimit()
714 if ((int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit'] > 16) {
715 @ini_set
('memory_limit', ((int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit'] . 'm'));
721 * Define TYPO3_REQUESTTYPE* constants that can be used for developers to see if any context has been hit
722 * also see setRequestType(). Is done at the very beginning so these parameters are always available.
726 protected function defineTypo3RequestTypes()
728 define('TYPO3_REQUESTTYPE_FE', 1);
729 define('TYPO3_REQUESTTYPE_BE', 2);
730 define('TYPO3_REQUESTTYPE_CLI', 4);
731 define('TYPO3_REQUESTTYPE_AJAX', 8);
732 define('TYPO3_REQUESTTYPE_INSTALL', 16);
736 * Defines the TYPO3_REQUESTTYPE constant so the environment knows which context the request is running.
738 * @throws \RuntimeException if the method was already called during a request
741 public function setRequestType($requestType)
743 if (defined('TYPO3_REQUESTTYPE')) {
744 throw new \
RuntimeException('TYPO3_REQUESTTYPE has already been set, cannot be called multiple times', 1450561878);
746 define('TYPO3_REQUESTTYPE', $requestType);
751 * Extensions may register new caches, so we set the
752 * global cache array to the manager again at this point
755 * @internal This is not a public API method, do not use in own extensions
757 public function setFinalCachingFrameworkCacheConfiguration()
759 $this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager
::class)->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
764 * Define logging and exception constants
767 * @internal This is not a public API method, do not use in own extensions
769 public function defineLoggingAndExceptionConstants()
771 define('TYPO3_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_DLOG']);
772 define('TYPO3_ERROR_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_errorDLOG']);
773 define('TYPO3_EXCEPTION_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_exceptionDLOG']);
778 * Unsetting reserved global variables:
779 * Those are set in "ext:core/ext_tables.php" file:
782 * @internal This is not a public API method, do not use in own extensions
784 public function unsetReservedGlobalVariables()
786 unset($GLOBALS['PAGES_TYPES']);
787 unset($GLOBALS['TCA']);
788 unset($GLOBALS['TBE_MODULES']);
789 unset($GLOBALS['TBE_STYLES']);
790 unset($GLOBALS['BE_USER']);
791 // Those set otherwise:
792 unset($GLOBALS['TBE_MODULES_EXT']);
793 unset($GLOBALS['TCA_DESCR']);
794 unset($GLOBALS['LOCAL_LANG']);
799 * Initialize database connection in $GLOBALS and connect if requested
801 * @return \TYPO3\CMS\Core\Core\Bootstrap
802 * @internal This is not a public API method, do not use in own extensions
804 public function initializeTypo3DbGlobal()
806 /** @var $databaseConnection \TYPO3\CMS\Core\Database\DatabaseConnection */
807 $databaseConnection = GeneralUtility
::makeInstance(\TYPO3\CMS\Core\Database\DatabaseConnection
::class);
808 $databaseConnection->setDatabaseName(TYPO3_db
);
809 $databaseConnection->setDatabaseUsername(TYPO3_db_username
);
810 $databaseConnection->setDatabasePassword(TYPO3_db_password
);
812 $databaseHost = TYPO3_db_host
;
813 if (isset($GLOBALS['TYPO3_CONF_VARS']['DB']['port'])) {
814 $databaseConnection->setDatabasePort($GLOBALS['TYPO3_CONF_VARS']['DB']['port']);
815 } elseif (strpos($databaseHost, ':') > 0) {
816 // @TODO: Find a way to handle this case in the install tool and drop this
817 list($databaseHost, $databasePort) = explode(':', $databaseHost);
818 $databaseConnection->setDatabasePort($databasePort);
820 if (isset($GLOBALS['TYPO3_CONF_VARS']['DB']['socket'])) {
821 $databaseConnection->setDatabaseSocket($GLOBALS['TYPO3_CONF_VARS']['DB']['socket']);
823 $databaseConnection->setDatabaseHost($databaseHost);
825 $databaseConnection->debugOutput
= $GLOBALS['TYPO3_CONF_VARS']['SYS']['sqlDebug'];
828 isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect'])
829 && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect']
831 $databaseConnection->setPersistentDatabaseConnection(true);
834 $isDatabaseHostLocalHost = $databaseHost === 'localhost' ||
$databaseHost === '127.0.0.1' ||
$databaseHost === '::1';
836 isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress'])
837 && $GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress']
838 && !$isDatabaseHostLocalHost
840 $databaseConnection->setConnectionCompression(true);
843 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit'])) {
844 $commandsAfterConnect = GeneralUtility
::trimExplode(
846 str_replace('\' . LF . \'', LF
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit']),
849 $databaseConnection->setInitializeCommandsAfterConnect($commandsAfterConnect);
852 $GLOBALS['TYPO3_DB'] = $databaseConnection;
853 // $GLOBALS['TYPO3_DB'] needs to be defined first in order to work for DBAL
854 $GLOBALS['TYPO3_DB']->initialize();
860 * Check adminOnly configuration variable and redirects
861 * to an URL in file typo3conf/LOCK_BACKEND or exit the script
863 * @throws \RuntimeException
864 * @param bool $forceProceeding if this option is set, the bootstrap will proceed even if the user is logged in (usually only needed for special AJAX cases, see AjaxRequestHandler)
866 * @internal This is not a public API method, do not use in own extensions
868 public function checkLockedBackendAndRedirectOrDie($forceProceeding = false)
870 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'] < 0) {
871 throw new \
RuntimeException('TYPO3 Backend locked: Backend and Install Tool are locked for maintenance. [BE][adminOnly] is set to "' . (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'] . '".', 1294586847);
873 if (@is_file
(PATH_typo3conf
. 'LOCK_BACKEND') && $forceProceeding === false) {
874 $fileContent = GeneralUtility
::getUrl(PATH_typo3conf
. 'LOCK_BACKEND');
876 header('Location: ' . $fileContent);
878 throw new \
RuntimeException('TYPO3 Backend locked: Browser backend is locked for maintenance. Remove lock by removing the file "typo3conf/LOCK_BACKEND" or use CLI-scripts.', 1294586848);
886 * Compare client IP with IPmaskList and exit the script run
887 * if the client is not allowed to access the backend
890 * @internal This is not a public API method, do not use in own extensions
891 * @throws \RuntimeException
893 public function checkBackendIpOrDie()
895 if (trim($GLOBALS['TYPO3_CONF_VARS']['BE']['IPmaskList'])) {
896 if (!GeneralUtility
::cmpIP(GeneralUtility
::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['BE']['IPmaskList'])) {
897 throw new \
RuntimeException('TYPO3 Backend access denied: The IP address of your client does not match the list of allowed IP addresses.', 1389265900);
904 * Check lockSSL configuration variable and redirect
905 * to https version of the backend if needed
908 * @internal This is not a public API method, do not use in own extensions
909 * @throws \RuntimeException
911 public function checkSslBackendAndRedirectIfNeeded()
913 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL']) {
914 if (!GeneralUtility
::getIndpEnv('TYPO3_SSL')) {
915 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL'] === 2) {
916 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort']) {
917 $sslPortSuffix = ':' . (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort'];
921 list(, $url) = explode('://', GeneralUtility
::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir
, 2);
922 list($server, $address) = explode('/', $url, 2);
923 header('Location: https://' . $server . $sslPortSuffix . '/' . $address);
926 throw new \
RuntimeException('TYPO3 Backend not accessed via SSL: TYPO3 Backend is configured to only be accessible through SSL. Change the URL in your browser and try again.', 1389265726);
934 * Load TCA for frontend
936 * This method is *only* executed in frontend scope. The idea is to execute the
937 * whole TCA and ext_tables (which manipulate TCA) on first frontend access,
938 * and then cache the full TCA on disk to be used for the next run again.
940 * This way, ext_tables.php ist not executed every time, but $GLOBALS['TCA']
941 * is still always there.
944 * @internal This is not a public API method, do not use in own extensions
946 public function loadCachedTca()
948 $cacheIdentifier = 'tca_fe_' . sha1((TYPO3_version
. PATH_site
. 'tca_fe'));
949 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
950 $codeCache = $this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager
::class)->getCache('cache_core');
951 if ($codeCache->has($cacheIdentifier)) {
952 // substr is necessary, because the php frontend wraps php code around the cache value
953 $GLOBALS['TCA'] = unserialize(substr($codeCache->get($cacheIdentifier), 6, -2));
955 $this->loadExtensionTables();
956 $codeCache->set($cacheIdentifier, serialize($GLOBALS['TCA']));
962 * Load ext_tables and friends.
964 * This will mainly set up $TCA and several other global arrays
965 * through API's like extMgm.
966 * Executes ext_tables.php files of loaded extensions or the
967 * according cache file if exists.
969 * @param bool $allowCaching True, if reading compiled ext_tables file from cache is allowed
971 * @internal This is not a public API method, do not use in own extensions
973 public function loadExtensionTables($allowCaching = true)
975 ExtensionManagementUtility
::loadBaseTca($allowCaching);
976 ExtensionManagementUtility
::loadExtTables($allowCaching);
977 $this->runExtTablesPostProcessingHooks();
982 * Check for registered ext tables hooks and run them
984 * @throws \UnexpectedValueException
987 protected function runExtTablesPostProcessingHooks()
989 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['extTablesInclusion-PostProcessing'])) {
990 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['extTablesInclusion-PostProcessing'] as $classReference) {
991 /** @var $hookObject \TYPO3\CMS\Core\Database\TableConfigurationPostProcessingHookInterface */
992 $hookObject = GeneralUtility
::getUserObj($classReference);
993 if (!$hookObject instanceof \TYPO3\CMS\Core\Database\TableConfigurationPostProcessingHookInterface
) {
994 throw new \
UnexpectedValueException(
995 '$hookObject "' . $classReference . '" must implement interface TYPO3\\CMS\\Core\\Database\\TableConfigurationPostProcessingHookInterface',
999 $hookObject->processData();
1005 * Initialize the Routing for the TYPO3 Backend
1006 * Loads all routes registered inside all packages and stores them inside the Router
1009 * @internal This is not a public API method, do not use in own extensions
1011 public function initializeBackendRouter()
1013 $packageManager = $this->getEarlyInstance(\TYPO3\CMS\Core\Package\PackageManager
::class);
1015 // See if the Routes.php from all active packages have been built together already
1016 $cacheIdentifier = 'BackendRoutesFromPackages_' . sha1((TYPO3_version
. PATH_site
. 'BackendRoutesFromPackages'));
1018 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
1019 $codeCache = $this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager
::class)->getCache('cache_core');
1020 $routesFromPackages = array();
1021 if ($codeCache->has($cacheIdentifier)) {
1022 // substr is necessary, because the php frontend wraps php code around the cache value
1023 $routesFromPackages = unserialize(substr($codeCache->get($cacheIdentifier), 6, -2));
1025 // Loop over all packages and check for a Configuration/Backend/Routes.php file
1026 $packages = $packageManager->getActivePackages();
1027 foreach ($packages as $package) {
1028 $routesFileNameForPackage = $package->getPackagePath() . 'Configuration/Backend/Routes.php';
1029 if (file_exists($routesFileNameForPackage)) {
1030 $definedRoutesInPackage = require $routesFileNameForPackage;
1031 if (is_array($definedRoutesInPackage)) {
1032 $routesFromPackages +
= $definedRoutesInPackage;
1035 $routesFileNameForPackage = $package->getPackagePath() . 'Configuration/Backend/AjaxRoutes.php';
1036 if (file_exists($routesFileNameForPackage)) {
1037 $definedRoutesInPackage = require $routesFileNameForPackage;
1038 if (is_array($definedRoutesInPackage)) {
1039 foreach ($definedRoutesInPackage as $routeIdentifier => $routeOptions) {
1040 // prefix the route with "ajax_" as "namespace"
1041 $routeOptions['path'] = '/ajax' . $routeOptions['path'];
1042 $routesFromPackages['ajax_' . $routeIdentifier] = $routeOptions;
1043 $routesFromPackages['ajax_' . $routeIdentifier]['ajax'] = true;
1048 // Store the data from all packages in the cache
1049 $codeCache->set($cacheIdentifier, serialize($routesFromPackages));
1052 // Build Route objects from the data
1053 $router = GeneralUtility
::makeInstance(\TYPO3\CMS\Backend\Routing\Router
::class);
1054 foreach ($routesFromPackages as $name => $options) {
1055 $path = $options['path'];
1056 unset($options['path']);
1057 $route = GeneralUtility
::makeInstance(\TYPO3\CMS\Backend\Routing\Route
::class, $path, $options);
1058 $router->addRoute($name, $route);
1064 * Initialize backend user object in globals
1067 * @internal This is not a public API method, do not use in own extensions
1069 public function initializeBackendUser()
1071 /** @var $backendUser \TYPO3\CMS\Core\Authentication\BackendUserAuthentication */
1072 $backendUser = GeneralUtility
::makeInstance(\TYPO3\CMS\Core\Authentication\BackendUserAuthentication
::class);
1073 $backendUser->warningEmail
= $GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr'];
1074 $backendUser->lockIP
= $GLOBALS['TYPO3_CONF_VARS']['BE']['lockIP'];
1075 $backendUser->auth_timeout_field
= (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['sessionTimeout'];
1076 if (TYPO3_REQUESTTYPE
& TYPO3_REQUESTTYPE_CLI
) {
1077 $backendUser->dontSetCookie
= true;
1079 // The global must be available very early, because methods below
1080 // might trigger code which relies on it. See: #45625
1081 $GLOBALS['BE_USER'] = $backendUser;
1082 $backendUser->start();
1087 * Initializes and ensures authenticated access
1089 * @internal This is not a public API method, do not use in own extensions
1090 * @param bool $proceedIfNoUserIsLoggedIn if set to TRUE, no forced redirect to the login page will be done
1091 * @return \TYPO3\CMS\Core\Core\Bootstrap
1093 public function initializeBackendAuthentication($proceedIfNoUserIsLoggedIn = false)
1095 $GLOBALS['BE_USER']->backendCheckLogin($proceedIfNoUserIsLoggedIn);
1100 * Initialize language object
1103 * @internal This is not a public API method, do not use in own extensions
1105 public function initializeLanguageObject()
1107 /** @var $GLOBALS['LANG'] \TYPO3\CMS\Lang\LanguageService */
1108 $GLOBALS['LANG'] = GeneralUtility
::makeInstance(\TYPO3\CMS\Lang\LanguageService
::class);
1109 $GLOBALS['LANG']->init($GLOBALS['BE_USER']->uc
['lang']);
1114 * Throw away all output that may have happened during bootstrapping by weird extensions
1117 * @internal This is not a public API method, do not use in own extensions
1119 public function endOutputBufferingAndCleanPreviousOutput()
1126 * Initialize output compression if configured
1129 * @internal This is not a public API method, do not use in own extensions
1131 public function initializeOutputCompression()
1133 if (extension_loaded('zlib') && $GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel']) {
1134 if (MathUtility
::canBeInterpretedAsInteger($GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel'])) {
1135 @ini_set
('zlib.output_compression_level', $GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel']);
1137 ob_start('ob_gzhandler');
1143 * Send HTTP headers if configured
1146 * @internal This is not a public API method, do not use in own extensions
1148 public function sendHttpHeaders()
1150 if (!empty($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers']) && is_array($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers'])) {
1151 foreach ($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers'] as $header) {
1159 * Things that should be performed to shut down the framework.
1160 * This method is called in all important scripts for a clean
1161 * shut down of the system.
1164 * @internal This is not a public API method, do not use in own extensions
1166 public function shutdown()
1168 $this->sendResponse();
1173 * Provides an instance of "template" for backend-modules to
1177 * @internal This is not a public API method, do not use in own extensions
1179 public function initializeBackendTemplate()
1181 $GLOBALS['TBE_TEMPLATE'] = GeneralUtility
::makeInstance(\TYPO3\CMS\Backend\Template\DocumentTemplate
::class);