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