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