[TASK] Bootstrap: Load TCA configuration on every request
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Core / Bootstrap.php
1 <?php
2 namespace TYPO3\CMS\Core\Core;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
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.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
18 use TYPO3\CMS\Core\Utility\GeneralUtility;
19 use TYPO3\CMS\Core\Utility\MathUtility;
20
21 /**
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 paths and so on.
25 *
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!
31 */
32 class Bootstrap
33 {
34 /**
35 * @var \TYPO3\CMS\Core\Core\Bootstrap
36 */
37 protected static $instance = null;
38
39 /**
40 * Unique Request ID
41 *
42 * @var string
43 */
44 protected $requestId;
45
46 /**
47 * The application context
48 *
49 * @var \TYPO3\CMS\Core\Core\ApplicationContext
50 */
51 protected $applicationContext;
52
53 /**
54 * @var array List of early instances
55 */
56 protected $earlyInstances = [];
57
58 /**
59 * @var string Path to install tool
60 */
61 protected $installToolPath;
62
63 /**
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[]
66 */
67 protected $availableRequestHandlers = [];
68
69 /**
70 * The Response object when using Request/Response logic
71 * @var \Psr\Http\Message\ResponseInterface
72 * @see shutdown()
73 */
74 protected $response;
75
76 /**
77 * @var bool
78 */
79 protected static $usesComposerClassLoading = false;
80
81 /**
82 * Disable direct creation of this object.
83 * Set unique requestId and the application context
84 *
85 * @var string Application context
86 */
87 protected function __construct($applicationContext)
88 {
89 $this->requestId = substr(md5(uniqid('', true)), 0, 13);
90 $this->applicationContext = new ApplicationContext($applicationContext);
91 }
92
93 /**
94 * @return bool
95 */
96 public static function usesComposerClassLoading()
97 {
98 return self::$usesComposerClassLoading;
99 }
100
101 /**
102 * Disable direct cloning of this object.
103 */
104 protected function __clone()
105 {
106 }
107
108 /**
109 * Return 'this' as singleton
110 *
111 * @return Bootstrap
112 * @internal This is not a public API method, do not use in own extensions
113 */
114 public static function getInstance()
115 {
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();
120 }
121 return static::$instance;
122 }
123
124 /**
125 * Gets the request's unique ID
126 *
127 * @return string Unique request ID
128 * @internal This is not a public API method, do not use in own extensions
129 */
130 public function getRequestId()
131 {
132 return $this->requestId;
133 }
134
135 /**
136 * Returns the application context this bootstrap was started in.
137 *
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
141 */
142 public function getApplicationContext()
143 {
144 return $this->applicationContext;
145 }
146
147 /**
148 * Prevent any unwanted output that may corrupt AJAX/compression.
149 * This does not interfere with "die()" or "echo"+"exit()" messages!
150 *
151 * @return Bootstrap
152 * @internal This is not a public API method, do not use in own extensions
153 */
154 public function startOutputBuffering()
155 {
156 ob_start();
157 return $this;
158 }
159
160 /**
161 * Main entry point called at every request usually from Global scope. Checks if everything is correct,
162 * and loads the Configuration.
163 *
164 * Make sure that the baseSetup() is called before and the class loader is present
165 *
166 * @return Bootstrap
167 */
168 public function configure()
169 {
170 $this->startOutputBuffering()
171 ->loadConfigurationAndInitialize()
172 ->loadTypo3LoadedExtAndExtLocalconf(true)
173 ->setFinalCachingFrameworkCacheConfiguration()
174 ->defineLoggingAndExceptionConstants()
175 ->unsetReservedGlobalVariables()
176 ->loadBaseTca();
177
178 return $this;
179 }
180
181 /**
182 * Run the base setup that checks server environment, determines paths,
183 * populates base files and sets common configuration.
184 *
185 * Script execution will be aborted if something fails here.
186 *
187 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
188 * @return Bootstrap
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
191 */
192 public function baseSetup($entryPointLevel = 0)
193 {
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);
196 }
197 SystemEnvironmentBuilder::run($entryPointLevel);
198 if (!self::$usesComposerClassLoading && ClassLoadingInformation::isClassLoadingInformationAvailable()) {
199 ClassLoadingInformation::registerClassLoadingInformation();
200 }
201 GeneralUtility::presetApplicationContext($this->applicationContext);
202 return $this;
203 }
204
205 /**
206 * Sets the class loader to the bootstrap
207 *
208 * @param \Composer\Autoload\ClassLoader $classLoader an instance of the class loader
209 * @return Bootstrap
210 * @internal This is not a public API method, do not use in own extensions
211 */
212 public function initializeClassLoader($classLoader)
213 {
214 $this->setEarlyInstance(\Composer\Autoload\ClassLoader::class, $classLoader);
215 if (defined('TYPO3_COMPOSER_MODE') && TYPO3_COMPOSER_MODE) {
216 self::$usesComposerClassLoading = true;
217 }
218 return $this;
219 }
220
221 /**
222 * checks if LocalConfiguration.php or PackageStates.php is missing,
223 * used to see if a redirect to the install tool is needed
224 *
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
227 */
228 public function checkIfEssentialConfigurationExists()
229 {
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');
233 }
234
235 /**
236 * Redirect to install tool if LocalConfiguration.php is missing.
237 *
238 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
239 * @internal This is not a public API method, do not use in own extensions
240 */
241 public function redirectToInstallTool($entryPointLevel = 0)
242 {
243 $path = TYPO3_mainDir . 'sysext/install/Start/Install.php';
244 if ($entryPointLevel > 0) {
245 $path = str_repeat('../', $entryPointLevel) . $path;
246 }
247 header('Location: ' . $path);
248 die;
249 }
250
251 /**
252 * Adds available request handlers usually done via an application from the outside.
253 *
254 * @param string $requestHandler class which implements the request handler interface
255 * @return Bootstrap
256 * @internal This is not a public API method, do not use in own extensions
257 */
258 public function registerRequestHandlerImplementation($requestHandler)
259 {
260 $this->availableRequestHandlers[] = $requestHandler;
261 return $this;
262 }
263
264 /**
265 * Fetches the request handler that suits the best based on the priority and the interface
266 * Be sure to always have the constants that are defined in $this->defineTypo3RequestTypes() are set,
267 * so most RequestHandlers can check if they can handle the request.
268 *
269 * @param \Psr\Http\Message\ServerRequestInterface|\Symfony\Component\Console\Input\InputInterface $request
270 * @return \TYPO3\CMS\Core\Http\RequestHandlerInterface|\TYPO3\CMS\Core\Console\RequestHandlerInterface
271 * @throws \TYPO3\CMS\Core\Exception
272 * @internal This is not a public API method, do not use in own extensions
273 */
274 protected function resolveRequestHandler($request)
275 {
276 $suitableRequestHandlers = [];
277 foreach ($this->availableRequestHandlers as $requestHandlerClassName) {
278 /** @var \TYPO3\CMS\Core\Http\RequestHandlerInterface|\TYPO3\CMS\Core\Console\RequestHandlerInterface $requestHandler */
279 $requestHandler = GeneralUtility::makeInstance($requestHandlerClassName, $this);
280 if ($requestHandler->canHandleRequest($request)) {
281 $priority = $requestHandler->getPriority();
282 if (isset($suitableRequestHandlers[$priority])) {
283 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);
284 }
285 $suitableRequestHandlers[$priority] = $requestHandler;
286 }
287 }
288 if (empty($suitableRequestHandlers)) {
289 throw new \TYPO3\CMS\Core\Exception('No suitable request handler found.', 1225418233);
290 }
291 ksort($suitableRequestHandlers);
292 return array_pop($suitableRequestHandlers);
293 }
294
295 /**
296 * Builds a Request instance from the current process, and then resolves the request
297 * through the request handlers depending on Frontend, Backend, CLI etc.
298 *
299 * @param \Psr\Http\Message\RequestInterface|\Symfony\Component\Console\Input\InputInterface $request
300 * @return Bootstrap
301 * @throws \TYPO3\CMS\Core\Exception
302 * @internal This is not a public API method, do not use in own extensions
303 */
304 public function handleRequest($request)
305 {
306 // Resolve request handler that were registered based on the Application
307 $requestHandler = $this->resolveRequestHandler($request);
308
309 // Execute the command which returns a Response object or NULL
310 $this->response = $requestHandler->handleRequest($request);
311 return $this;
312 }
313
314 /**
315 * Outputs content if there is a proper Response object.
316 *
317 * @return Bootstrap
318 */
319 protected function sendResponse()
320 {
321 if ($this->response instanceof \Psr\Http\Message\ResponseInterface) {
322 if (!headers_sent()) {
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());
329 }
330
331 foreach ($this->response->getHeaders() as $name => $values) {
332 header($name . ': ' . implode(', ', $values));
333 }
334 }
335 echo $this->response->getBody()->__toString();
336 }
337 return $this;
338 }
339
340 /**
341 * Registers the instance of the specified object for an early boot stage.
342 * On finalizing the Object Manager initialization, all those instances will
343 * be transferred to the Object Manager's registry.
344 *
345 * @param string $objectName Object name, as later used by the Object Manager
346 * @param object $instance The instance to register
347 * @internal This is not a public API method, do not use in own extensions
348 */
349 public function setEarlyInstance($objectName, $instance)
350 {
351 $this->earlyInstances[$objectName] = $instance;
352 }
353
354 /**
355 * Returns an instance which was registered earlier through setEarlyInstance()
356 *
357 * @param string $objectName Object name of the registered instance
358 * @return object
359 * @throws \TYPO3\CMS\Core\Exception
360 * @internal This is not a public API method, do not use in own extensions
361 */
362 public function getEarlyInstance($objectName)
363 {
364 if (!isset($this->earlyInstances[$objectName])) {
365 throw new \TYPO3\CMS\Core\Exception('Unknown early instance "' . $objectName . '"', 1365167380);
366 }
367 return $this->earlyInstances[$objectName];
368 }
369
370 /**
371 * Returns all registered early instances indexed by object name
372 *
373 * @return array
374 * @internal This is not a public API method, do not use in own extensions
375 */
376 public function getEarlyInstances()
377 {
378 return $this->earlyInstances;
379 }
380
381 /**
382 * Includes LocalConfiguration.php and sets several
383 * global settings depending on configuration.
384 *
385 * @param bool $allowCaching Whether to allow caching - affects cache_core (autoloader)
386 * @param string $packageManagerClassName Define an alternative package manager implementation (usually for the installer)
387 * @return Bootstrap
388 * @internal This is not a public API method, do not use in own extensions
389 */
390 public function loadConfigurationAndInitialize($allowCaching = true, $packageManagerClassName = \TYPO3\CMS\Core\Package\PackageManager::class)
391 {
392 $this->populateLocalConfiguration()
393 ->initializeErrorHandling();
394 if (!$allowCaching) {
395 $this->disableCoreCache();
396 }
397 $this->initializeCachingFramework()
398 ->initializePackageManagement($packageManagerClassName)
399 ->initializeRuntimeActivatedPackagesFromConfiguration()
400 ->defineUserAgentConstant()
401 ->setCacheHashOptions()
402 ->setDefaultTimezone()
403 ->initializeL10nLocales()
404 ->setMemoryLimit();
405 if ($allowCaching) {
406 $this->ensureClassLoadingInformationExists();
407 }
408 return $this;
409 }
410
411 /**
412 * Initializes the package system and loads the package configuration and settings
413 * provided by the packages.
414 *
415 * @param string $packageManagerClassName Define an alternative package manager implementation (usually for the installer)
416 * @return Bootstrap
417 * @internal This is not a public API method, do not use in own extensions
418 */
419 public function initializePackageManagement($packageManagerClassName)
420 {
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();
430 GeneralUtility::setSingletonInstance(\TYPO3\CMS\Core\Package\PackageManager::class, $packageManager);
431 return $this;
432 }
433
434 /**
435 * Writes class loading information if not yet present
436 *
437 * @return Bootstrap
438 * @internal This is not a public API method, do not use in own extensions
439 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9. Use the Install Tool to dump autoload information.
440 */
441 public function ensureClassLoadingInformationExists()
442 {
443 if (!self::$usesComposerClassLoading && !ClassLoadingInformation::isClassLoadingInformationAvailable()) {
444 GeneralUtility::logDeprecatedFunction();
445 ClassLoadingInformation::dumpClassLoadingInformation();
446 ClassLoadingInformation::registerClassLoadingInformation();
447 }
448 return $this;
449 }
450
451 /**
452 * Activates a package during runtime. This is used in AdditionalConfiguration.php
453 * to enable extensions under conditions.
454 *
455 * @return Bootstrap
456 */
457 protected function initializeRuntimeActivatedPackagesFromConfiguration()
458 {
459 if (!empty($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages']) && is_array($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages'])) {
460 /** @var \TYPO3\CMS\Core\Package\PackageManager $packageManager */
461 $packageManager = $this->getEarlyInstance(\TYPO3\CMS\Core\Package\PackageManager::class);
462 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages'] as $runtimeAddedPackageKey) {
463 $packageManager->activatePackageDuringRuntime($runtimeAddedPackageKey);
464 }
465 }
466 return $this;
467 }
468
469 /**
470 * Load ext_localconf of extensions
471 *
472 * @param bool $allowCaching
473 * @return Bootstrap
474 * @internal This is not a public API method, do not use in own extensions
475 */
476 public function loadTypo3LoadedExtAndExtLocalconf($allowCaching = true)
477 {
478 ExtensionManagementUtility::loadExtLocalconf($allowCaching);
479 return $this;
480 }
481
482 /**
483 * We need an early instance of the configuration manager.
484 * Since makeInstance relies on the object configuration, we create it here with new instead.
485 *
486 * @return Bootstrap
487 * @internal This is not a public API method, do not use in own extensions
488 */
489 public function populateLocalConfiguration()
490 {
491 try {
492 $configurationManager = $this->getEarlyInstance(\TYPO3\CMS\Core\Configuration\ConfigurationManager::class);
493 } catch (\TYPO3\CMS\Core\Exception $exception) {
494 $configurationManager = new \TYPO3\CMS\Core\Configuration\ConfigurationManager();
495 $this->setEarlyInstance(\TYPO3\CMS\Core\Configuration\ConfigurationManager::class, $configurationManager);
496 }
497 $configurationManager->exportConfiguration();
498 return $this;
499 }
500
501 /**
502 * Set cache_core to null backend, effectively disabling eg. the cache for ext_localconf and PackageManager etc.
503 *
504 * @return \TYPO3\CMS\Core\Core\Bootstrap
505 * @internal This is not a public API method, do not use in own extensions
506 */
507 public function disableCoreCache()
508 {
509 $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['cache_core']['backend']
510 = \TYPO3\CMS\Core\Cache\Backend\NullBackend::class;
511 unset($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['cache_core']['options']);
512 return $this;
513 }
514
515 /**
516 * Define user agent constant
517 *
518 * @return \TYPO3\CMS\Core\Core\Bootstrap
519 */
520 protected function defineUserAgentConstant()
521 {
522 define('TYPO3_user_agent', 'User-Agent: ' . $GLOBALS['TYPO3_CONF_VARS']['HTTP']['headers']['User-Agent']);
523 return $this;
524 }
525
526 /**
527 * Initialize caching framework, and re-initializes it (e.g. in the install tool) by recreating the instances
528 * again despite the Singleton instance
529 *
530 * @return Bootstrap
531 * @internal This is not a public API method, do not use in own extensions
532 */
533 public function initializeCachingFramework()
534 {
535 $cacheManager = new \TYPO3\CMS\Core\Cache\CacheManager();
536 $cacheManager->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
537 GeneralUtility::setSingletonInstance(\TYPO3\CMS\Core\Cache\CacheManager::class, $cacheManager);
538 $this->setEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class, $cacheManager);
539 return $this;
540 }
541
542 /**
543 * Set cacheHash options
544 *
545 * @return Bootstrap
546 */
547 protected function setCacheHashOptions()
548 {
549 $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash'] = [
550 'cachedParametersWhiteList' => GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashOnlyForParameters'], true),
551 'excludedParameters' => GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParameters'], true),
552 'requireCacheHashPresenceParameters' => GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashRequiredParameters'], true),
553 ];
554 if (trim($GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParametersIfEmpty']) === '*') {
555 $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludeAllEmptyParameters'] = true;
556 } else {
557 $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludedParametersIfEmpty'] = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParametersIfEmpty'], true);
558 }
559 return $this;
560 }
561
562 /**
563 * Set default timezone
564 *
565 * @return Bootstrap
566 */
567 protected function setDefaultTimezone()
568 {
569 $timeZone = $GLOBALS['TYPO3_CONF_VARS']['SYS']['phpTimeZone'];
570 if (empty($timeZone)) {
571 // Time zone from the server environment (TZ env or OS query)
572 $defaultTimeZone = @date_default_timezone_get();
573 if ($defaultTimeZone !== '') {
574 $timeZone = $defaultTimeZone;
575 } else {
576 $timeZone = 'UTC';
577 }
578 }
579 // Set default to avoid E_WARNINGs with PHP > 5.3
580 date_default_timezone_set($timeZone);
581 return $this;
582 }
583
584 /**
585 * Initialize the locales handled by TYPO3
586 *
587 * @return Bootstrap
588 */
589 protected function initializeL10nLocales()
590 {
591 \TYPO3\CMS\Core\Localization\Locales::initialize();
592 return $this;
593 }
594
595 /**
596 * Configure and set up exception and error handling
597 *
598 * @return Bootstrap
599 * @throws \RuntimeException
600 */
601 protected function initializeErrorHandling()
602 {
603 $productionExceptionHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['productionExceptionHandler'];
604 $debugExceptionHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['debugExceptionHandler'];
605
606 $errorHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandler'];
607 $errorHandlerErrors = $GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandlerErrors'];
608 $exceptionalErrors = $GLOBALS['TYPO3_CONF_VARS']['SYS']['exceptionalErrors'];
609
610 $displayErrorsSetting = (int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['displayErrors'];
611 switch ($displayErrorsSetting) {
612 case -1:
613 $ipMatchesDevelopmentSystem = GeneralUtility::cmpIP(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']);
614 $exceptionHandlerClassName = $ipMatchesDevelopmentSystem ? $debugExceptionHandlerClassName : $productionExceptionHandlerClassName;
615 $displayErrors = $ipMatchesDevelopmentSystem ? 1 : 0;
616 $exceptionalErrors = $ipMatchesDevelopmentSystem ? $exceptionalErrors : 0;
617 break;
618 case 0:
619 $exceptionHandlerClassName = $productionExceptionHandlerClassName;
620 $displayErrors = 0;
621 break;
622 case 1:
623 $exceptionHandlerClassName = $debugExceptionHandlerClassName;
624 $displayErrors = 1;
625 break;
626 default:
627 // Throw exception if an invalid option is set.
628 throw new \RuntimeException(
629 'The option $TYPO3_CONF_VARS[SYS][displayErrors] is not set to "-1", "0" or "1".',
630 1476046290
631 );
632 }
633 @ini_set('display_errors', $displayErrors);
634
635 if (!empty($errorHandlerClassName)) {
636 // Register an error handler for the given errorHandlerError
637 $errorHandler = GeneralUtility::makeInstance($errorHandlerClassName, $errorHandlerErrors);
638 $errorHandler->setExceptionalErrors($exceptionalErrors);
639 if (is_callable([$errorHandler, 'setDebugMode'])) {
640 $errorHandler->setDebugMode($displayErrors === 1);
641 }
642 }
643 if (!empty($exceptionHandlerClassName)) {
644 // Registering the exception handler is done in the constructor
645 GeneralUtility::makeInstance($exceptionHandlerClassName);
646 }
647 return $this;
648 }
649
650 /**
651 * Set PHP memory limit depending on value of
652 * $GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit']
653 *
654 * @return Bootstrap
655 */
656 protected function setMemoryLimit()
657 {
658 if ((int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit'] > 16) {
659 @ini_set('memory_limit', ((int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit'] . 'm'));
660 }
661 return $this;
662 }
663
664 /**
665 * Define TYPO3_REQUESTTYPE* constants that can be used for developers to see if any context has been hit
666 * also see setRequestType(). Is done at the very beginning so these parameters are always available.
667 *
668 * @return Bootstrap
669 */
670 protected function defineTypo3RequestTypes()
671 {
672 define('TYPO3_REQUESTTYPE_FE', 1);
673 define('TYPO3_REQUESTTYPE_BE', 2);
674 define('TYPO3_REQUESTTYPE_CLI', 4);
675 define('TYPO3_REQUESTTYPE_AJAX', 8);
676 define('TYPO3_REQUESTTYPE_INSTALL', 16);
677 }
678
679 /**
680 * Defines the TYPO3_REQUESTTYPE constant so the environment knows which context the request is running.
681 *
682 * @throws \RuntimeException if the method was already called during a request
683 * @return Bootstrap
684 */
685 public function setRequestType($requestType)
686 {
687 if (defined('TYPO3_REQUESTTYPE')) {
688 throw new \RuntimeException('TYPO3_REQUESTTYPE has already been set, cannot be called multiple times', 1450561878);
689 }
690 define('TYPO3_REQUESTTYPE', $requestType);
691 return $this;
692 }
693
694 /**
695 * Extensions may register new caches, so we set the
696 * global cache array to the manager again at this point
697 *
698 * @return Bootstrap
699 * @internal This is not a public API method, do not use in own extensions
700 */
701 public function setFinalCachingFrameworkCacheConfiguration()
702 {
703 $this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
704 return $this;
705 }
706
707 /**
708 * Define logging and exception constants
709 *
710 * @return Bootstrap
711 * @internal This is not a public API method, do not use in own extensions
712 */
713 public function defineLoggingAndExceptionConstants()
714 {
715 define('TYPO3_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_DLOG']);
716 define('TYPO3_ERROR_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_errorDLOG']);
717 define('TYPO3_EXCEPTION_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_exceptionDLOG']);
718 return $this;
719 }
720
721 /**
722 * Unsetting reserved global variables:
723 * Those are set in "ext:core/ext_tables.php" file:
724 *
725 * @return Bootstrap
726 * @internal This is not a public API method, do not use in own extensions
727 */
728 public function unsetReservedGlobalVariables()
729 {
730 unset($GLOBALS['PAGES_TYPES']);
731 unset($GLOBALS['TCA']);
732 unset($GLOBALS['TBE_MODULES']);
733 unset($GLOBALS['TBE_STYLES']);
734 unset($GLOBALS['BE_USER']);
735 // Those set otherwise:
736 unset($GLOBALS['TBE_MODULES_EXT']);
737 unset($GLOBALS['TCA_DESCR']);
738 unset($GLOBALS['LOCAL_LANG']);
739 return $this;
740 }
741
742 /**
743 * Check adminOnly configuration variable and redirects
744 * to an URL in file typo3conf/LOCK_BACKEND or exit the script
745 *
746 * @throws \RuntimeException
747 * @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)
748 * @return Bootstrap
749 * @internal This is not a public API method, do not use in own extensions
750 */
751 public function checkLockedBackendAndRedirectOrDie($forceProceeding = false)
752 {
753 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'] < 0) {
754 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);
755 }
756 if (@is_file(PATH_typo3conf . 'LOCK_BACKEND') && $forceProceeding === false) {
757 $fileContent = file_get_contents(PATH_typo3conf . 'LOCK_BACKEND');
758 if ($fileContent) {
759 header('Location: ' . $fileContent);
760 } else {
761 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);
762 }
763 die;
764 }
765 return $this;
766 }
767
768 /**
769 * Compare client IP with IPmaskList and exit the script run
770 * if the client is not allowed to access the backend
771 *
772 * @return Bootstrap
773 * @internal This is not a public API method, do not use in own extensions
774 * @throws \RuntimeException
775 */
776 public function checkBackendIpOrDie()
777 {
778 if (trim($GLOBALS['TYPO3_CONF_VARS']['BE']['IPmaskList'])) {
779 if (!GeneralUtility::cmpIP(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['BE']['IPmaskList'])) {
780 throw new \RuntimeException('TYPO3 Backend access denied: The IP address of your client does not match the list of allowed IP addresses.', 1389265900);
781 }
782 }
783 return $this;
784 }
785
786 /**
787 * Check lockSSL configuration variable and redirect
788 * to https version of the backend if needed
789 *
790 * @return Bootstrap
791 * @internal This is not a public API method, do not use in own extensions
792 * @throws \RuntimeException
793 */
794 public function checkSslBackendAndRedirectIfNeeded()
795 {
796 if ((bool)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL'] && !GeneralUtility::getIndpEnv('TYPO3_SSL')) {
797 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort']) {
798 $sslPortSuffix = ':' . (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort'];
799 } else {
800 $sslPortSuffix = '';
801 }
802 list(, $url) = explode('://', GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir, 2);
803 list($server, $address) = explode('/', $url, 2);
804 header('Location: https://' . $server . $sslPortSuffix . '/' . $address);
805 die;
806 }
807 return $this;
808 }
809
810 /**
811 * Load $TCA
812 *
813 * This will mainly set up $TCA through extMgm API.
814 *
815 * @param bool $allowCaching True, if loading TCA from cache is allowed
816 * @return Bootstrap
817 * @internal This is not a public API method, do not use in own extensions
818 */
819 public function loadBaseTca(bool $allowCaching = true): Bootstrap
820 {
821 ExtensionManagementUtility::loadBaseTca($allowCaching);
822 return $this;
823 }
824
825 /**
826 * Load ext_tables and friends.
827 *
828 * This will mainly load and execute ext_tables.php files of loaded extensions
829 * or the according cache file if exists.
830 *
831 * @param bool $allowCaching True, if reading compiled ext_tables file from cache is allowed
832 * @return Bootstrap
833 * @internal This is not a public API method, do not use in own extensions
834 */
835 public function loadExtTables(bool $allowCaching = true): Bootstrap
836 {
837 ExtensionManagementUtility::loadExtTables($allowCaching);
838 $this->runExtTablesPostProcessingHooks();
839 return $this;
840 }
841
842 /**
843 * Check for registered ext tables hooks and run them
844 *
845 * @throws \UnexpectedValueException
846 */
847 protected function runExtTablesPostProcessingHooks()
848 {
849 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['extTablesInclusion-PostProcessing'])) {
850 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['extTablesInclusion-PostProcessing'] as $className) {
851 /** @var $hookObject \TYPO3\CMS\Core\Database\TableConfigurationPostProcessingHookInterface */
852 $hookObject = GeneralUtility::makeInstance($className);
853 if (!$hookObject instanceof \TYPO3\CMS\Core\Database\TableConfigurationPostProcessingHookInterface) {
854 throw new \UnexpectedValueException(
855 '$hookObject "' . $className . '" must implement interface TYPO3\\CMS\\Core\\Database\\TableConfigurationPostProcessingHookInterface',
856 1320585902
857 );
858 }
859 $hookObject->processData();
860 }
861 }
862 }
863
864 /**
865 * Initialize the Routing for the TYPO3 Backend
866 * Loads all routes registered inside all packages and stores them inside the Router
867 *
868 * @return Bootstrap
869 * @internal This is not a public API method, do not use in own extensions
870 */
871 public function initializeBackendRouter()
872 {
873 // See if the Routes.php from all active packages have been built together already
874 $cacheIdentifier = 'BackendRoutesFromPackages_' . sha1((TYPO3_version . PATH_site . 'BackendRoutesFromPackages'));
875
876 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
877 $codeCache = $this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('cache_core');
878 $routesFromPackages = [];
879 if ($codeCache->has($cacheIdentifier)) {
880 // substr is necessary, because the php frontend wraps php code around the cache value
881 $routesFromPackages = unserialize(substr($codeCache->get($cacheIdentifier), 6, -2));
882 } else {
883 // Loop over all packages and check for a Configuration/Backend/Routes.php file
884 $packageManager = $this->getEarlyInstance(\TYPO3\CMS\Core\Package\PackageManager::class);
885 $packages = $packageManager->getActivePackages();
886 foreach ($packages as $package) {
887 $routesFileNameForPackage = $package->getPackagePath() . 'Configuration/Backend/Routes.php';
888 if (file_exists($routesFileNameForPackage)) {
889 $definedRoutesInPackage = require $routesFileNameForPackage;
890 if (is_array($definedRoutesInPackage)) {
891 $routesFromPackages = array_merge($routesFromPackages, $definedRoutesInPackage);
892 }
893 }
894 $routesFileNameForPackage = $package->getPackagePath() . 'Configuration/Backend/AjaxRoutes.php';
895 if (file_exists($routesFileNameForPackage)) {
896 $definedRoutesInPackage = require $routesFileNameForPackage;
897 if (is_array($definedRoutesInPackage)) {
898 foreach ($definedRoutesInPackage as $routeIdentifier => $routeOptions) {
899 // prefix the route with "ajax_" as "namespace"
900 $routeOptions['path'] = '/ajax' . $routeOptions['path'];
901 $routesFromPackages['ajax_' . $routeIdentifier] = $routeOptions;
902 $routesFromPackages['ajax_' . $routeIdentifier]['ajax'] = true;
903 }
904 }
905 }
906 }
907 // Store the data from all packages in the cache
908 $codeCache->set($cacheIdentifier, serialize($routesFromPackages));
909 }
910
911 // Build Route objects from the data
912 $router = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\Router::class);
913 foreach ($routesFromPackages as $name => $options) {
914 $path = $options['path'];
915 unset($options['path']);
916 $route = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\Route::class, $path, $options);
917 $router->addRoute($name, $route);
918 }
919 return $this;
920 }
921
922 /**
923 * Initialize backend user object in globals
924 *
925 * @param string $className usually \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::class but can be used for CLI
926 * @return Bootstrap
927 * @internal This is not a public API method, do not use in own extensions
928 */
929 public function initializeBackendUser($className = \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::class)
930 {
931 /** @var $backendUser \TYPO3\CMS\Core\Authentication\BackendUserAuthentication */
932 $backendUser = GeneralUtility::makeInstance($className);
933 // The global must be available very early, because methods below
934 // might trigger code which relies on it. See: #45625
935 $GLOBALS['BE_USER'] = $backendUser;
936 $backendUser->start();
937 return $this;
938 }
939
940 /**
941 * Initializes and ensures authenticated access
942 *
943 * @internal This is not a public API method, do not use in own extensions
944 * @param bool $proceedIfNoUserIsLoggedIn if set to TRUE, no forced redirect to the login page will be done
945 * @return \TYPO3\CMS\Core\Core\Bootstrap
946 */
947 public function initializeBackendAuthentication($proceedIfNoUserIsLoggedIn = false)
948 {
949 $GLOBALS['BE_USER']->backendCheckLogin($proceedIfNoUserIsLoggedIn);
950 return $this;
951 }
952
953 /**
954 * Initialize language object
955 *
956 * @return Bootstrap
957 * @internal This is not a public API method, do not use in own extensions
958 */
959 public function initializeLanguageObject()
960 {
961 /** @var $GLOBALS['LANG'] \TYPO3\CMS\Core\Localization\LanguageService */
962 $GLOBALS['LANG'] = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Localization\LanguageService::class);
963 $GLOBALS['LANG']->init($GLOBALS['BE_USER']->uc['lang']);
964 return $this;
965 }
966
967 /**
968 * Throw away all output that may have happened during bootstrapping by weird extensions
969 *
970 * @return Bootstrap
971 * @internal This is not a public API method, do not use in own extensions
972 */
973 public function endOutputBufferingAndCleanPreviousOutput()
974 {
975 ob_clean();
976 return $this;
977 }
978
979 /**
980 * Initialize output compression if configured
981 *
982 * @return Bootstrap
983 * @internal This is not a public API method, do not use in own extensions
984 */
985 public function initializeOutputCompression()
986 {
987 if (extension_loaded('zlib') && $GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel']) {
988 if (MathUtility::canBeInterpretedAsInteger($GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel'])) {
989 @ini_set('zlib.output_compression_level', $GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel']);
990 }
991 ob_start('ob_gzhandler');
992 }
993 return $this;
994 }
995
996 /**
997 * Send HTTP headers if configured
998 *
999 * @return Bootstrap
1000 * @internal This is not a public API method, do not use in own extensions
1001 */
1002 public function sendHttpHeaders()
1003 {
1004 if (!empty($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers']) && is_array($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers'])) {
1005 foreach ($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers'] as $header) {
1006 header($header);
1007 }
1008 }
1009 return $this;
1010 }
1011
1012 /**
1013 * Things that should be performed to shut down the framework.
1014 * This method is called in all important scripts for a clean
1015 * shut down of the system.
1016 *
1017 * @return Bootstrap
1018 * @internal This is not a public API method, do not use in own extensions
1019 */
1020 public function shutdown()
1021 {
1022 $this->sendResponse();
1023 return $this;
1024 }
1025
1026 /**
1027 * Provides an instance of "template" for backend-modules to
1028 * work with.
1029 *
1030 * @return Bootstrap
1031 * @internal This is not a public API method, do not use in own extensions
1032 */
1033 public function initializeBackendTemplate()
1034 {
1035 $GLOBALS['TBE_TEMPLATE'] = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Template\DocumentTemplate::class);
1036 return $this;
1037 }
1038 }