[TASK] Functional tests without phpunit process isolation
[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/donate/online-donation/');
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 $isCli = PHP_SAPI === 'cli';
271 // Absolute path of the entry script that was called
272 $scriptPath = PATH_thisScript;
273 $rootPath = rtrim(PATH_site, '/');
274 if (getenv('TYPO3_PATH_ROOT')) {
275 $rootPath = GeneralUtility::fixWindowsFilePath(getenv('TYPO3_PATH_ROOT'));
276 $rootPath = rtrim($rootPath, '/');
277 // Check if the root path has been set in the environment (e.g. by the composer installer)
278 if ($isCli && self::usesComposerClassLoading() && StringUtility::endsWith($scriptPath, 'typo3')) {
279 // PATH_thisScript is used for various path calculations based on the document root
280 // Therefore we assume it is always a subdirectory of the document root, which is not the case
281 // in composer mode on cli, as the binary is in the composer bin directory.
282 // Because of that, we enforce the document root path of this binary to be set
283 $scriptName = '/typo3/sysext/core/bin/typo3';
284 } else {
285 // Base the script path on the path taken from the environment
286 // to make relative path calculations work in case only one of both is symlinked
287 // or has the real path
288 $scriptName = substr($scriptPath, strlen($rootPath));
289 }
290 $scriptPath = $rootPath . $scriptName;
291 }
292
293 $sitePath = rtrim($rootPath, '/');
294 $projectRootPath = GeneralUtility::fixWindowsFilePath(getenv('TYPO3_PATH_APP'));
295 $isDifferentRootPath = ($projectRootPath && $projectRootPath !== $sitePath);
296 Environment::initialize(
297 $context,
298 $isCli,
299 self::usesComposerClassLoading(),
300 $isDifferentRootPath ? $projectRootPath : $sitePath,
301 $sitePath,
302 $isDifferentRootPath ? $projectRootPath . '/var' : $sitePath . '/typo3temp/var',
303 $isDifferentRootPath ? $projectRootPath . '/config' : $sitePath . '/typo3conf',
304 $scriptPath,
305 self::getTypo3Os() === 'WIN' ? 'WINDOWS' : 'UNIX'
306 );
307 }
308
309 /**
310 * Initialize basic error reporting.
311 *
312 * There are a lot of extensions that have no strict / notice / deprecated free
313 * ext_localconf or ext_tables. Since the final error reporting must be set up
314 * after those extension files are read, a default configuration is needed to
315 * suppress error reporting meanwhile during further bootstrap.
316 */
317 protected static function initializeBasicErrorReporting()
318 {
319 // Core should be notice free at least until this point ...
320 error_reporting(E_ALL & ~(E_STRICT | E_NOTICE | E_DEPRECATED));
321 }
322
323 /**
324 * Determine the operating system TYPO3 is running on.
325 *
326 * @return string Either 'WIN' if running on Windows, else empty string
327 */
328 protected static function getTypo3Os()
329 {
330 $typoOs = '';
331 if (!stristr(PHP_OS, 'darwin') && !stristr(PHP_OS, 'cygwin') && stristr(PHP_OS, 'win')) {
332 $typoOs = 'WIN';
333 }
334 return $typoOs;
335 }
336
337 /**
338 * Calculate PATH_thisScript
339 *
340 * First step in path calculation: Goal is to find the absolute path of the entry script
341 * that was called without resolving any links. This is important since the TYPO3 entry
342 * points are often linked to a central core location, so we can not use the php magic
343 * __FILE__ here, but resolve the called script path from given server environments.
344 *
345 * This path is important to calculate the document root (PATH_site). The strategy is to
346 * find out the script name that was called in the first place and to subtract the local
347 * part from it to find the document root.
348 *
349 * @param bool $isCli
350 * @return string Absolute path to entry script
351 */
352 protected static function getPathThisScript(bool $isCli)
353 {
354 if ($isCli) {
355 return self::getPathThisScriptCli();
356 }
357 return self::getPathThisScriptNonCli();
358 }
359
360 /**
361 * Calculate path to entry script if not in cli mode.
362 *
363 * Depending on the environment, the script path is found in different $_SERVER variables.
364 *
365 * @return string Absolute path to entry script
366 */
367 protected static function getPathThisScriptNonCli()
368 {
369 $cgiPath = '';
370 if (isset($_SERVER['ORIG_PATH_TRANSLATED'])) {
371 $cgiPath = $_SERVER['ORIG_PATH_TRANSLATED'];
372 } elseif (isset($_SERVER['PATH_TRANSLATED'])) {
373 $cgiPath = $_SERVER['PATH_TRANSLATED'];
374 }
375 if ($cgiPath && in_array(PHP_SAPI, self::$supportedCgiServerApis, true)) {
376 $scriptPath = $cgiPath;
377 } else {
378 if (isset($_SERVER['ORIG_SCRIPT_FILENAME'])) {
379 $scriptPath = $_SERVER['ORIG_SCRIPT_FILENAME'];
380 } else {
381 $scriptPath = $_SERVER['SCRIPT_FILENAME'];
382 }
383 }
384 return $scriptPath;
385 }
386
387 /**
388 * Calculate path to entry script if in cli mode.
389 *
390 * First argument of a cli script is the path to the script that was called. If the script does not start
391 * with / (or A:\ for Windows), the path is not absolute yet, and the current working directory is added.
392 *
393 * @return string Absolute path to entry script
394 */
395 protected static function getPathThisScriptCli()
396 {
397 // Possible relative path of the called script
398 if (isset($_SERVER['argv'][0])) {
399 $scriptPath = $_SERVER['argv'][0];
400 } elseif (isset($_ENV['_'])) {
401 $scriptPath = $_ENV['_'];
402 } else {
403 $scriptPath = $_SERVER['_'];
404 }
405 // Find out if path is relative or not
406 $isRelativePath = false;
407 if (self::getTypo3Os() === 'WIN') {
408 if (!preg_match('/^([a-zA-Z]:)?\\\\/', $scriptPath)) {
409 $isRelativePath = true;
410 }
411 } else {
412 if ($scriptPath[0] !== '/') {
413 $isRelativePath = true;
414 }
415 }
416 // Concatenate path to current working directory with relative path and remove "/./" constructs
417 if ($isRelativePath) {
418 if (isset($_SERVER['PWD'])) {
419 $workingDirectory = $_SERVER['PWD'];
420 } else {
421 $workingDirectory = getcwd();
422 }
423 $scriptPath = $workingDirectory . '/' . preg_replace('/\\.\\//', '', $scriptPath);
424 }
425 return $scriptPath;
426 }
427
428 /**
429 * Calculate the document root part to the instance from PATH_thisScript.
430 * This is based on the amount of subdirectories "under" PATH_site where PATH_thisScript is located.
431 *
432 * The following main scenarios for entry points exist by default in the TYPO3 core:
433 * - Directly called documentRoot/index.php (-> FE call or eiD include): index.php is located in the same directory
434 * as the main project. The document root is identical to the directory the script is located at.
435 * - The install tool, located under typo3/install.php.
436 * - A Backend script: This is the case for the typo3/index.php dispatcher and other entry scripts like 'typo3/sysext/core/bin/typo3'
437 * or 'typo3/index.php' that are located inside typo3/ directly.
438 *
439 * @param string $scriptPath Calculated path to the entry script
440 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
441 * @return string Absolute path to document root of installation
442 */
443 protected static function getRootPathFromScriptPath($scriptPath, $entryPointLevel)
444 {
445 $entryScriptDirectory = PathUtility::dirnameDuringBootstrap($scriptPath);
446 if ($entryPointLevel > 0) {
447 list($rootPath) = GeneralUtility::revExplode('/', $entryScriptDirectory, $entryPointLevel + 1);
448 } else {
449 $rootPath = $entryScriptDirectory;
450 }
451 return $rootPath;
452 }
453
454 /**
455 * Send http headers, echo out a text message and exit with error code
456 *
457 * @param string $message
458 */
459 protected static function exitWithMessage($message)
460 {
461 $headers = [
462 \TYPO3\CMS\Core\Utility\HttpUtility::HTTP_STATUS_500,
463 'Content-Type: text/plain'
464 ];
465 if (!headers_sent()) {
466 foreach ($headers as $header) {
467 header($header);
468 }
469 }
470 echo $message . LF;
471 exit(1);
472 }
473
474 /**
475 * Check if the given function is disabled in the system
476 *
477 * @param string $function
478 * @return bool
479 */
480 public static function isFunctionDisabled($function)
481 {
482 if (static::$disabledFunctions === null) {
483 static::$disabledFunctions = GeneralUtility::trimExplode(',', ini_get('disable_functions'));
484 }
485 if (!empty(static::$disabledFunctions)) {
486 return in_array($function, static::$disabledFunctions, true);
487 }
488
489 return false;
490 }
491
492 /**
493 * @return bool
494 */
495 protected static function usesComposerClassLoading(): bool
496 {
497 return defined('TYPO3_COMPOSER_MODE') && TYPO3_COMPOSER_MODE;
498 }
499
500 /**
501 * Define TYPO3_REQUESTTYPE* constants that can be used for developers to see if any context has been hit
502 * also see setRequestType(). Is done at the very beginning so these parameters are always available.
503 */
504 protected static function defineTypo3RequestTypes()
505 {
506 if (defined('TYPO3_REQUESTTYPE_FE')) { // @todo remove once Bootstrap::getInstance() is dropped
507 return;
508 }
509 define('TYPO3_REQUESTTYPE_FE', self::REQUESTTYPE_FE);
510 define('TYPO3_REQUESTTYPE_BE', self::REQUESTTYPE_BE);
511 define('TYPO3_REQUESTTYPE_CLI', self::REQUESTTYPE_CLI);
512 define('TYPO3_REQUESTTYPE_AJAX', self::REQUESTTYPE_AJAX);
513 define('TYPO3_REQUESTTYPE_INSTALL', self::REQUESTTYPE_INSTALL);
514 }
515
516 /**
517 * Defines the TYPO3_REQUESTTYPE constant so the environment knows which context the request is running.
518 *
519 * @param int $requestType
520 */
521 protected static function setRequestType(int $requestType)
522 {
523 if (defined('TYPO3_REQUESTTYPE')) { // @todo remove once Bootstrap::getInstance() is dropped
524 return;
525 }
526 define('TYPO3_REQUESTTYPE', $requestType);
527 }
528
529 /**
530 * Define constants and variables
531 *
532 * @param string
533 */
534 protected static function defineLegacyConstants(string $mode)
535 {
536 if (defined('TYPO3_MODE')) { // @todo remove once Bootstrap::getInstance()
537 return;
538 }
539 define('TYPO3_MODE', $mode);
540 }
541 }