f2f71800dbebd5b07de1e91220f030cc355d454a
[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
177 return $this;
178 }
179
180 /**
181 * Run the base setup that checks server environment, determines paths,
182 * populates base files and sets common configuration.
183 *
184 * Script execution will be aborted if something fails here.
185 *
186 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
187 * @return Bootstrap
188 * @throws \RuntimeException when TYPO3_REQUESTTYPE was not set before, setRequestType() needs to be called before
189 * @internal This is not a public API method, do not use in own extensions
190 */
191 public function baseSetup($entryPointLevel = 0)
192 {
193 if (!defined('TYPO3_REQUESTTYPE')) {
194 throw new \RuntimeException('No Request Type was set, TYPO3 does not know in which context it is run.', 1450561838);
195 }
196 SystemEnvironmentBuilder::run($entryPointLevel);
197 if (!self::$usesComposerClassLoading && ClassLoadingInformation::isClassLoadingInformationAvailable()) {
198 ClassLoadingInformation::registerClassLoadingInformation();
199 }
200 GeneralUtility::presetApplicationContext($this->applicationContext);
201 return $this;
202 }
203
204 /**
205 * Sets the class loader to the bootstrap
206 *
207 * @param \Composer\Autoload\ClassLoader $classLoader an instance of the class loader
208 * @return Bootstrap
209 * @internal This is not a public API method, do not use in own extensions
210 */
211 public function initializeClassLoader($classLoader)
212 {
213 $this->setEarlyInstance(\Composer\Autoload\ClassLoader::class, $classLoader);
214 if (defined('TYPO3_COMPOSER_MODE') && TYPO3_COMPOSER_MODE) {
215 self::$usesComposerClassLoading = true;
216 }
217 return $this;
218 }
219
220 /**
221 * checks if LocalConfiguration.php or PackageStates.php is missing,
222 * used to see if a redirect to the install tool is needed
223 *
224 * @return bool TRUE when the essential configuration is available, otherwise FALSE
225 * @internal This is not a public API method, do not use in own extensions
226 */
227 public function checkIfEssentialConfigurationExists()
228 {
229 $configurationManager = new \TYPO3\CMS\Core\Configuration\ConfigurationManager;
230 $this->setEarlyInstance(\TYPO3\CMS\Core\Configuration\ConfigurationManager::class, $configurationManager);
231 return file_exists($configurationManager->getLocalConfigurationFileLocation()) && file_exists(PATH_typo3conf . 'PackageStates.php');
232 }
233
234 /**
235 * Redirect to install tool if LocalConfiguration.php is missing.
236 *
237 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
238 * @internal This is not a public API method, do not use in own extensions
239 */
240 public function redirectToInstallTool($entryPointLevel = 0)
241 {
242 $path = TYPO3_mainDir . 'sysext/install/Start/Install.php';
243 if ($entryPointLevel > 0) {
244 $path = str_repeat('../', $entryPointLevel) . $path;
245 }
246 header('Location: ' . $path);
247 die;
248 }
249
250 /**
251 * Adds available request handlers usually done via an application from the outside.
252 *
253 * @param string $requestHandler class which implements the request handler interface
254 * @return Bootstrap
255 * @internal This is not a public API method, do not use in own extensions
256 */
257 public function registerRequestHandlerImplementation($requestHandler)
258 {
259 $this->availableRequestHandlers[] = $requestHandler;
260 return $this;
261 }
262
263 /**
264 * Fetches the request handler that suits the best based on the priority and the interface
265 * Be sure to always have the constants that are defined in $this->defineTypo3RequestTypes() are set,
266 * so most RequestHandlers can check if they can handle the request.
267 *
268 * @param \Psr\Http\Message\ServerRequestInterface|\Symfony\Component\Console\Input\InputInterface $request
269 * @return \TYPO3\CMS\Core\Http\RequestHandlerInterface|\TYPO3\CMS\Core\Console\RequestHandlerInterface
270 * @throws \TYPO3\CMS\Core\Exception
271 * @internal This is not a public API method, do not use in own extensions
272 */
273 protected function resolveRequestHandler($request)
274 {
275 $suitableRequestHandlers = [];
276 foreach ($this->availableRequestHandlers as $requestHandlerClassName) {
277 /** @var \TYPO3\CMS\Core\Http\RequestHandlerInterface|\TYPO3\CMS\Core\Console\RequestHandlerInterface $requestHandler */
278 $requestHandler = GeneralUtility::makeInstance($requestHandlerClassName, $this);
279 if ($requestHandler->canHandleRequest($request)) {
280 $priority = $requestHandler->getPriority();
281 if (isset($suitableRequestHandlers[$priority])) {
282 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);
283 }
284 $suitableRequestHandlers[$priority] = $requestHandler;
285 }
286 }
287 if (empty($suitableRequestHandlers)) {
288 throw new \TYPO3\CMS\Core\Exception('No suitable request handler found.', 1225418233);
289 }
290 ksort($suitableRequestHandlers);
291 return array_pop($suitableRequestHandlers);
292 }
293
294 /**
295 * Builds a Request instance from the current process, and then resolves the request
296 * through the request handlers depending on Frontend, Backend, CLI etc.
297 *
298 * @param \Psr\Http\Message\RequestInterface|\Symfony\Component\Console\Input\InputInterface $request
299 * @return Bootstrap
300 * @throws \TYPO3\CMS\Core\Exception
301 * @internal This is not a public API method, do not use in own extensions
302 */
303 public function handleRequest($request)
304 {
305 // Resolve request handler that were registered based on the Application
306 $requestHandler = $this->resolveRequestHandler($request);
307
308 // Execute the command which returns a Response object or NULL
309 $this->response = $requestHandler->handleRequest($request);
310 return $this;
311 }
312
313 /**
314 * Outputs content if there is a proper Response object.
315 *
316 * @return Bootstrap
317 */
318 protected function sendResponse()
319 {
320 if ($this->response instanceof \Psr\Http\Message\ResponseInterface) {
321 if (!headers_sent()) {
322 // If the response code was not changed by legacy code (still is 200)
323 // then allow the PSR-7 response object to explicitly set it.
324 // Otherwise let legacy code take precedence.
325 // This code path can be deprecated once we expose the response object to third party code
326 if (http_response_code() === 200) {
327 header('HTTP/' . $this->response->getProtocolVersion() . ' ' . $this->response->getStatusCode() . ' ' . $this->response->getReasonPhrase());
328 }
329
330 foreach ($this->response->getHeaders() as $name => $values) {
331 header($name . ': ' . implode(', ', $values));
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 * @internal This is not a public API method, do not use in own extensions
347 */
348 public function setEarlyInstance($objectName, $instance)
349 {
350 $this->earlyInstances[$objectName] = $instance;
351 }
352
353 /**
354 * Returns an instance which was registered earlier through setEarlyInstance()
355 *
356 * @param string $objectName Object name of the registered instance
357 * @return object
358 * @throws \TYPO3\CMS\Core\Exception
359 * @internal This is not a public API method, do not use in own extensions
360 */
361 public function getEarlyInstance($objectName)
362 {
363 if (!isset($this->earlyInstances[$objectName])) {
364 throw new \TYPO3\CMS\Core\Exception('Unknown early instance "' . $objectName . '"', 1365167380);
365 }
366 return $this->earlyInstances[$objectName];
367 }
368
369 /**
370 * Returns all registered early instances indexed by object name
371 *
372 * @return array
373 * @internal This is not a public API method, do not use in own extensions
374 */
375 public function getEarlyInstances()
376 {
377 return $this->earlyInstances;
378 }
379
380 /**
381 * Includes LocalConfiguration.php and sets several
382 * global settings depending on configuration.
383 *
384 * @param bool $allowCaching Whether to allow caching - affects cache_core (autoloader)
385 * @param string $packageManagerClassName Define an alternative package manager implementation (usually for the installer)
386 * @return Bootstrap
387 * @internal This is not a public API method, do not use in own extensions
388 */
389 public function loadConfigurationAndInitialize($allowCaching = true, $packageManagerClassName = \TYPO3\CMS\Core\Package\PackageManager::class)
390 {
391 $this->populateLocalConfiguration()
392 ->initializeErrorHandling();
393 if (!$allowCaching) {
394 $this->disableCoreCache();
395 }
396 $this->initializeCachingFramework()
397 ->initializePackageManagement($packageManagerClassName)
398 ->initializeRuntimeActivatedPackagesFromConfiguration()
399 ->defineUserAgentConstant()
400 ->registerExtDirectComponents()
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 * Register default ExtDirect components
528 *
529 * @return Bootstrap
530 */
531 protected function registerExtDirectComponents()
532 {
533 if (TYPO3_MODE === 'BE') {
534 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ExtDirect']['TYPO3.Components.PageTree.DataProvider'] = [
535 'callbackClass' => \TYPO3\CMS\Backend\Tree\Pagetree\ExtdirectTreeDataProvider::class,
536 'moduleName' => null,
537 'accessLevel' => null
538 ];
539 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ExtDirect']['TYPO3.Components.PageTree.Commands'] = [
540 'callbackClass' => \TYPO3\CMS\Backend\Tree\Pagetree\ExtdirectTreeCommands::class,
541 'moduleName' => null,
542 'accessLevel' => null
543 ];
544 }
545 return $this;
546 }
547
548 /**
549 * Initialize caching framework, and re-initializes it (e.g. in the install tool) by recreating the instances
550 * again despite the Singleton instance
551 *
552 * @return Bootstrap
553 * @internal This is not a public API method, do not use in own extensions
554 */
555 public function initializeCachingFramework()
556 {
557 $cacheManager = new \TYPO3\CMS\Core\Cache\CacheManager();
558 $cacheManager->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
559 GeneralUtility::setSingletonInstance(\TYPO3\CMS\Core\Cache\CacheManager::class, $cacheManager);
560 $this->setEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class, $cacheManager);
561 return $this;
562 }
563
564 /**
565 * Set cacheHash options
566 *
567 * @return Bootstrap
568 */
569 protected function setCacheHashOptions()
570 {
571 $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash'] = [
572 'cachedParametersWhiteList' => GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashOnlyForParameters'], true),
573 'excludedParameters' => GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParameters'], true),
574 'requireCacheHashPresenceParameters' => GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashRequiredParameters'], true),
575 ];
576 if (trim($GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParametersIfEmpty']) === '*') {
577 $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludeAllEmptyParameters'] = true;
578 } else {
579 $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludedParametersIfEmpty'] = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParametersIfEmpty'], true);
580 }
581 return $this;
582 }
583
584 /**
585 * Set default timezone
586 *
587 * @return Bootstrap
588 */
589 protected function setDefaultTimezone()
590 {
591 $timeZone = $GLOBALS['TYPO3_CONF_VARS']['SYS']['phpTimeZone'];
592 if (empty($timeZone)) {
593 // Time zone from the server environment (TZ env or OS query)
594 $defaultTimeZone = @date_default_timezone_get();
595 if ($defaultTimeZone !== '') {
596 $timeZone = $defaultTimeZone;
597 } else {
598 $timeZone = 'UTC';
599 }
600 }
601 // Set default to avoid E_WARNINGs with PHP > 5.3
602 date_default_timezone_set($timeZone);
603 return $this;
604 }
605
606 /**
607 * Initialize the locales handled by TYPO3
608 *
609 * @return Bootstrap
610 */
611 protected function initializeL10nLocales()
612 {
613 \TYPO3\CMS\Core\Localization\Locales::initialize();
614 return $this;
615 }
616
617 /**
618 * Configure and set up exception and error handling
619 *
620 * @return Bootstrap
621 * @throws \RuntimeException
622 */
623 protected function initializeErrorHandling()
624 {
625 $productionExceptionHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['productionExceptionHandler'];
626 $debugExceptionHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['debugExceptionHandler'];
627
628 $errorHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandler'];
629 $errorHandlerErrors = $GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandlerErrors'];
630 $exceptionalErrors = $GLOBALS['TYPO3_CONF_VARS']['SYS']['exceptionalErrors'];
631
632 $displayErrorsSetting = (int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['displayErrors'];
633 switch ($displayErrorsSetting) {
634 case -1:
635 $ipMatchesDevelopmentSystem = GeneralUtility::cmpIP(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']);
636 $exceptionHandlerClassName = $ipMatchesDevelopmentSystem ? $debugExceptionHandlerClassName : $productionExceptionHandlerClassName;
637 $displayErrors = $ipMatchesDevelopmentSystem ? 1 : 0;
638 $exceptionalErrors = $ipMatchesDevelopmentSystem ? $exceptionalErrors : 0;
639 break;
640 case 0:
641 $exceptionHandlerClassName = $productionExceptionHandlerClassName;
642 $displayErrors = 0;
643 break;
644 case 1:
645 $exceptionHandlerClassName = $debugExceptionHandlerClassName;
646 $displayErrors = 1;
647 break;
648 default:
649 // Throw exception if an invalid option is set.
650 throw new \RuntimeException(
651 'The option $TYPO3_CONF_VARS[SYS][displayErrors] is not set to "-1", "0" or "1".',
652 1476046290
653 );
654 }
655 @ini_set('display_errors', $displayErrors);
656
657 if (!empty($errorHandlerClassName)) {
658 // Register an error handler for the given errorHandlerError
659 $errorHandler = GeneralUtility::makeInstance($errorHandlerClassName, $errorHandlerErrors);
660 $errorHandler->setExceptionalErrors($exceptionalErrors);
661 if (is_callable([$errorHandler, 'setDebugMode'])) {
662 $errorHandler->setDebugMode($displayErrors === 1);
663 }
664 }
665 if (!empty($exceptionHandlerClassName)) {
666 // Registering the exception handler is done in the constructor
667 GeneralUtility::makeInstance($exceptionHandlerClassName);
668 }
669 return $this;
670 }
671
672 /**
673 * Set PHP memory limit depending on value of
674 * $GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit']
675 *
676 * @return Bootstrap
677 */
678 protected function setMemoryLimit()
679 {
680 if ((int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit'] > 16) {
681 @ini_set('memory_limit', ((int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit'] . 'm'));
682 }
683 return $this;
684 }
685
686 /**
687 * Define TYPO3_REQUESTTYPE* constants that can be used for developers to see if any context has been hit
688 * also see setRequestType(). Is done at the very beginning so these parameters are always available.
689 *
690 * @return Bootstrap
691 */
692 protected function defineTypo3RequestTypes()
693 {
694 define('TYPO3_REQUESTTYPE_FE', 1);
695 define('TYPO3_REQUESTTYPE_BE', 2);
696 define('TYPO3_REQUESTTYPE_CLI', 4);
697 define('TYPO3_REQUESTTYPE_AJAX', 8);
698 define('TYPO3_REQUESTTYPE_INSTALL', 16);
699 }
700
701 /**
702 * Defines the TYPO3_REQUESTTYPE constant so the environment knows which context the request is running.
703 *
704 * @throws \RuntimeException if the method was already called during a request
705 * @return Bootstrap
706 */
707 public function setRequestType($requestType)
708 {
709 if (defined('TYPO3_REQUESTTYPE')) {
710 throw new \RuntimeException('TYPO3_REQUESTTYPE has already been set, cannot be called multiple times', 1450561878);
711 }
712 define('TYPO3_REQUESTTYPE', $requestType);
713 return $this;
714 }
715
716 /**
717 * Extensions may register new caches, so we set the
718 * global cache array to the manager again at this point
719 *
720 * @return Bootstrap
721 * @internal This is not a public API method, do not use in own extensions
722 */
723 public function setFinalCachingFrameworkCacheConfiguration()
724 {
725 $this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
726 return $this;
727 }
728
729 /**
730 * Define logging and exception constants
731 *
732 * @return Bootstrap
733 * @internal This is not a public API method, do not use in own extensions
734 */
735 public function defineLoggingAndExceptionConstants()
736 {
737 define('TYPO3_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_DLOG']);
738 define('TYPO3_ERROR_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_errorDLOG']);
739 define('TYPO3_EXCEPTION_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_exceptionDLOG']);
740 return $this;
741 }
742
743 /**
744 * Unsetting reserved global variables:
745 * Those are set in "ext:core/ext_tables.php" file:
746 *
747 * @return Bootstrap
748 * @internal This is not a public API method, do not use in own extensions
749 */
750 public function unsetReservedGlobalVariables()
751 {
752 unset($GLOBALS['PAGES_TYPES']);
753 unset($GLOBALS['TCA']);
754 unset($GLOBALS['TBE_MODULES']);
755 unset($GLOBALS['TBE_STYLES']);
756 unset($GLOBALS['BE_USER']);
757 // Those set otherwise:
758 unset($GLOBALS['TBE_MODULES_EXT']);
759 unset($GLOBALS['TCA_DESCR']);
760 unset($GLOBALS['LOCAL_LANG']);
761 return $this;
762 }
763
764 /**
765 * Check adminOnly configuration variable and redirects
766 * to an URL in file typo3conf/LOCK_BACKEND or exit the script
767 *
768 * @throws \RuntimeException
769 * @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)
770 * @return Bootstrap
771 * @internal This is not a public API method, do not use in own extensions
772 */
773 public function checkLockedBackendAndRedirectOrDie($forceProceeding = false)
774 {
775 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'] < 0) {
776 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);
777 }
778 if (@is_file(PATH_typo3conf . 'LOCK_BACKEND') && $forceProceeding === false) {
779 $fileContent = file_get_contents(PATH_typo3conf . 'LOCK_BACKEND');
780 if ($fileContent) {
781 header('Location: ' . $fileContent);
782 } else {
783 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);
784 }
785 die;
786 }
787 return $this;
788 }
789
790 /**
791 * Compare client IP with IPmaskList and exit the script run
792 * if the client is not allowed to access the backend
793 *
794 * @return Bootstrap
795 * @internal This is not a public API method, do not use in own extensions
796 * @throws \RuntimeException
797 */
798 public function checkBackendIpOrDie()
799 {
800 if (trim($GLOBALS['TYPO3_CONF_VARS']['BE']['IPmaskList'])) {
801 if (!GeneralUtility::cmpIP(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['BE']['IPmaskList'])) {
802 throw new \RuntimeException('TYPO3 Backend access denied: The IP address of your client does not match the list of allowed IP addresses.', 1389265900);
803 }
804 }
805 return $this;
806 }
807
808 /**
809 * Check lockSSL configuration variable and redirect
810 * to https version of the backend if needed
811 *
812 * @return Bootstrap
813 * @internal This is not a public API method, do not use in own extensions
814 * @throws \RuntimeException
815 */
816 public function checkSslBackendAndRedirectIfNeeded()
817 {
818 if ((bool)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL'] && !GeneralUtility::getIndpEnv('TYPO3_SSL')) {
819 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort']) {
820 $sslPortSuffix = ':' . (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort'];
821 } else {
822 $sslPortSuffix = '';
823 }
824 list(, $url) = explode('://', GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir, 2);
825 list($server, $address) = explode('/', $url, 2);
826 header('Location: https://' . $server . $sslPortSuffix . '/' . $address);
827 die;
828 }
829 return $this;
830 }
831
832 /**
833 * Load $TCA
834 *
835 * This will mainly set up $TCA through extMgm API.
836 *
837 * @param bool $allowCaching True, if loading TCA from cache is allowed
838 * @return Bootstrap
839 * @internal This is not a public API method, do not use in own extensions
840 */
841 public function loadBaseTca(bool $allowCaching = true): Bootstrap
842 {
843 ExtensionManagementUtility::loadBaseTca($allowCaching);
844 return $this;
845 }
846
847 /**
848 * Load ext_tables and friends.
849 *
850 * This will mainly load and execute ext_tables.php files of loaded extensions
851 * or the according cache file if exists.
852 *
853 * @param bool $allowCaching True, if reading compiled ext_tables file from cache is allowed
854 * @return Bootstrap
855 * @internal This is not a public API method, do not use in own extensions
856 */
857 public function loadExtTables(bool $allowCaching = true): Bootstrap
858 {
859 ExtensionManagementUtility::loadExtTables($allowCaching);
860 $this->runExtTablesPostProcessingHooks();
861 return $this;
862 }
863
864 /**
865 * Check for registered ext tables hooks and run them
866 *
867 * @throws \UnexpectedValueException
868 */
869 protected function runExtTablesPostProcessingHooks()
870 {
871 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['extTablesInclusion-PostProcessing'])) {
872 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['extTablesInclusion-PostProcessing'] as $className) {
873 /** @var $hookObject \TYPO3\CMS\Core\Database\TableConfigurationPostProcessingHookInterface */
874 $hookObject = GeneralUtility::makeInstance($className);
875 if (!$hookObject instanceof \TYPO3\CMS\Core\Database\TableConfigurationPostProcessingHookInterface) {
876 throw new \UnexpectedValueException(
877 '$hookObject "' . $className . '" must implement interface TYPO3\\CMS\\Core\\Database\\TableConfigurationPostProcessingHookInterface',
878 1320585902
879 );
880 }
881 $hookObject->processData();
882 }
883 }
884 }
885
886 /**
887 * Initialize the Routing for the TYPO3 Backend
888 * Loads all routes registered inside all packages and stores them inside the Router
889 *
890 * @return Bootstrap
891 * @internal This is not a public API method, do not use in own extensions
892 */
893 public function initializeBackendRouter()
894 {
895 // See if the Routes.php from all active packages have been built together already
896 $cacheIdentifier = 'BackendRoutesFromPackages_' . sha1((TYPO3_version . PATH_site . 'BackendRoutesFromPackages'));
897
898 /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
899 $codeCache = $this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('cache_core');
900 $routesFromPackages = [];
901 if ($codeCache->has($cacheIdentifier)) {
902 // substr is necessary, because the php frontend wraps php code around the cache value
903 $routesFromPackages = unserialize(substr($codeCache->get($cacheIdentifier), 6, -2));
904 } else {
905 // Loop over all packages and check for a Configuration/Backend/Routes.php file
906 $packageManager = $this->getEarlyInstance(\TYPO3\CMS\Core\Package\PackageManager::class);
907 $packages = $packageManager->getActivePackages();
908 foreach ($packages as $package) {
909 $routesFileNameForPackage = $package->getPackagePath() . 'Configuration/Backend/Routes.php';
910 if (file_exists($routesFileNameForPackage)) {
911 $definedRoutesInPackage = require $routesFileNameForPackage;
912 if (is_array($definedRoutesInPackage)) {
913 $routesFromPackages = array_merge($routesFromPackages, $definedRoutesInPackage);
914 }
915 }
916 $routesFileNameForPackage = $package->getPackagePath() . 'Configuration/Backend/AjaxRoutes.php';
917 if (file_exists($routesFileNameForPackage)) {
918 $definedRoutesInPackage = require $routesFileNameForPackage;
919 if (is_array($definedRoutesInPackage)) {
920 foreach ($definedRoutesInPackage as $routeIdentifier => $routeOptions) {
921 // prefix the route with "ajax_" as "namespace"
922 $routeOptions['path'] = '/ajax' . $routeOptions['path'];
923 $routesFromPackages['ajax_' . $routeIdentifier] = $routeOptions;
924 $routesFromPackages['ajax_' . $routeIdentifier]['ajax'] = true;
925 }
926 }
927 }
928 }
929 // Store the data from all packages in the cache
930 $codeCache->set($cacheIdentifier, serialize($routesFromPackages));
931 }
932
933 // Build Route objects from the data
934 $router = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\Router::class);
935 foreach ($routesFromPackages as $name => $options) {
936 $path = $options['path'];
937 unset($options['path']);
938 $route = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\Route::class, $path, $options);
939 $router->addRoute($name, $route);
940 }
941 return $this;
942 }
943
944 /**
945 * Initialize backend user object in globals
946 *
947 * @param string $className usually \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::class but can be used for CLI
948 * @return Bootstrap
949 * @internal This is not a public API method, do not use in own extensions
950 */
951 public function initializeBackendUser($className = \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::class)
952 {
953 /** @var $backendUser \TYPO3\CMS\Core\Authentication\BackendUserAuthentication */
954 $backendUser = GeneralUtility::makeInstance($className);
955 // The global must be available very early, because methods below
956 // might trigger code which relies on it. See: #45625
957 $GLOBALS['BE_USER'] = $backendUser;
958 $backendUser->start();
959 return $this;
960 }
961
962 /**
963 * Initializes and ensures authenticated access
964 *
965 * @internal This is not a public API method, do not use in own extensions
966 * @param bool $proceedIfNoUserIsLoggedIn if set to TRUE, no forced redirect to the login page will be done
967 * @return \TYPO3\CMS\Core\Core\Bootstrap
968 */
969 public function initializeBackendAuthentication($proceedIfNoUserIsLoggedIn = false)
970 {
971 $GLOBALS['BE_USER']->backendCheckLogin($proceedIfNoUserIsLoggedIn);
972 return $this;
973 }
974
975 /**
976 * Initialize language object
977 *
978 * @return Bootstrap
979 * @internal This is not a public API method, do not use in own extensions
980 */
981 public function initializeLanguageObject()
982 {
983 /** @var $GLOBALS['LANG'] \TYPO3\CMS\Lang\LanguageService */
984 $GLOBALS['LANG'] = GeneralUtility::makeInstance(\TYPO3\CMS\Lang\LanguageService::class);
985 $GLOBALS['LANG']->init($GLOBALS['BE_USER']->uc['lang']);
986 return $this;
987 }
988
989 /**
990 * Throw away all output that may have happened during bootstrapping by weird extensions
991 *
992 * @return Bootstrap
993 * @internal This is not a public API method, do not use in own extensions
994 */
995 public function endOutputBufferingAndCleanPreviousOutput()
996 {
997 ob_clean();
998 return $this;
999 }
1000
1001 /**
1002 * Initialize output compression if configured
1003 *
1004 * @return Bootstrap
1005 * @internal This is not a public API method, do not use in own extensions
1006 */
1007 public function initializeOutputCompression()
1008 {
1009 if (extension_loaded('zlib') && $GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel']) {
1010 if (MathUtility::canBeInterpretedAsInteger($GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel'])) {
1011 @ini_set('zlib.output_compression_level', $GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel']);
1012 }
1013 ob_start('ob_gzhandler');
1014 }
1015 return $this;
1016 }
1017
1018 /**
1019 * Send HTTP headers if configured
1020 *
1021 * @return Bootstrap
1022 * @internal This is not a public API method, do not use in own extensions
1023 */
1024 public function sendHttpHeaders()
1025 {
1026 if (!empty($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers']) && is_array($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers'])) {
1027 foreach ($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers'] as $header) {
1028 header($header);
1029 }
1030 }
1031 return $this;
1032 }
1033
1034 /**
1035 * Things that should be performed to shut down the framework.
1036 * This method is called in all important scripts for a clean
1037 * shut down of the system.
1038 *
1039 * @return Bootstrap
1040 * @internal This is not a public API method, do not use in own extensions
1041 */
1042 public function shutdown()
1043 {
1044 $this->sendResponse();
1045 return $this;
1046 }
1047
1048 /**
1049 * Provides an instance of "template" for backend-modules to
1050 * work with.
1051 *
1052 * @return Bootstrap
1053 * @internal This is not a public API method, do not use in own extensions
1054 */
1055 public function initializeBackendTemplate()
1056 {
1057 $GLOBALS['TBE_TEMPLATE'] = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Template\DocumentTemplate::class);
1058 return $this;
1059 }
1060 }