1467d2c7a20f7cbdad47983c50ad857b62810609
[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 // Set PARSETIME_START to the system time in milliseconds.
221 $GLOBALS['PARSETIME_START'] = GeneralUtility::milliseconds();
222 // Microtime of (nearly) script start
223 $GLOBALS['TYPO3_MISC']['microtime_start'] = microtime(true);
224 // EXEC_TIME is set so that the rest of the script has a common value for the script execution time
225 $GLOBALS['EXEC_TIME'] = time();
226 // $ACCESS_TIME is a common time in minutes for access control
227 $GLOBALS['ACCESS_TIME'] = $GLOBALS['EXEC_TIME'] - $GLOBALS['EXEC_TIME'] % 60;
228 // $SIM_EXEC_TIME is set to $EXEC_TIME but can be altered later in the script if we want to
229 // simulate another execution-time when selecting from eg. a database
230 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
231 // If $SIM_EXEC_TIME is changed this value must be set accordingly
232 $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
233 }
234
235 /**
236 * Initialize basic error reporting.
237 *
238 * There are a lot of extensions that have no strict / notice / deprecated free
239 * ext_localconf or ext_tables. Since the final error reporting must be set up
240 * after those extension files are read, a default configuration is needed to
241 * suppress error reporting meanwhile during further bootstrap.
242 */
243 protected static function initializeBasicErrorReporting()
244 {
245 // Core should be notice free at least until this point ...
246 error_reporting(E_ALL & ~(E_STRICT | E_NOTICE | E_DEPRECATED));
247 }
248
249 /**
250 * Determine the operating system TYPO3 is running on.
251 *
252 * @return string Either 'WIN' if running on Windows, else empty string
253 */
254 protected static function getTypo3Os()
255 {
256 $typoOs = '';
257 if (!stristr(PHP_OS, 'darwin') && !stristr(PHP_OS, 'cygwin') && stristr(PHP_OS, 'win')) {
258 $typoOs = 'WIN';
259 }
260 return $typoOs;
261 }
262
263 /**
264 * Calculate PATH_thisScript
265 *
266 * First step in path calculation: Goal is to find the absolute path of the entry script
267 * that was called without resolving any links. This is important since the TYPO3 entry
268 * points are often linked to a central core location, so we can not use the php magic
269 * __FILE__ here, but resolve the called script path from given server environments.
270 *
271 * This path is important to calculate the document root (PATH_site). The strategy is to
272 * find out the script name that was called in the first place and to subtract the local
273 * part from it to find the document root.
274 *
275 * @return string Absolute path to entry script
276 */
277 protected static function getPathThisScript()
278 {
279 if (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI) {
280 return self::getPathThisScriptCli();
281 }
282 return self::getPathThisScriptNonCli();
283 }
284
285 /**
286 * Calculate path to entry script if not in cli mode.
287 *
288 * Depending on the environment, the script path is found in different $_SERVER variables.
289 *
290 * @return string Absolute path to entry script
291 */
292 protected static function getPathThisScriptNonCli()
293 {
294 $cgiPath = '';
295 if (isset($_SERVER['ORIG_PATH_TRANSLATED'])) {
296 $cgiPath = $_SERVER['ORIG_PATH_TRANSLATED'];
297 } elseif (isset($_SERVER['PATH_TRANSLATED'])) {
298 $cgiPath = $_SERVER['PATH_TRANSLATED'];
299 }
300 if ($cgiPath && in_array(PHP_SAPI, self::$supportedCgiServerApis, true)) {
301 $scriptPath = $cgiPath;
302 } else {
303 if (isset($_SERVER['ORIG_SCRIPT_FILENAME'])) {
304 $scriptPath = $_SERVER['ORIG_SCRIPT_FILENAME'];
305 } else {
306 $scriptPath = $_SERVER['SCRIPT_FILENAME'];
307 }
308 }
309 return $scriptPath;
310 }
311
312 /**
313 * Calculate path to entry script if in cli mode.
314 *
315 * First argument of a cli script is the path to the script that was called. If the script does not start
316 * with / (or A:\ for Windows), the path is not absolute yet, and the current working directory is added.
317 *
318 * @return string Absolute path to entry script
319 */
320 protected static function getPathThisScriptCli()
321 {
322 // Possible relative path of the called script
323 if (isset($_SERVER['argv'][0])) {
324 $scriptPath = $_SERVER['argv'][0];
325 } elseif (isset($_ENV['_'])) {
326 $scriptPath = $_ENV['_'];
327 } else {
328 $scriptPath = $_SERVER['_'];
329 }
330 // Find out if path is relative or not
331 $isRelativePath = false;
332 if (TYPO3_OS === 'WIN') {
333 if (!preg_match('/^([a-zA-Z]:)?\\\\/', $scriptPath)) {
334 $isRelativePath = true;
335 }
336 } else {
337 if ($scriptPath[0] !== '/') {
338 $isRelativePath = true;
339 }
340 }
341 // Concatenate path to current working directory with relative path and remove "/./" constructs
342 if ($isRelativePath) {
343 if (isset($_SERVER['PWD'])) {
344 $workingDirectory = $_SERVER['PWD'];
345 } else {
346 $workingDirectory = getcwd();
347 }
348 $scriptPath = $workingDirectory . '/' . preg_replace('/\\.\\//', '', $scriptPath);
349 }
350 return $scriptPath;
351 }
352
353 /**
354 * Calculate the document root part to the instance from PATH_thisScript.
355 * This is based on the amount of subdirectories "under" PATH_site where PATH_thisScript is located.
356 *
357 * The following main scenarios for entry points exist by default in the TYPO3 core:
358 * - Directly called documentRoot/index.php (-> FE call or eiD include): index.php is located in the same directory
359 * as the main project. The document root is identical to the directory the script is located at.
360 * - The install tool, located under typo3/install.php.
361 * - A Backend script: This is the case for the typo3/index.php dispatcher and other entry scripts like 'typo3/sysext/core/bin/typo3'
362 * or 'typo3/index.php' that are located inside typo3/ directly.
363 *
364 * @param string $scriptPath Calculated path to the entry script
365 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
366 * @return string Absolute path to document root of installation
367 */
368 protected static function getRootPathFromScriptPath($scriptPath, $entryPointLevel)
369 {
370 $entryScriptDirectory = dirname($scriptPath);
371 if ($entryPointLevel > 0) {
372 list($rootPath) = GeneralUtility::revExplode('/', $entryScriptDirectory, $entryPointLevel + 1);
373 } else {
374 $rootPath = $entryScriptDirectory;
375 }
376 return $rootPath;
377 }
378
379 /**
380 * Send http headers, echo out a text message and exit with error code
381 *
382 * @param string $message
383 */
384 protected static function exitWithMessage($message)
385 {
386 $headers = [
387 \TYPO3\CMS\Core\Utility\HttpUtility::HTTP_STATUS_500,
388 'Content-Type: text/plain'
389 ];
390 if (!headers_sent()) {
391 foreach ($headers as $header) {
392 header($header);
393 }
394 }
395 echo $message . LF;
396 exit(1);
397 }
398
399 /**
400 * Check if the given function is disabled in the system
401 *
402 * @param string $function
403 * @return bool
404 */
405 public static function isFunctionDisabled($function)
406 {
407 if (static::$disabledFunctions === null) {
408 static::$disabledFunctions = GeneralUtility::trimExplode(',', ini_get('disable_functions'));
409 }
410 if (!empty(static::$disabledFunctions)) {
411 return in_array($function, static::$disabledFunctions, true);
412 }
413
414 return false;
415 }
416 }