[!!!][TASK] Remove global variable PARSETIME_START
[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\StringUtility;
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 /**
42 * A list of supported CGI server APIs
43 * NOTICE: This is a duplicate of the SAME array in GeneralUtility!
44 * It is duplicated here as this information is needed early in bootstrap
45 * and GeneralUtility is not available yet.
46 * @var array
47 */
48 protected static $supportedCgiServerApis = [
49 'fpm-fcgi',
50 'cgi',
51 'isapi',
52 'cgi-fcgi',
53 'srv', // HHVM with fastcgi
54 ];
55
56 /**
57 * An array of disabled methods
58 *
59 * @var string[]
60 */
61 protected static $disabledFunctions = null;
62
63 /**
64 * Run base setup.
65 * This entry method is used in all scopes (FE, BE, eid, ajax, ...)
66 *
67 * @internal This method should not be used by 3rd party code. It will change without further notice.
68 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
69 */
70 public static function run($entryPointLevel = 0)
71 {
72 self::defineBaseConstants();
73 self::definePaths($entryPointLevel);
74 self::checkMainPathsExist();
75 self::initializeGlobalVariables();
76 self::initializeGlobalTimeTrackingVariables();
77 self::initializeBasicErrorReporting();
78 }
79
80 /**
81 * Define all simple constants that have no dependency to local configuration
82 */
83 protected static function defineBaseConstants()
84 {
85 // This version, branch and copyright
86 define('TYPO3_version', '9.0.0-dev');
87 define('TYPO3_branch', '9.0');
88 define('TYPO3_copyright_year', '1998-2017');
89
90 // TYPO3 external links
91 define('TYPO3_URL_GENERAL', 'https://typo3.org/');
92 define('TYPO3_URL_LICENSE', 'https://typo3.org/typo3-cms/overview/licenses/');
93 define('TYPO3_URL_EXCEPTION', 'https://typo3.org/go/exception/CMS/');
94 define('TYPO3_URL_MAILINGLISTS', 'http://lists.typo3.org/cgi-bin/mailman/listinfo');
95 define('TYPO3_URL_DOCUMENTATION', 'https://typo3.org/documentation/');
96 define('TYPO3_URL_DOCUMENTATION_TSREF', 'https://docs.typo3.org/typo3cms/TyposcriptReference/');
97 define('TYPO3_URL_DOCUMENTATION_TSCONFIG', 'https://docs.typo3.org/typo3cms/TSconfigReference/');
98 define('TYPO3_URL_CONSULTANCY', 'https://typo3.org/support/professional-services/');
99 define('TYPO3_URL_CONTRIBUTE', 'https://typo3.org/contribute/');
100 define('TYPO3_URL_SECURITY', 'https://typo3.org/teams/security/');
101 define('TYPO3_URL_DOWNLOAD', 'https://typo3.org/download/');
102 define('TYPO3_URL_SYSTEMREQUIREMENTS', 'https://typo3.org/typo3-cms/overview/requirements/');
103 define('TYPO3_URL_DONATE', 'https://typo3.org/donate/online-donation/');
104 define('TYPO3_URL_WIKI_OPCODECACHE', 'https://wiki.typo3.org/Opcode_Cache');
105
106 // A null, a tabulator, a linefeed, a carriage return, a substitution, a CR-LF combination
107 defined('NUL') ?: define('NUL', chr(0));
108 defined('TAB') ?: define('TAB', chr(9));
109 defined('LF') ?: define('LF', chr(10));
110 defined('CR') ?: define('CR', chr(13));
111 defined('SUB') ?: define('SUB', chr(26));
112 defined('CRLF') ?: define('CRLF', CR . LF);
113
114 // Security related constant: Default value of fileDenyPattern
115 define('FILE_DENY_PATTERN_DEFAULT', '\\.(php[3-7]?|phpsh|phtml|pht)(\\..*)?$|^\\.htaccess$');
116 // Security related constant: List of file extensions that should be registered as php script file extensions
117 define('PHP_EXTENSIONS_DEFAULT', 'php,php3,php4,php5,php6,php7,phpsh,inc,phtml,pht');
118
119 // Operating system identifier
120 // Either "WIN" or empty string
121 defined('TYPO3_OS') ?: define('TYPO3_OS', self::getTypo3Os());
122
123 // Service error constants
124 // General error - something went wrong
125 define('T3_ERR_SV_GENERAL', -1);
126 // During execution it showed that the service is not available and should be ignored. The service itself should call $this->setNonAvailable()
127 define('T3_ERR_SV_NOT_AVAIL', -2);
128 // Passed subtype is not possible with this service
129 define('T3_ERR_SV_WRONG_SUBTYPE', -3);
130 // Passed subtype is not possible with this service
131 define('T3_ERR_SV_NO_INPUT', -4);
132 // File not found which the service should process
133 define('T3_ERR_SV_FILE_NOT_FOUND', -20);
134 // File not readable
135 define('T3_ERR_SV_FILE_READ', -21);
136 // File not writable
137 define('T3_ERR_SV_FILE_WRITE', -22);
138 // Passed subtype is not possible with this service
139 define('T3_ERR_SV_PROG_NOT_FOUND', -40);
140 // Passed subtype is not possible with this service
141 define('T3_ERR_SV_PROG_FAILED', -41);
142 }
143
144 /**
145 * Calculate all required base paths and set as constants.
146 *
147 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
148 */
149 protected static function definePaths($entryPointLevel = 0)
150 {
151 // Absolute path of the entry script that was called
152 $scriptPath = GeneralUtility::fixWindowsFilePath(self::getPathThisScript());
153 $rootPath = self::getRootPathFromScriptPath($scriptPath, $entryPointLevel);
154 // Check if the root path has been set in the environment (e.g. by the composer installer)
155 if (getenv('TYPO3_PATH_ROOT')) {
156 if ((TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI)
157 && Bootstrap::usesComposerClassLoading()
158 && StringUtility::endsWith($scriptPath, 'typo3')
159 ) {
160 // PATH_thisScript is used for various path calculations based on the document root
161 // Therefore we assume it is always a subdirectory of the document root, which is not the case
162 // in composer mode on cli, as the binary is in the composer bin directory.
163 // Because of that, we enforce the document root path of this binary to be set
164 $scriptName = '/typo3/sysext/core/bin/typo3';
165 } else {
166 // Base the script path on the path taken from the environment
167 // to make relative path calculations work in case only one of both is symlinked
168 // or has the real path
169 $scriptName = substr($scriptPath, strlen($rootPath));
170 }
171 $rootPath = GeneralUtility::fixWindowsFilePath(getenv('TYPO3_PATH_ROOT'));
172 $scriptPath = $rootPath . $scriptName;
173 }
174
175 if (!defined('PATH_thisScript')) {
176 define('PATH_thisScript', $scriptPath);
177 }
178 // Absolute path of the document root of the instance with trailing slash
179 if (!defined('PATH_site')) {
180 define('PATH_site', $rootPath . '/');
181 }
182 // Relative path from document root to typo3/ directory
183 // Hardcoded to "typo3/"
184 define('TYPO3_mainDir', 'typo3/');
185 // Absolute path of the typo3 directory of the instance with trailing slash
186 // Example "/var/www/instance-name/htdocs/typo3/"
187 define('PATH_typo3', PATH_site . TYPO3_mainDir);
188 // Absolute path to the typo3conf directory with trailing slash
189 // Example "/var/www/instance-name/htdocs/typo3conf/"
190 define('PATH_typo3conf', PATH_site . 'typo3conf/');
191 }
192
193 /**
194 * Check if path and script file name calculation was successful, exit if not.
195 */
196 protected static function checkMainPathsExist()
197 {
198 if (!is_file(PATH_thisScript)) {
199 static::exitWithMessage('Unable to determine path to entry script.');
200 }
201 }
202
203 /**
204 * Set up / initialize several globals variables
205 */
206 protected static function initializeGlobalVariables()
207 {
208 // Unset variable(s) in global scope (security issue #13959)
209 $GLOBALS['TYPO3_MISC'] = [];
210 $GLOBALS['T3_VAR'] = [];
211 $GLOBALS['T3_SERVICES'] = [];
212 }
213
214 /**
215 * Initialize global time tracking variables.
216 * These are helpers to for example output script parsetime at the end of a script.
217 */
218 protected static function initializeGlobalTimeTrackingVariables()
219 {
220 // Microtime of (nearly) script start
221 $GLOBALS['TYPO3_MISC']['microtime_start'] = microtime(true);
222 // EXEC_TIME is set so that the rest of the script has a common value for the script execution time
223 $GLOBALS['EXEC_TIME'] = time();
224 // $ACCESS_TIME is a common time in minutes for access control
225 $GLOBALS['ACCESS_TIME'] = $GLOBALS['EXEC_TIME'] - $GLOBALS['EXEC_TIME'] % 60;
226 // $SIM_EXEC_TIME is set to $EXEC_TIME but can be altered later in the script if we want to
227 // simulate another execution-time when selecting from eg. a database
228 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
229 // If $SIM_EXEC_TIME is changed this value must be set accordingly
230 $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
231 }
232
233 /**
234 * Initialize basic error reporting.
235 *
236 * There are a lot of extensions that have no strict / notice / deprecated free
237 * ext_localconf or ext_tables. Since the final error reporting must be set up
238 * after those extension files are read, a default configuration is needed to
239 * suppress error reporting meanwhile during further bootstrap.
240 */
241 protected static function initializeBasicErrorReporting()
242 {
243 // Core should be notice free at least until this point ...
244 error_reporting(E_ALL & ~(E_STRICT | E_NOTICE | E_DEPRECATED));
245 }
246
247 /**
248 * Determine the operating system TYPO3 is running on.
249 *
250 * @return string Either 'WIN' if running on Windows, else empty string
251 */
252 protected static function getTypo3Os()
253 {
254 $typoOs = '';
255 if (!stristr(PHP_OS, 'darwin') && !stristr(PHP_OS, 'cygwin') && stristr(PHP_OS, 'win')) {
256 $typoOs = 'WIN';
257 }
258 return $typoOs;
259 }
260
261 /**
262 * Calculate PATH_thisScript
263 *
264 * First step in path calculation: Goal is to find the absolute path of the entry script
265 * that was called without resolving any links. This is important since the TYPO3 entry
266 * points are often linked to a central core location, so we can not use the php magic
267 * __FILE__ here, but resolve the called script path from given server environments.
268 *
269 * This path is important to calculate the document root (PATH_site). The strategy is to
270 * find out the script name that was called in the first place and to subtract the local
271 * part from it to find the document root.
272 *
273 * @return string Absolute path to entry script
274 */
275 protected static function getPathThisScript()
276 {
277 if (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI) {
278 return self::getPathThisScriptCli();
279 }
280 return self::getPathThisScriptNonCli();
281 }
282
283 /**
284 * Calculate path to entry script if not in cli mode.
285 *
286 * Depending on the environment, the script path is found in different $_SERVER variables.
287 *
288 * @return string Absolute path to entry script
289 */
290 protected static function getPathThisScriptNonCli()
291 {
292 $cgiPath = '';
293 if (isset($_SERVER['ORIG_PATH_TRANSLATED'])) {
294 $cgiPath = $_SERVER['ORIG_PATH_TRANSLATED'];
295 } elseif (isset($_SERVER['PATH_TRANSLATED'])) {
296 $cgiPath = $_SERVER['PATH_TRANSLATED'];
297 }
298 if ($cgiPath && in_array(PHP_SAPI, self::$supportedCgiServerApis, true)) {
299 $scriptPath = $cgiPath;
300 } else {
301 if (isset($_SERVER['ORIG_SCRIPT_FILENAME'])) {
302 $scriptPath = $_SERVER['ORIG_SCRIPT_FILENAME'];
303 } else {
304 $scriptPath = $_SERVER['SCRIPT_FILENAME'];
305 }
306 }
307 return $scriptPath;
308 }
309
310 /**
311 * Calculate path to entry script if in cli mode.
312 *
313 * First argument of a cli script is the path to the script that was called. If the script does not start
314 * with / (or A:\ for Windows), the path is not absolute yet, and the current working directory is added.
315 *
316 * @return string Absolute path to entry script
317 */
318 protected static function getPathThisScriptCli()
319 {
320 // Possible relative path of the called script
321 if (isset($_SERVER['argv'][0])) {
322 $scriptPath = $_SERVER['argv'][0];
323 } elseif (isset($_ENV['_'])) {
324 $scriptPath = $_ENV['_'];
325 } else {
326 $scriptPath = $_SERVER['_'];
327 }
328 // Find out if path is relative or not
329 $isRelativePath = false;
330 if (TYPO3_OS === 'WIN') {
331 if (!preg_match('/^([a-zA-Z]:)?\\\\/', $scriptPath)) {
332 $isRelativePath = true;
333 }
334 } else {
335 if ($scriptPath[0] !== '/') {
336 $isRelativePath = true;
337 }
338 }
339 // Concatenate path to current working directory with relative path and remove "/./" constructs
340 if ($isRelativePath) {
341 if (isset($_SERVER['PWD'])) {
342 $workingDirectory = $_SERVER['PWD'];
343 } else {
344 $workingDirectory = getcwd();
345 }
346 $scriptPath = $workingDirectory . '/' . preg_replace('/\\.\\//', '', $scriptPath);
347 }
348 return $scriptPath;
349 }
350
351 /**
352 * Calculate the document root part to the instance from PATH_thisScript.
353 * This is based on the amount of subdirectories "under" PATH_site where PATH_thisScript is located.
354 *
355 * The following main scenarios for entry points exist by default in the TYPO3 core:
356 * - Directly called documentRoot/index.php (-> FE call or eiD include): index.php is located in the same directory
357 * as the main project. The document root is identical to the directory the script is located at.
358 * - The install tool, located under typo3/install.php.
359 * - A Backend script: This is the case for the typo3/index.php dispatcher and other entry scripts like 'typo3/sysext/core/bin/typo3'
360 * or 'typo3/index.php' that are located inside typo3/ directly.
361 *
362 * @param string $scriptPath Calculated path to the entry script
363 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
364 * @return string Absolute path to document root of installation
365 */
366 protected static function getRootPathFromScriptPath($scriptPath, $entryPointLevel)
367 {
368 $entryScriptDirectory = dirname($scriptPath);
369 if ($entryPointLevel > 0) {
370 list($rootPath) = GeneralUtility::revExplode('/', $entryScriptDirectory, $entryPointLevel + 1);
371 } else {
372 $rootPath = $entryScriptDirectory;
373 }
374 return $rootPath;
375 }
376
377 /**
378 * Send http headers, echo out a text message and exit with error code
379 *
380 * @param string $message
381 */
382 protected static function exitWithMessage($message)
383 {
384 $headers = [
385 \TYPO3\CMS\Core\Utility\HttpUtility::HTTP_STATUS_500,
386 'Content-Type: text/plain'
387 ];
388 if (!headers_sent()) {
389 foreach ($headers as $header) {
390 header($header);
391 }
392 }
393 echo $message . LF;
394 exit(1);
395 }
396
397 /**
398 * Check if the given function is disabled in the system
399 *
400 * @param string $function
401 * @return bool
402 */
403 public static function isFunctionDisabled($function)
404 {
405 if (static::$disabledFunctions === null) {
406 static::$disabledFunctions = GeneralUtility::trimExplode(',', ini_get('disable_functions'));
407 }
408 if (!empty(static::$disabledFunctions)) {
409 return in_array($function, static::$disabledFunctions, true);
410 }
411
412 return false;
413 }
414 }