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