2ad8ab6d4dba70142e59ee707a56240a41600f4b
[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 pathes 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 ->initializeTypo3DbGlobal();
177
178 return $this;
179 }
180
181 /**
182 * Run the base setup that checks server environment, determines pathes,
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 foreach ($this->response->getHeaders() as $name => $values) {
324 header($name . ': ' . implode(', ', $values));
325 }
326 // If the response code was not changed by legacy code (still is 200)
327 // then allow the PSR-7 response object to explicitly set it.
328 // Otherwise let legacy code take precedence.
329 // This code path can be deprecated once we expose the response object to third party code
330 if (http_response_code() === 200) {
331 header('HTTP/' . $this->response->getProtocolVersion() . ' ' . $this->response->getStatusCode() . ' ' . $this->response->getReasonPhrase());
332 }
333 }
334 echo $this->response->getBody()->__toString();
335 }
336 return $this;
337 }
338
339 /**
340 * Registers the instance of the specified object for an early boot stage.
341 * On finalizing the Object Manager initialization, all those instances will
342 * be transferred to the Object Manager's registry.
343 *
344 * @param string $objectName Object name, as later used by the Object Manager
345 * @param object $instance The instance to register
346 * @return void
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 ->registerExtDirectComponents()
402 ->setCacheHashOptions()
403 ->setDefaultTimezone()
404 ->initializeL10nLocales()
405 ->setMemoryLimit();
406 if ($allowCaching) {
407 $this->ensureClassLoadingInformationExists();
408 }
409 return $this;
410 }
411
412 /**
413 * Initializes the package system and loads the package configuration and settings
414 * provided by the packages.
415 *
416 * @param string $packageManagerClassName Define an alternative package manager implementation (usually for the installer)
417 * @return Bootstrap
418 * @internal This is not a public API method, do not use in own extensions
419 */
420 public function initializePackageManagement($packageManagerClassName)
421 {
422 /** @var \TYPO3\CMS\Core\Package\PackageManager $packageManager */
423 $packageManager = new $packageManagerClassName();
424 $this->setEarlyInstance(\TYPO3\CMS\Core\Package\PackageManager::class, $packageManager);
425 ExtensionManagementUtility::setPackageManager($packageManager);
426 $packageManager->injectCoreCache($this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('cache_core'));
427 $dependencyResolver = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Package\DependencyResolver::class);
428 $dependencyResolver->injectDependencyOrderingService(GeneralUtility::makeInstance(\TYPO3\CMS\Core\Service\DependencyOrderingService::class));
429 $packageManager->injectDependencyResolver($dependencyResolver);
430 $packageManager->initialize();
431 GeneralUtility::setSingletonInstance(\TYPO3\CMS\Core\Package\PackageManager::class, $packageManager);
432 return $this;
433 }
434
435 /**
436 * Writes class loading information if not yet present
437 *
438 * @return Bootstrap
439 * @internal This is not a public API method, do not use in own extensions
440 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9. Use the Install Tool to dump autoload information.
441 */
442 public function ensureClassLoadingInformationExists()
443 {
444 if (!self::$usesComposerClassLoading && !ClassLoadingInformation::isClassLoadingInformationAvailable()) {
445 GeneralUtility::logDeprecatedFunction();
446 ClassLoadingInformation::dumpClassLoadingInformation();
447 ClassLoadingInformation::registerClassLoadingInformation();
448 }
449 return $this;
450 }
451
452 /**
453 * Activates a package during runtime. This is used in AdditionalConfiguration.php
454 * to enable extensions under conditions.
455 *
456 * @return Bootstrap
457 */
458 protected function initializeRuntimeActivatedPackagesFromConfiguration()
459 {
460 if (!empty($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages']) && is_array($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages'])) {
461 /** @var \TYPO3\CMS\Core\Package\PackageManager $packageManager */
462 $packageManager = $this->getEarlyInstance(\TYPO3\CMS\Core\Package\PackageManager::class);
463 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages'] as $runtimeAddedPackageKey) {
464 $packageManager->activatePackageDuringRuntime($runtimeAddedPackageKey);
465 }
466 }
467 return $this;
468 }
469
470 /**
471 * Load ext_localconf of extensions
472 *
473 * @param bool $allowCaching
474 * @return Bootstrap
475 * @internal This is not a public API method, do not use in own extensions
476 */
477 public function loadTypo3LoadedExtAndExtLocalconf($allowCaching = true)
478 {
479 ExtensionManagementUtility::loadExtLocalconf($allowCaching);
480 return $this;
481 }
482
483 /**
484 * We need an early instance of the configuration manager.
485 * Since makeInstance relies on the object configuration, we create it here with new instead.
486 *
487 * @return Bootstrap
488 * @internal This is not a public API method, do not use in own extensions
489 */
490 public function populateLocalConfiguration()
491 {
492 try {
493 $configurationManager = $this->getEarlyInstance(\TYPO3\CMS\Core\Configuration\ConfigurationManager::class);
494 } catch (\TYPO3\CMS\Core\Exception $exception) {
495 $configurationManager = new \TYPO3\CMS\Core\Configuration\ConfigurationManager();
496 $this->setEarlyInstance(\TYPO3\CMS\Core\Configuration\ConfigurationManager::class, $configurationManager);
497 }
498 $configurationManager->exportConfiguration();
499 return $this;
500 }
501
502 /**
503 * Set cache_core to null backend, effectively disabling eg. the cache for ext_localconf and PackageManager etc.
504 *
505 * @return \TYPO3\CMS\Core\Core\Bootstrap
506 * @internal This is not a public API method, do not use in own extensions
507 */
508 public function disableCoreCache()
509 {
510 $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['cache_core']['backend']
511 = \TYPO3\CMS\Core\Cache\Backend\NullBackend::class;
512 unset($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['cache_core']['options']);
513 return $this;
514 }
515
516 /**
517 * Define user agent constant
518 *
519 * @return \TYPO3\CMS\Core\Core\Bootstrap
520 */
521 protected function defineUserAgentConstant()
522 {
523 define('TYPO3_user_agent', 'User-Agent: ' . $GLOBALS['TYPO3_CONF_VARS']['HTTP']['headers']['User-Agent']);
524 return $this;
525 }
526
527 /**
528 * Register default ExtDirect components
529 *
530 * @return Bootstrap
531 */
532 protected function registerExtDirectComponents()
533 {
534 if (TYPO3_MODE === 'BE') {
535 ExtensionManagementUtility::registerExtDirectComponent(
536 'TYPO3.Components.PageTree.DataProvider',
537 \TYPO3\CMS\Backend\Tree\Pagetree\ExtdirectTreeDataProvider::class
538 );
539 ExtensionManagementUtility::registerExtDirectComponent(
540 'TYPO3.Components.PageTree.Commands',
541 \TYPO3\CMS\Backend\Tree\Pagetree\ExtdirectTreeCommands::class
542 );
543 ExtensionManagementUtility::registerExtDirectComponent(
544 'TYPO3.Components.PageTree.ContextMenuDataProvider',
545 \TYPO3\CMS\Backend\ContextMenu\Pagetree\Extdirect\ContextMenuConfiguration::class
546 );
547 }
548 return $this;
549 }
550
551 /**
552 * Initialize caching framework, and re-initializes it (e.g. in the install tool) by recreating the instances
553 * again despite the Singleton instance
554 *
555 * @return Bootstrap
556 * @internal This is not a public API method, do not use in own extensions
557 */
558 public function initializeCachingFramework()
559 {
560 $cacheManager = new \TYPO3\CMS\Core\Cache\CacheManager();
561 $cacheManager->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
562 GeneralUtility::setSingletonInstance(\TYPO3\CMS\Core\Cache\CacheManager::class, $cacheManager);
563 $this->setEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class, $cacheManager);
564 return $this;
565 }
566
567 /**
568 * Set cacheHash options
569 *
570 * @return Bootstrap
571 */
572 protected function setCacheHashOptions()
573 {
574 $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash'] = [
575 'cachedParametersWhiteList' => GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashOnlyForParameters'], true),
576 'excludedParameters' => GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParameters'], true),
577 'requireCacheHashPresenceParameters' => GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashRequiredParameters'], true),
578 'includePageId' => $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashIncludePageId']
579 ];
580 if (trim($GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParametersIfEmpty']) === '*') {
581 $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludeAllEmptyParameters'] = true;
582 } else {
583 $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludedParametersIfEmpty'] = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParametersIfEmpty'], true);
584 }
585 return $this;
586 }
587
588 /**
589 * Set default timezone
590 *
591 * @return Bootstrap
592 */
593 protected function setDefaultTimezone()
594 {
595 $timeZone = $GLOBALS['TYPO3_CONF_VARS']['SYS']['phpTimeZone'];
596 if (empty($timeZone)) {
597 // Time zone from the server environment (TZ env or OS query)
598 $defaultTimeZone = @date_default_timezone_get();
599 if ($defaultTimeZone !== '') {
600 $timeZone = $defaultTimeZone;
601 } else {
602 $timeZone = 'UTC';
603 }
604 }
605 // Set default to avoid E_WARNINGs with PHP > 5.3
606 date_default_timezone_set($timeZone);
607 return $this;
608 }
609
610 /**
611 * Initialize the locales handled by TYPO3
612 *
613 * @return Bootstrap
614 */
615 protected function initializeL10nLocales()
616 {
617 \TYPO3\CMS\Core\Localization\Locales::initialize();
618 return $this;
619 }
620
621 /**
622 * Configure and set up exception and error handling
623 *
624 * @return Bootstrap
625 * @throws \RuntimeException
626 */
627 protected function initializeErrorHandling()
628 {
629 $productionExceptionHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['productionExceptionHandler'];
630 $debugExceptionHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['debugExceptionHandler'];
631
632 $errorHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandler'];
633 $errorHandlerErrors = $GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandlerErrors'];
634 $exceptionalErrors = $GLOBALS['TYPO3_CONF_VARS']['SYS']['exceptionalErrors'];
635
636 $displayErrorsSetting = (int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['displayErrors'];
637 switch ($displayErrorsSetting) {
638 case -1:
639 $ipMatchesDevelopmentSystem = GeneralUtility::cmpIP(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']);
640 $exceptionHandlerClassName = $ipMatchesDevelopmentSystem ? $debugExceptionHandlerClassName : $productionExceptionHandlerClassName;
641 $displayErrors = $ipMatchesDevelopmentSystem ? 1 : 0;
642 $exceptionalErrors = $ipMatchesDevelopmentSystem ? $exceptionalErrors : 0;
643 break;
644 case 0:
645 $exceptionHandlerClassName = $productionExceptionHandlerClassName;
646 $displayErrors = 0;
647 break;
648 case 1:
649 $exceptionHandlerClassName = $debugExceptionHandlerClassName;
650 $displayErrors = 1;
651 break;
652 default:
653 // Throw exception if an invalid option is set.
654 throw new \RuntimeException(
655 'The option $TYPO3_CONF_VARS[SYS][displayErrors] is not set to "-1", "0" or "1".',
656 1476046290
657 );
658 }
659 @ini_set('display_errors', $displayErrors);
660
661 if (!empty($errorHandlerClassName)) {
662 // Register an error handler for the given errorHandlerError
663 $errorHandler = GeneralUtility::makeInstance($errorHandlerClassName, $errorHandlerErrors);
664 $errorHandler->setExceptionalErrors($exceptionalErrors);
665 if (is_callable([$errorHandler, 'setDebugMode'])) {
666 $errorHandler->setDebugMode($displayErrors === 1);
667 }
668 }
669 if (!empty($exceptionHandlerClassName)) {
670 // Registering the exception handler is done in the constructor
671 GeneralUtility::makeInstance($exceptionHandlerClassName);
672 }
673 return $this;
674 }
675
676 /**
677 * Set PHP memory limit depending on value of
678 * $GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit']
679 *
680 * @return Bootstrap
681 */
682 protected function setMemoryLimit()
683 {
684 if ((int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit'] > 16) {
685 @ini_set('memory_limit', ((int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit'] . 'm'));
686 }
687 return $this;
688 }
689
690 /**
691 * Define TYPO3_REQUESTTYPE* constants that can be used for developers to see if any context has been hit
692 * also see setRequestType(). Is done at the very beginning so these parameters are always available.
693 *
694 * @return Bootstrap
695 */
696 protected function defineTypo3RequestTypes()
697 {
698 define('TYPO3_REQUESTTYPE_FE', 1);
699 define('TYPO3_REQUESTTYPE_BE', 2);
700 define('TYPO3_REQUESTTYPE_CLI', 4);
701 define('TYPO3_REQUESTTYPE_AJAX', 8);
702 define('TYPO3_REQUESTTYPE_INSTALL', 16);
703 }
704
705 /**
706 * Defines the TYPO3_REQUESTTYPE constant so the environment knows which context the request is running.
707 *
708 * @throws \RuntimeException if the method was already called during a request
709 * @return Bootstrap
710 */
711 public function setRequestType($requestType)
712 {
713 if (defined('TYPO3_REQUESTTYPE')) {
714 throw new \RuntimeException('TYPO3_REQUESTTYPE has already been set, cannot be called multiple times', 1450561878);
715 }
716 define('TYPO3_REQUESTTYPE', $requestType);
717 return $this;
718 }
719
720 /**
721 * Extensions may register new caches, so we set the
722 * global cache array to the manager again at this point
723 *
724 * @return Bootstrap
725 * @internal This is not a public API method, do not use in own extensions
726 */
727 public function setFinalCachingFrameworkCacheConfiguration()
728 {
729 $this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
730 return $this;
731 }
732
733 /**
734 * Define logging and exception constants
735 *
736 * @return Bootstrap
737 * @internal This is not a public API method, do not use in own extensions
738 */
739 public function defineLoggingAndExceptionConstants()
740 {
741 define('TYPO3_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_DLOG']);
742 define('TYPO3_ERROR_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_errorDLOG']);
743 define('TYPO3_EXCEPTION_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_exceptionDLOG']);
744 return $this;
745 }
746
747 /**
748 * Unsetting reserved global variables:
749 * Those are set in "ext:core/ext_tables.php" file:
750 *
751 * @return Bootstrap
752 * @internal This is not a public API method, do not use in own extensions
753 */
754 public function unsetReservedGlobalVariables()
755 {
756 unset($GLOBALS['PAGES_TYPES']);
757 unset($GLOBALS['TCA']);
758 unset($GLOBALS['TBE_MODULES']);
759 unset($GLOBALS['TBE_STYLES']);
760 unset($GLOBALS['BE_USER']);
761 // Those set otherwise:
762 unset($GLOBALS['TBE_MODULES_EXT']);
763 unset($GLOBALS['TCA_DESCR']);
764 unset($GLOBALS['LOCAL_LANG']);
765 return $this;
766 }
767
768 /**
769 * Initialize database connection in $GLOBALS and connect if requested
770 *
771 * @return \TYPO3\CMS\Core\Core\Bootstrap
772 * @internal This is not a public API method, do not use in own extensions
773 */
774 public function initializeTypo3DbGlobal()
775 {
776 /** @var $databaseConnection \TYPO3\CMS\Core\Database\DatabaseConnection */
777 $databaseConnection = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\DatabaseConnection::class);
778 $databaseConnection->setDatabaseName(
779 $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['dbname'] ?? ''
780 );
781 $databaseConnection->setDatabaseUsername(
782 $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['user'] ?? ''
783 );
784 $databaseConnection->setDatabasePassword(
785 $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['password'] ?? ''
786 );
787
788 $databaseHost = $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['host'] ?? '';
789 if (isset($GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['port'])) {
790 $databaseConnection->setDatabasePort($GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['port']);
791 } elseif (strpos($databaseHost, ':') > 0) {
792 // @TODO: Find a way to handle this case in the install tool and drop this
793 list($databaseHost, $databasePort) = explode(':', $databaseHost);
794 $databaseConnection->setDatabasePort($databasePort);
795 }
796 if (isset($GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['unix_socket'])) {
797 $databaseConnection->setDatabaseSocket(
798 $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['unix_socket']
799 );
800 }
801 $databaseConnection->setDatabaseHost($databaseHost);
802
803 $databaseConnection->debugOutput = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sqlDebug'];
804
805 if (isset($GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['persistentConnection'])
806 && $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['persistentConnection']
807 ) {
808 $databaseConnection->setPersistentDatabaseConnection(true);
809 }
810
811 $isDatabaseHostLocalHost = in_array($databaseHost, ['localhost', '127.0.0.1', '::1'], true);
812 if (isset($GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['driverOptions'])
813 && $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['driverOptions'] & MYSQLI_CLIENT_COMPRESS
814 && !$isDatabaseHostLocalHost
815 ) {
816 $databaseConnection->setConnectionCompression(true);
817 }
818
819 if (!empty($GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['initCommands'])) {
820 $commandsAfterConnect = GeneralUtility::trimExplode(
821 LF,
822 str_replace(
823 '\' . LF . \'',
824 LF,
825 $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['initCommands']
826 ),
827 true
828 );
829 $databaseConnection->setInitializeCommandsAfterConnect($commandsAfterConnect);
830 }
831
832 $GLOBALS['TYPO3_DB'] = $databaseConnection;
833 // $GLOBALS['TYPO3_DB'] needs to be defined first in order to work for DBAL
834 $GLOBALS['TYPO3_DB']->initialize();
835
836 return $this;
837 }
838
839 /**
840 * Check adminOnly configuration variable and redirects
841 * to an URL in file typo3conf/LOCK_BACKEND or exit the script
842 *
843 * @throws \RuntimeException
844 * @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)
845 * @return Bootstrap
846 * @internal This is not a public API method, do not use in own extensions
847 */
848 public function checkLockedBackendAndRedirectOrDie($forceProceeding = false)
849 {
850 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'] < 0) {
851 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);
852 }
853 if (@is_file(PATH_typo3conf . 'LOCK_BACKEND') && $forceProceeding === false) {
854 $fileContent = file_get_contents(PATH_typo3conf . 'LOCK_BACKEND');
855 if ($fileContent) {
856 header('Location: ' . $fileContent);
857 } else {
858 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);
859 }
860 die;
861 }
862 return $this;
863 }
864
865 /**
866 * Compare client IP with IPmaskList and exit the script run
867 * if the client is not allowed to access the backend
868 *
869 * @return Bootstrap
870 * @internal This is not a public API method, do not use in own extensions
871 * @throws \RuntimeException
872 */
873 public function checkBackendIpOrDie()
874 {
875 if (trim($GLOBALS['TYPO3_CONF_VARS']['BE']['IPmaskList'])) {
876 if (!GeneralUtility::cmpIP(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['BE']['IPmaskList'])) {
877 throw new \RuntimeException('TYPO3 Backend access denied: The IP address of your client does not match the list of allowed IP addresses.', 1389265900);
878 }
879 }
880 return $this;
881 }
882
883 /**
884 * Check lockSSL configuration variable and redirect
885 * to https version of the backend if needed
886 *
887 * @return Bootstrap
888 * @internal This is not a public API method, do not use in own extensions
889 * @throws \RuntimeException
890 */
891 public function checkSslBackendAndRedirectIfNeeded()
892 {
893 if ((bool)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL'] && !GeneralUtility::getIndpEnv('TYPO3_SSL')) {
894 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort']) {
895 $sslPortSuffix = ':' . (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort'];
896 } else {
897 $sslPortSuffix = '';
898 }
899 list(, $url) = explode('://', GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir, 2);
900 list($server, $address) = explode('/', $url, 2);
901 header('Location: https://' . $server . $sslPortSuffix . '/' . $address);
902 die;
903 }
904 return $this;
905 }
906
907 /**
908 * Load ext_tables and friends.
909 *
910 * This will mainly set up $TCA and several other global arrays
911 * through API's like extMgm.
912 * Executes ext_tables.php files of loaded extensions or the
913 * according cache file if exists.
914 *
915 * @param bool $allowCaching True, if reading compiled ext_tables file from cache is allowed
916 * @return Bootstrap
917 * @internal This is not a public API method, do not use in own extensions
918 */
919 public function loadExtensionTables($allowCaching = true)
920 {
921 ExtensionManagementUtility::loadBaseTca($allowCaching);
922 ExtensionManagementUtility::loadExtTables($allowCaching);
923 $this->runExtTablesPostProcessingHooks();
924 return $this;
925 }
926
927 /**
928 * Check for registered ext tables hooks and run them
929 *
930 * @throws \UnexpectedValueException
931 * @return void
932 */
933 protected function runExtTablesPostProcessingHooks()
934 {
935 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['extTablesInclusion-PostProcessing'])) {
936 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['extTablesInclusion-PostProcessing'] as $classReference) {
937 /** @var $hookObject \TYPO3\CMS\Core\Database\TableConfigurationPostProcessingHookInterface */
938 $hookObject = GeneralUtility::getUserObj($classReference);
939 if (!$hookObject instanceof \TYPO3\CMS\Core\Database\TableConfigurationPostProcessingHookInterface) {
940 throw new \UnexpectedValueException(
941 '$hookObject "' . $classReference . '" must implement interface TYPO3\\CMS\\Core\\Database\\TableConfigurationPostProcessingHookInterface',
942 1320585902
943 );
944 }
945 $hookObject->processData();
946 }
947 }
948 }
949
950 /**
951 * Initialize the Routing for the TYPO3 Backend
952 * Loads all routes registered inside all packages and stores them inside the Router
953 *
954 * @return Bootstrap
955 * @internal This is not a public API method, do not use in own extensions
956 */
957 public function initializeBackendRouter()
958 {
959 // See if the Routes.php from all active packages have been built together already
960 $cacheIdentifier = 'BackendRoutesFromPackages_' . sha1((TYPO3_version . PATH_site . 'BackendRoutesFromPackages'));
961
962 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
963 $codeCache = $this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('cache_core');
964 $routesFromPackages = [];
965 if ($codeCache->has($cacheIdentifier)) {
966 // substr is necessary, because the php frontend wraps php code around the cache value
967 $routesFromPackages = unserialize(substr($codeCache->get($cacheIdentifier), 6, -2));
968 } else {
969 // Loop over all packages and check for a Configuration/Backend/Routes.php file
970 $packageManager = $this->getEarlyInstance(\TYPO3\CMS\Core\Package\PackageManager::class);
971 $packages = $packageManager->getActivePackages();
972 foreach ($packages as $package) {
973 $routesFileNameForPackage = $package->getPackagePath() . 'Configuration/Backend/Routes.php';
974 if (file_exists($routesFileNameForPackage)) {
975 $definedRoutesInPackage = require $routesFileNameForPackage;
976 if (is_array($definedRoutesInPackage)) {
977 $routesFromPackages = array_merge($routesFromPackages, $definedRoutesInPackage);
978 }
979 }
980 $routesFileNameForPackage = $package->getPackagePath() . 'Configuration/Backend/AjaxRoutes.php';
981 if (file_exists($routesFileNameForPackage)) {
982 $definedRoutesInPackage = require $routesFileNameForPackage;
983 if (is_array($definedRoutesInPackage)) {
984 foreach ($definedRoutesInPackage as $routeIdentifier => $routeOptions) {
985 // prefix the route with "ajax_" as "namespace"
986 $routeOptions['path'] = '/ajax' . $routeOptions['path'];
987 $routesFromPackages['ajax_' . $routeIdentifier] = $routeOptions;
988 $routesFromPackages['ajax_' . $routeIdentifier]['ajax'] = true;
989 }
990 }
991 }
992 }
993 // Store the data from all packages in the cache
994 $codeCache->set($cacheIdentifier, serialize($routesFromPackages));
995 }
996
997 // Build Route objects from the data
998 $router = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\Router::class);
999 foreach ($routesFromPackages as $name => $options) {
1000 $path = $options['path'];
1001 unset($options['path']);
1002 $route = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\Route::class, $path, $options);
1003 $router->addRoute($name, $route);
1004 }
1005 return $this;
1006 }
1007
1008 /**
1009 * Initialize backend user object in globals
1010 *
1011 * @param string $className usually \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::class but can be used for CLI
1012 * @return Bootstrap
1013 * @internal This is not a public API method, do not use in own extensions
1014 */
1015 public function initializeBackendUser($className = \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::class)
1016 {
1017 /** @var $backendUser \TYPO3\CMS\Core\Authentication\BackendUserAuthentication */
1018 $backendUser = GeneralUtility::makeInstance($className);
1019 // The global must be available very early, because methods below
1020 // might trigger code which relies on it. See: #45625
1021 $GLOBALS['BE_USER'] = $backendUser;
1022 $backendUser->start();
1023 return $this;
1024 }
1025
1026 /**
1027 * Initializes and ensures authenticated access
1028 *
1029 * @internal This is not a public API method, do not use in own extensions
1030 * @param bool $proceedIfNoUserIsLoggedIn if set to TRUE, no forced redirect to the login page will be done
1031 * @return \TYPO3\CMS\Core\Core\Bootstrap
1032 */
1033 public function initializeBackendAuthentication($proceedIfNoUserIsLoggedIn = false)
1034 {
1035 $GLOBALS['BE_USER']->backendCheckLogin($proceedIfNoUserIsLoggedIn);
1036 return $this;
1037 }
1038
1039 /**
1040 * Initialize language object
1041 *
1042 * @return Bootstrap
1043 * @internal This is not a public API method, do not use in own extensions
1044 */
1045 public function initializeLanguageObject()
1046 {
1047 /** @var $GLOBALS['LANG'] \TYPO3\CMS\Lang\LanguageService */
1048 $GLOBALS['LANG'] = GeneralUtility::makeInstance(\TYPO3\CMS\Lang\LanguageService::class);
1049 $GLOBALS['LANG']->init($GLOBALS['BE_USER']->uc['lang']);
1050 return $this;
1051 }
1052
1053 /**
1054 * Throw away all output that may have happened during bootstrapping by weird extensions
1055 *
1056 * @return Bootstrap
1057 * @internal This is not a public API method, do not use in own extensions
1058 */
1059 public function endOutputBufferingAndCleanPreviousOutput()
1060 {
1061 ob_clean();
1062 return $this;
1063 }
1064
1065 /**
1066 * Initialize output compression if configured
1067 *
1068 * @return Bootstrap
1069 * @internal This is not a public API method, do not use in own extensions
1070 */
1071 public function initializeOutputCompression()
1072 {
1073 if (extension_loaded('zlib') && $GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel']) {
1074 if (MathUtility::canBeInterpretedAsInteger($GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel'])) {
1075 @ini_set('zlib.output_compression_level', $GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel']);
1076 }
1077 ob_start('ob_gzhandler');
1078 }
1079 return $this;
1080 }
1081
1082 /**
1083 * Send HTTP headers if configured
1084 *
1085 * @return Bootstrap
1086 * @internal This is not a public API method, do not use in own extensions
1087 */
1088 public function sendHttpHeaders()
1089 {
1090 if (!empty($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers']) && is_array($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers'])) {
1091 foreach ($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers'] as $header) {
1092 header($header);
1093 }
1094 }
1095 return $this;
1096 }
1097
1098 /**
1099 * Things that should be performed to shut down the framework.
1100 * This method is called in all important scripts for a clean
1101 * shut down of the system.
1102 *
1103 * @return Bootstrap
1104 * @internal This is not a public API method, do not use in own extensions
1105 */
1106 public function shutdown()
1107 {
1108 $this->sendResponse();
1109 return $this;
1110 }
1111
1112 /**
1113 * Provides an instance of "template" for backend-modules to
1114 * work with.
1115 *
1116 * @return Bootstrap
1117 * @internal This is not a public API method, do not use in own extensions
1118 */
1119 public function initializeBackendTemplate()
1120 {
1121 $GLOBALS['TBE_TEMPLATE'] = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Template\DocumentTemplate::class);
1122 return $this;
1123 }
1124 }