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