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