[!!!][TASK] Remove last usages of $GLOBALS[T3_VAR]
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Core / SystemEnvironmentBuilder.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\GeneralUtility;
18 use TYPO3\CMS\Core\Utility\PathUtility;
19
20 /**
21 * Class to encapsulate base setup of bootstrap.
22 *
23 * This class contains all code that must be executed by every entry script.
24 *
25 * It sets up all basic paths, constants, global variables and checks
26 * the basic environment TYPO3 runs in.
27 *
28 * This class does not use any TYPO3 instance specific configuration, it only
29 * sets up things based on the server environment and core code. Even with a
30 * missing typo3conf/localconf.php this script will be successful.
31 *
32 * The script aborts execution with an error message if
33 * some part fails or conditions are not met.
34 *
35 * This script is internal code and subject to change.
36 * DO NOT use it in own code, or be prepared your code might
37 * break in future versions of the core.
38 */
39 class SystemEnvironmentBuilder
40 {
41 /** @internal */
42 const REQUESTTYPE_FE = 1;
43 /** @internal */
44 const REQUESTTYPE_BE = 2;
45 /** @internal */
46 const REQUESTTYPE_CLI = 4;
47 /** @internal */
48 const REQUESTTYPE_AJAX = 8;
49 /** @internal */
50 const REQUESTTYPE_INSTALL = 16;
51
52 /**
53 * A list of supported CGI server APIs
54 * NOTICE: This is a duplicate of the SAME array in GeneralUtility!
55 * It is duplicated here as this information is needed early in bootstrap
56 * and GeneralUtility is not available yet.
57 * @var array
58 */
59 protected static $supportedCgiServerApis = [
60 'fpm-fcgi',
61 'cgi',
62 'isapi',
63 'cgi-fcgi',
64 'srv', // HHVM with fastcgi
65 ];
66
67 /**
68 * An array of disabled methods
69 *
70 * @var string[]
71 */
72 protected static $disabledFunctions;
73
74 /**
75 * Run base setup.
76 * This entry method is used in all scopes (FE, BE, eid, ajax, ...)
77 *
78 * @internal This method should not be used by 3rd party code. It will change without further notice.
79 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
80 * @param int $requestType
81 */
82 public static function run(int $entryPointLevel = 0, int $requestType = self::REQUESTTYPE_FE)
83 {
84 self::defineBaseConstants();
85 self::defineTypo3RequestTypes();
86 self::setRequestType($requestType | ($requestType === self::REQUESTTYPE_BE && strpos($_REQUEST['route'] ?? '', '/ajax/') === 0 ? TYPO3_REQUESTTYPE_AJAX : 0));
87 self::defineLegacyConstants($requestType === self::REQUESTTYPE_FE ? 'FE' : 'BE');
88 $scriptPath = self::calculateScriptPath($entryPointLevel, $requestType);
89 $rootPath = self::calculateRootPath($entryPointLevel, $requestType);
90
91 self::initializeGlobalVariables();
92 self::initializeGlobalTimeTrackingVariables();
93 self::initializeBasicErrorReporting();
94
95 $applicationContext = static::createApplicationContext();
96 self::initializeEnvironment($applicationContext, $requestType, $scriptPath, $rootPath);
97 GeneralUtility::presetApplicationContext($applicationContext);
98 }
99
100 protected static function createApplicationContext(): ApplicationContext
101 {
102 $applicationContext = getenv('TYPO3_CONTEXT') ?: (getenv('REDIRECT_TYPO3_CONTEXT') ?: 'Production');
103
104 return new ApplicationContext($applicationContext);
105 }
106
107 /**
108 * Define all simple constants that have no dependency to local configuration
109 */
110 protected static function defineBaseConstants()
111 {
112 // Check one of the constants and return early if already defined,
113 // needed if multiple requests are handled in one process, for instance in functional testing.
114 if (defined('TYPO3_version')) {
115 return;
116 }
117
118 // This version, branch and copyright
119 define('TYPO3_version', '10.0.0-dev');
120 define('TYPO3_branch', '10.0');
121 define('TYPO3_copyright_year', '1998-' . date('Y'));
122
123 // TYPO3 external links
124 define('TYPO3_URL_GENERAL', 'https://typo3.org/');
125 define('TYPO3_URL_LICENSE', 'https://typo3.org/typo3-cms/overview/licenses/');
126 define('TYPO3_URL_EXCEPTION', 'https://typo3.org/go/exception/CMS/');
127 define('TYPO3_URL_DONATE', 'https://typo3.org/community/contribute/donate/');
128 define('TYPO3_URL_WIKI_OPCODECACHE', 'https://wiki.typo3.org/Opcode_Cache');
129
130 // A linefeed, a carriage return, a CR-LF combination
131 defined('LF') ?: define('LF', chr(10));
132 defined('CR') ?: define('CR', chr(13));
133 defined('CRLF') ?: define('CRLF', CR . LF);
134
135 // Security related constant: Default value of fileDenyPattern
136 define('FILE_DENY_PATTERN_DEFAULT', '\\.(php[3-7]?|phpsh|phtml|pht|phar|shtml|cgi)(\\..*)?$|\\.pl$|^\\.htaccess$');
137 // Security related constant: List of file extensions that should be registered as php script file extensions
138 define('PHP_EXTENSIONS_DEFAULT', 'php,php3,php4,php5,php6,php7,phpsh,inc,phtml,pht,phar');
139
140 // Relative path from document root to typo3/ directory, hardcoded to "typo3/"
141 if (!defined('TYPO3_mainDir')) {
142 define('TYPO3_mainDir', 'typo3/');
143 }
144 }
145
146 /**
147 * Calculate script path. This is the absolute path to the entry script.
148 * Can be something like '.../public/index.php' or '.../public/typo3/index.php' for
149 * web calls, or '.../bin/typo3' or similar for cli calls.
150 *
151 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
152 * @param int $requestType
153 * @return string Absolute path to entry script
154 */
155 protected static function calculateScriptPath(int $entryPointLevel, int $requestType): string
156 {
157 $isCli = self::isCliRequestType($requestType);
158 // Absolute path of the entry script that was called
159 $scriptPath = GeneralUtility::fixWindowsFilePath(self::getPathThisScript($isCli));
160 $rootPath = self::getRootPathFromScriptPath($scriptPath, $entryPointLevel);
161 // Check if the root path has been set in the environment (e.g. by the composer installer)
162 if (getenv('TYPO3_PATH_ROOT')) {
163 if ($isCli && self::usesComposerClassLoading()) {
164 // $scriptPath is used for various path calculations based on the document root
165 // Therefore we assume it is always a subdirectory of the document root, which is not the case
166 // in composer mode on cli, as the binary is in the composer bin directory.
167 // Because of that, we enforce the document root path of this binary to be set
168 $scriptName = 'typo3/sysext/core/bin/typo3';
169 } else {
170 // Base the script path on the path taken from the environment
171 // to make relative path calculations work in case only one of both is symlinked
172 // or has the real path
173 $scriptName = ltrim(substr($scriptPath, strlen($rootPath)), '/');
174 }
175 $rootPath = rtrim(GeneralUtility::fixWindowsFilePath(getenv('TYPO3_PATH_ROOT')), '/');
176 $scriptPath = $rootPath . '/' . $scriptName;
177 }
178 return $scriptPath;
179 }
180
181 /**
182 * Absolute path to the root of the typo3 instance. This is often identical to the web document root path (eg. .../public),
183 * but may be different. For instance helhum/typo3-secure-web uses this: Then, rootPath TYPO3_PATH_ROOT is the absolute path to
184 * the private directory where code and runtime files are located (currently typo3/ext, typo3/sysext, fileadmin, typo3temp),
185 * while TYPO3_PATH_WEB is the public/ web document folder that gets assets like filedamin and Resources/Public folders
186 * from extensions linked in.
187 *
188 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
189 * @param int $requestType
190 * @return string Absolute path without trailing slash
191 */
192 protected static function calculateRootPath(int $entryPointLevel, int $requestType): string
193 {
194 // Check if the root path has been set in the environment (e.g. by the composer installer)
195 if (getenv('TYPO3_PATH_ROOT')) {
196 return rtrim(GeneralUtility::fixWindowsFilePath(getenv('TYPO3_PATH_ROOT')), '/');
197 }
198 $isCli = self::isCliRequestType($requestType);
199 // Absolute path of the entry script that was called
200 $scriptPath = GeneralUtility::fixWindowsFilePath(self::getPathThisScript($isCli));
201 return self::getRootPathFromScriptPath($scriptPath, $entryPointLevel);
202 }
203
204 /**
205 * Set up / initialize several globals variables
206 */
207 protected static function initializeGlobalVariables()
208 {
209 // Unset variable(s) in global scope (security issue #13959)
210 $GLOBALS['T3_SERVICES'] = [];
211 }
212
213 /**
214 * Initialize global time tracking variables.
215 * These are helpers to for example output script parsetime at the end of a script.
216 */
217 protected static function initializeGlobalTimeTrackingVariables()
218 {
219 // EXEC_TIME is set so that the rest of the script has a common value for the script execution time
220 $GLOBALS['EXEC_TIME'] = time();
221 // $ACCESS_TIME is a common time in minutes for access control
222 $GLOBALS['ACCESS_TIME'] = $GLOBALS['EXEC_TIME'] - $GLOBALS['EXEC_TIME'] % 60;
223 // $SIM_EXEC_TIME is set to $EXEC_TIME but can be altered later in the script if we want to
224 // simulate another execution-time when selecting from eg. a database
225 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
226 // If $SIM_EXEC_TIME is changed this value must be set accordingly
227 $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
228 }
229
230 /**
231 * Initialize the Environment class
232 *
233 * @param ApplicationContext $context
234 * @param int $requestType
235 * @param string $scriptPath
236 * @param string $sitePath
237 */
238 protected static function initializeEnvironment(ApplicationContext $context, int $requestType, string $scriptPath, string $sitePath)
239 {
240 if (getenv('TYPO3_PATH_ROOT')) {
241 $rootPathFromEnvironment = rtrim(GeneralUtility::fixWindowsFilePath(getenv('TYPO3_PATH_ROOT')), '/');
242 if ($sitePath !== $rootPathFromEnvironment) {
243 // This means, that we re-initialized the environment during a single request
244 // This currently only happens in custom code or during functional testing
245 // Once the constants are removed, we might be able to remove this code here as well and directly pass an environment to the application
246 $scriptPath = $rootPathFromEnvironment . substr($scriptPath, strlen($sitePath));
247 $sitePath = $rootPathFromEnvironment;
248 }
249 }
250
251 $projectRootPath = GeneralUtility::fixWindowsFilePath(getenv('TYPO3_PATH_APP'));
252 $isDifferentRootPath = ($projectRootPath && $projectRootPath !== $sitePath);
253 Environment::initialize(
254 $context,
255 self::isCliRequestType($requestType),
256 self::usesComposerClassLoading(),
257 $isDifferentRootPath ? $projectRootPath : $sitePath,
258 $sitePath,
259 $isDifferentRootPath ? $projectRootPath . '/var' : $sitePath . '/typo3temp/var',
260 $isDifferentRootPath ? $projectRootPath . '/config' : $sitePath . '/typo3conf',
261 $scriptPath,
262 self::getTypo3Os() === 'WIN' ? 'WINDOWS' : 'UNIX'
263 );
264 }
265
266 /**
267 * Initialize basic error reporting.
268 *
269 * There are a lot of extensions that have no strict / notice / deprecated free
270 * ext_localconf or ext_tables. Since the final error reporting must be set up
271 * after those extension files are read, a default configuration is needed to
272 * suppress error reporting meanwhile during further bootstrap.
273 */
274 protected static function initializeBasicErrorReporting()
275 {
276 // Core should be notice free at least until this point ...
277 error_reporting(E_ALL & ~(E_STRICT | E_NOTICE | E_DEPRECATED));
278 }
279
280 /**
281 * Determine the operating system TYPO3 is running on.
282 *
283 * @return string Either 'WIN' if running on Windows, else empty string
284 */
285 protected static function getTypo3Os()
286 {
287 $typoOs = '';
288 if (!stristr(PHP_OS, 'darwin') && !stristr(PHP_OS, 'cygwin') && stristr(PHP_OS, 'win')) {
289 $typoOs = 'WIN';
290 }
291 return $typoOs;
292 }
293
294 /**
295 * Calculate script path.
296 *
297 * First step in path calculation: Goal is to find the absolute path of the entry script
298 * that was called without resolving any links. This is important since the TYPO3 entry
299 * points are often linked to a central core location, so we can not use the php magic
300 * __FILE__ here, but resolve the called script path from given server environments.
301 *
302 * This path is important to calculate the document root. The strategy is to
303 * find out the script name that was called in the first place and to subtract the local
304 * part from it to find the document root.
305 *
306 * @param bool $isCli
307 * @return string Absolute path to entry script
308 */
309 protected static function getPathThisScript(bool $isCli)
310 {
311 if ($isCli) {
312 return self::getPathThisScriptCli();
313 }
314 return self::getPathThisScriptNonCli();
315 }
316
317 /**
318 * Calculate path to entry script if not in cli mode.
319 *
320 * Depending on the environment, the script path is found in different $_SERVER variables.
321 *
322 * @return string Absolute path to entry script
323 */
324 protected static function getPathThisScriptNonCli()
325 {
326 $cgiPath = '';
327 if (isset($_SERVER['ORIG_PATH_TRANSLATED'])) {
328 $cgiPath = $_SERVER['ORIG_PATH_TRANSLATED'];
329 } elseif (isset($_SERVER['PATH_TRANSLATED'])) {
330 $cgiPath = $_SERVER['PATH_TRANSLATED'];
331 }
332 if ($cgiPath && in_array(PHP_SAPI, self::$supportedCgiServerApis, true)) {
333 $scriptPath = $cgiPath;
334 } else {
335 if (isset($_SERVER['ORIG_SCRIPT_FILENAME'])) {
336 $scriptPath = $_SERVER['ORIG_SCRIPT_FILENAME'];
337 } else {
338 $scriptPath = $_SERVER['SCRIPT_FILENAME'];
339 }
340 }
341 return $scriptPath;
342 }
343
344 /**
345 * Calculate path to entry script if in cli mode.
346 *
347 * First argument of a cli script is the path to the script that was called. If the script does not start
348 * with / (or A:\ for Windows), the path is not absolute yet, and the current working directory is added.
349 *
350 * @return string Absolute path to entry script
351 */
352 protected static function getPathThisScriptCli()
353 {
354 // Possible relative path of the called script
355 if (isset($_SERVER['argv'][0])) {
356 $scriptPath = $_SERVER['argv'][0];
357 } elseif (isset($_ENV['_'])) {
358 $scriptPath = $_ENV['_'];
359 } else {
360 $scriptPath = $_SERVER['_'];
361 }
362 // Find out if path is relative or not
363 $isRelativePath = false;
364 if (self::getTypo3Os() === 'WIN') {
365 if (!preg_match('/^([a-zA-Z]:)?\\\\/', $scriptPath)) {
366 $isRelativePath = true;
367 }
368 } else {
369 if ($scriptPath[0] !== '/') {
370 $isRelativePath = true;
371 }
372 }
373 // Concatenate path to current working directory with relative path and remove "/./" constructs
374 if ($isRelativePath) {
375 if (isset($_SERVER['PWD'])) {
376 $workingDirectory = $_SERVER['PWD'];
377 } else {
378 $workingDirectory = getcwd();
379 }
380 $scriptPath = $workingDirectory . '/' . preg_replace('/\\.\\//', '', $scriptPath);
381 }
382 return $scriptPath;
383 }
384
385 /**
386 * Calculate the document root part to the instance from $scriptPath.
387 * This is based on the amount of subdirectories "under" root path where $scriptPath is located.
388 *
389 * The following main scenarios for entry points exist by default in the TYPO3 core:
390 * - Directly called documentRoot/index.php (-> FE call or eiD include): index.php is located in the same directory
391 * as the main project. The document root is identical to the directory the script is located at.
392 * - The install tool, located under typo3/install.php.
393 * - A Backend script: This is the case for the typo3/index.php dispatcher and other entry scripts like 'typo3/sysext/core/bin/typo3'
394 * or 'typo3/index.php' that are located inside typo3/ directly.
395 *
396 * @param string $scriptPath Calculated path to the entry script
397 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
398 * @return string Absolute path to document root of installation without trailing slash
399 */
400 protected static function getRootPathFromScriptPath($scriptPath, $entryPointLevel)
401 {
402 $entryScriptDirectory = PathUtility::dirnameDuringBootstrap($scriptPath);
403 if ($entryPointLevel > 0) {
404 list($rootPath) = GeneralUtility::revExplode('/', $entryScriptDirectory, $entryPointLevel + 1);
405 } else {
406 $rootPath = $entryScriptDirectory;
407 }
408 return $rootPath;
409 }
410
411 /**
412 * Send http headers, echo out a text message and exit with error code
413 *
414 * @param string $message
415 */
416 protected static function exitWithMessage($message)
417 {
418 $headers = [
419 \TYPO3\CMS\Core\Utility\HttpUtility::HTTP_STATUS_500,
420 'Content-Type: text/plain'
421 ];
422 if (!headers_sent()) {
423 foreach ($headers as $header) {
424 header($header);
425 }
426 }
427 echo $message . LF;
428 exit(1);
429 }
430
431 /**
432 * Check if the given function is disabled in the system
433 *
434 * @param string $function
435 * @return bool
436 */
437 public static function isFunctionDisabled($function)
438 {
439 if (static::$disabledFunctions === null) {
440 static::$disabledFunctions = GeneralUtility::trimExplode(',', ini_get('disable_functions'));
441 }
442 if (!empty(static::$disabledFunctions)) {
443 return in_array($function, static::$disabledFunctions, true);
444 }
445
446 return false;
447 }
448
449 /**
450 * @return bool
451 */
452 protected static function usesComposerClassLoading(): bool
453 {
454 return defined('TYPO3_COMPOSER_MODE') && TYPO3_COMPOSER_MODE;
455 }
456
457 /**
458 * Define TYPO3_REQUESTTYPE* constants that can be used for developers to see if any context has been hit
459 * also see setRequestType(). Is done at the very beginning so these parameters are always available.
460 */
461 protected static function defineTypo3RequestTypes()
462 {
463 // Check one of the constants and return early if already defined,
464 // needed if multiple requests are handled in one process, for instance in functional testing.
465 if (defined('TYPO3_REQUESTTYPE_FE')) {
466 return;
467 }
468 define('TYPO3_REQUESTTYPE_FE', self::REQUESTTYPE_FE);
469 define('TYPO3_REQUESTTYPE_BE', self::REQUESTTYPE_BE);
470 define('TYPO3_REQUESTTYPE_CLI', self::REQUESTTYPE_CLI);
471 define('TYPO3_REQUESTTYPE_AJAX', self::REQUESTTYPE_AJAX);
472 define('TYPO3_REQUESTTYPE_INSTALL', self::REQUESTTYPE_INSTALL);
473 }
474
475 /**
476 * Defines the TYPO3_REQUESTTYPE constant so the environment knows which context the request is running.
477 *
478 * @param int $requestType
479 */
480 protected static function setRequestType(int $requestType)
481 {
482 // Return early if already defined,
483 // needed if multiple requests are handled in one process, for instance in functional testing.
484 if (defined('TYPO3_REQUESTTYPE')) {
485 return;
486 }
487 define('TYPO3_REQUESTTYPE', $requestType);
488 }
489
490 /**
491 * Define constants and variables
492 *
493 * @param string
494 */
495 protected static function defineLegacyConstants(string $mode)
496 {
497 // Return early if already defined,
498 // needed if multiple requests are handled in one process, for instance in functional testing.
499 if (defined('TYPO3_MODE')) {
500 return;
501 }
502 define('TYPO3_MODE', $mode);
503 }
504
505 /**
506 * Checks if request type is cli.
507 * Falls back to check PHP_SAPI in case request type is not provided
508 *
509 * @param int|null $requestType
510 * @return bool
511 */
512 protected static function isCliRequestType(?int $requestType): bool
513 {
514 if ($requestType === null) {
515 $requestType = PHP_SAPI === 'cli' ? self::REQUESTTYPE_CLI : self::REQUESTTYPE_FE;
516 }
517
518 return ($requestType & self::REQUESTTYPE_CLI) === self::REQUESTTYPE_CLI;
519 }
520 }