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