Revert "[TASK] Rebuild the calcAge functionality"
[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 /**
18 * Class to encapsulate base setup of bootstrap.
19 *
20 * This class contains all code that must be executed by every entry script.
21 *
22 * It sets up all basic paths, constants, global variables and checks
23 * the basic environment TYPO3 runs in.
24 *
25 * This class does not use any TYPO3 instance specific configuration, it only
26 * sets up things based on the server environment and core code. Even with a
27 * missing typo3conf/localconf.php this script will be successful.
28 *
29 * The script aborts execution with an error message if
30 * some part fails or conditions are not met.
31 *
32 * This script is internal code and subject to change.
33 * DO NOT use it in own code, or be prepared your code might
34 * break in future versions of the core.
35 */
36 class SystemEnvironmentBuilder {
37
38 /**
39 * A list of supported CGI server APIs
40 * NOTICE: This is a duplicate of the SAME array in GeneralUtility!
41 * It is duplicated here as this information is needed early in bootstrap
42 * and GeneralUtility is not available yet.
43 * @var array
44 */
45 static protected $supportedCgiServerApis = array(
46 'fpm-fcgi',
47 'cgi',
48 'isapi',
49 'cgi-fcgi',
50 'srv', // HHVM with fastcgi
51 );
52
53 /**
54 * Run base setup.
55 * This entry method is used in all scopes (FE, BE, eid, ajax, ...)
56 *
57 * @internal This method should not be used by 3rd party code. It will change without further notice.
58 * @param string $relativePathPart Relative path of the entry script back to document root
59 * @return void
60 */
61 static public function run($relativePathPart = '') {
62 self::defineBaseConstants();
63 self::definePaths($relativePathPart);
64 self::checkMainPathsExist();
65 self::requireBaseClasses();
66 self::handleMagicQuotesGpc();
67 self::addCorePearPathToIncludePath();
68 self::initializeGlobalVariables();
69 self::initializeGlobalTimeTrackingVariables();
70 self::initializeBasicErrorReporting();
71 }
72
73 /**
74 * Define all simple constants that have no dependency to local configuration
75 *
76 * @return void
77 */
78 static protected function defineBaseConstants() {
79 // This version, branch and copyright
80 define('TYPO3_version', '6.2.4-dev');
81 define('TYPO3_branch', '6.2');
82 define('TYPO3_copyright_year', '1998-2014');
83
84 // TYPO3 external links
85 define('TYPO3_URL_GENERAL', 'http://typo3.org/');
86 define('TYPO3_URL_ORG', 'http://typo3.org/');
87 define('TYPO3_URL_LICENSE', 'http://typo3.org/licenses');
88 define('TYPO3_URL_EXCEPTION', 'http://typo3.org/go/exception/CMS/');
89 define('TYPO3_URL_MAILINGLISTS', 'http://lists.typo3.org/cgi-bin/mailman/listinfo');
90 define('TYPO3_URL_DOCUMENTATION', 'http://typo3.org/documentation/');
91 define('TYPO3_URL_DOCUMENTATION_TSREF', 'http://docs.typo3.org/typo3cms/TyposcriptReference/');
92 define('TYPO3_URL_DOCUMENTATION_TSCONFIG', 'http://docs.typo3.org/typo3cms/TSconfigReference/');
93 define('TYPO3_URL_CONSULTANCY', 'http://typo3.org/support/professional-services/');
94 define('TYPO3_URL_CONTRIBUTE', 'http://typo3.org/contribute/');
95 define('TYPO3_URL_SECURITY', 'http://typo3.org/teams/security/');
96 define('TYPO3_URL_DOWNLOAD', 'http://typo3.org/download/');
97 define('TYPO3_URL_SYSTEMREQUIREMENTS', 'http://typo3.org/typo3-cms/overview/requirements/');
98 define('TYPO3_URL_DONATE', 'http://typo3.org/donate/online-donation/');
99 define('TYPO3_URL_WIKI_OPCODECACHE', 'http://wiki.typo3.org/Opcode_Cache');
100
101 // A tabulator, a linefeed, a carriage return, a CR-LF combination
102 define('TAB', chr(9));
103 define('LF', chr(10));
104 define('CR', chr(13));
105 define('CRLF', CR . LF);
106
107 // Security related constant: Default value of fileDenyPattern
108 define('FILE_DENY_PATTERN_DEFAULT', '\\.(php[3-6]?|phpsh|phtml)(\\..*)?$|^\\.htaccess$');
109 // Security related constant: List of file extensions that should be registered as php script file extensions
110 define('PHP_EXTENSIONS_DEFAULT', 'php,php3,php4,php5,php6,phpsh,inc,phtml');
111
112 // Operating system identifier
113 // Either "WIN" or empty string
114 define('TYPO3_OS', self::getTypo3Os());
115
116 // Service error constants
117 // General error - something went wrong
118 define('T3_ERR_SV_GENERAL', -1);
119 // During execution it showed that the service is not available and should be ignored. The service itself should call $this->setNonAvailable()
120 define('T3_ERR_SV_NOT_AVAIL', -2);
121 // Passed subtype is not possible with this service
122 define('T3_ERR_SV_WRONG_SUBTYPE', -3);
123 // Passed subtype is not possible with this service
124 define('T3_ERR_SV_NO_INPUT', -4);
125 // File not found which the service should process
126 define('T3_ERR_SV_FILE_NOT_FOUND', -20);
127 // File not readable
128 define('T3_ERR_SV_FILE_READ', -21);
129 // File not writable
130 define('T3_ERR_SV_FILE_WRITE', -22);
131 // Passed subtype is not possible with this service
132 define('T3_ERR_SV_PROG_NOT_FOUND', -40);
133 // Passed subtype is not possible with this service
134 define('T3_ERR_SV_PROG_FAILED', -41);
135 }
136
137 /**
138 * Calculate all required base paths and set as constants.
139 *
140 * @param string $relativePathPart Relative path of the entry script back to document root
141 * @return void
142 */
143 static protected function definePaths($relativePathPart = '') {
144 // Relative path from document root to typo3/ directory
145 // Hardcoded to "typo3/"
146 define('TYPO3_mainDir', 'typo3/');
147 // Absolute path of the entry script that was called
148 // All paths are unified between Windows and Unix, so the \ of Windows is substituted to a /
149 // Example "/var/www/instance-name/htdocs/typo3conf/ext/wec_map/mod1/index.php"
150 // Example "c:/var/www/instance-name/htdocs/typo3/backend.php" for a path in Windows
151 if (!defined('PATH_thisScript')) {
152 define('PATH_thisScript', self::getPathThisScript());
153 }
154 // Absolute path of the document root of the instance with trailing slash
155 // Example "/var/www/instance-name/htdocs/"
156 if (!defined('PATH_site')) {
157 define('PATH_site', self::getPathSite($relativePathPart));
158 }
159 // Absolute path of the typo3 directory of the instance with trailing slash
160 // Example "/var/www/instance-name/htdocs/typo3/"
161 define('PATH_typo3', PATH_site . TYPO3_mainDir);
162 // Relative path (from the PATH_typo3) to a BE module NOT using mod.php dispatcher with trailing slash
163 // Example "sysext/perms/mod/" for an extension installed in typo3/sysext/
164 // Example "install/" for the install tool entry script
165 // Example "../typo3conf/ext/templavoila/mod2/ for an extension installed in typo3conf/ext/
166 define('PATH_typo3_mod', defined('TYPO3_MOD_PATH') ? TYPO3_MOD_PATH : '');
167 // Absolute path to the typo3conf directory with trailing slash
168 // Example "/var/www/instance-name/htdocs/typo3conf/"
169 define('PATH_typo3conf', PATH_site . 'typo3conf/');
170 // Absolute path to the tslib directory with trailing slash
171 // Example "/var/www/instance-name/htdocs/typo3/sysext/cms/tslib/"
172 define('PATH_tslib', PATH_typo3 . 'sysext/cms/tslib/');
173 }
174
175 /**
176 * Check if path and script file name calculation was successful, exit if not.
177 *
178 * @return void
179 */
180 static protected function checkMainPathsExist() {
181 if (!is_file(PATH_thisScript)) {
182 die('Unable to determine path to entry script.');
183 }
184 if (!is_dir(PATH_tslib)) {
185 die('Calculated absolute path to tslib directory does not exist.');
186 }
187 }
188
189 /**
190 * Load several base classes during bootstrap
191 *
192 * @return void
193 */
194 static protected function requireBaseClasses() {
195 require_once __DIR__ . '/../Utility/GeneralUtility.php';
196 require_once __DIR__ . '/../Utility/ArrayUtility.php';
197 require_once __DIR__ . '/../Utility/PathUtility.php';
198 require_once __DIR__ . '/../SingletonInterface.php';
199 require_once __DIR__ . '/../Configuration/ConfigurationManager.php';
200 require_once __DIR__ . '/../Cache/Frontend/FrontendInterface.php';
201 require_once __DIR__ . '/../Cache/Frontend/AbstractFrontend.php';
202 require_once __DIR__ . '/../Cache/Frontend/StringFrontend.php';
203 require_once __DIR__ . '/../Cache/Frontend/PhpFrontend.php';
204 require_once __DIR__ . '/../Cache/Frontend/VariableFrontend.php';
205 require_once __DIR__ . '/../Cache/Backend/BackendInterface.php';
206 require_once __DIR__ . '/../Cache/Backend/PhpCapableBackendInterface.php';
207 require_once __DIR__ . '/../Cache/Backend/TaggableBackendInterface.php';
208 require_once __DIR__ . '/../Cache/Backend/AbstractBackend.php';
209 require_once __DIR__ . '/../Cache/Backend/TransientMemoryBackend.php';
210 require_once __DIR__ . '/ClassLoader.php';
211 require_once __DIR__ . '/ClassAliasMap.php';
212 }
213
214 /**
215 * Compatibility layer for magic quotes
216 *
217 * @return void
218 */
219 static protected function handleMagicQuotesGpc() {
220 if (!get_magic_quotes_gpc()) {
221 \TYPO3\CMS\Core\Utility\GeneralUtility::addSlashesOnArray($_GET);
222 \TYPO3\CMS\Core\Utility\GeneralUtility::addSlashesOnArray($_POST);
223 $GLOBALS['HTTP_GET_VARS'] = $_GET;
224 $GLOBALS['HTTP_POST_VARS'] = $_POST;
225 }
226 }
227
228 /**
229 * Add typo3/contrib/pear/ as first include folder in
230 * include path, because the shipped PEAR packages use
231 * relative paths to include their files.
232 *
233 * This is required for \TYPO3\CMS\Core\Http\HttpRequest
234 * to work.
235 *
236 * Having the TYPO3 folder first will make sure that the
237 * shipped version is loaded before any local PEAR package,
238 * thus avoiding any incompatibilities with newer or older
239 * versions.
240 *
241 * @return void
242 */
243 static protected function addCorePearPathToIncludePath() {
244 set_include_path(PATH_typo3 . 'contrib/pear/' . PATH_SEPARATOR . get_include_path());
245 }
246
247 /**
248 * Set up / initialize several globals variables
249 *
250 * @return void
251 */
252 static protected function initializeGlobalVariables() {
253 // Unset variable(s) in global scope (security issue #13959)
254 unset($GLOBALS['error']);
255 // Set up base information about browser/user-agent
256 $GLOBALS['CLIENT'] = \TYPO3\CMS\Core\Utility\GeneralUtility::clientInfo();
257 $GLOBALS['TYPO3_MISC'] = array();
258 $GLOBALS['T3_VAR'] = array();
259 $GLOBALS['T3_SERVICES'] = array();
260 }
261
262 /**
263 * Initialize global time tracking variables.
264 * These are helpers to for example output script parsetime at the end of a script.
265 *
266 * @return void
267 */
268 static protected function initializeGlobalTimeTrackingVariables() {
269 // Set PARSETIME_START to the system time in milliseconds.
270 $GLOBALS['PARSETIME_START'] = \TYPO3\CMS\Core\Utility\GeneralUtility::milliseconds();
271 // Microtime of (nearly) script start
272 $GLOBALS['TYPO3_MISC']['microtime_start'] = microtime(TRUE);
273 // EXEC_TIME is set so that the rest of the script has a common value for the script execution time
274 $GLOBALS['EXEC_TIME'] = time();
275 // $ACCESS_TIME is a common time in minutes for access control
276 $GLOBALS['ACCESS_TIME'] = $GLOBALS['EXEC_TIME'] - $GLOBALS['EXEC_TIME'] % 60;
277 // $SIM_EXEC_TIME is set to $EXEC_TIME but can be altered later in the script if we want to
278 // simulate another execution-time when selecting from eg. a database
279 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
280 // If $SIM_EXEC_TIME is changed this value must be set accordingly
281 $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
282 }
283
284 /**
285 * Initialize basic error reporting.
286 *
287 * There are a lot of extensions that have no strict / notice / deprecated free
288 * ext_localconf or ext_tables. Since the final error reporting must be set up
289 * after those extension files are read, a default configuration is needed to
290 * suppress error reporting meanwhile during further bootstrap.
291 *
292 * @return void
293 */
294 static protected function initializeBasicErrorReporting() {
295 // Core should be notice free at least until this point ...
296 error_reporting(E_ALL & ~(E_STRICT | E_NOTICE | E_DEPRECATED));
297 }
298
299 /**
300 * Determine the operating system TYPO3 is running on.
301 *
302 * @return string Either 'WIN' if running on Windows, else empty string
303 */
304 static protected function getTypo3Os() {
305 $typoOs = '';
306 if (!stristr(PHP_OS, 'darwin') && stristr(PHP_OS, 'win')) {
307 $typoOs = 'WIN';
308 }
309 return $typoOs;
310 }
311
312 /**
313 * Calculate PATH_thisScript
314 *
315 * First step in path calculation: Goal is to find the absolute path of the entry script
316 * that was called without resolving any links. This is important since the TYPO3 entry
317 * points are often linked to a central core location, so we can not use the php magic
318 * __FILE__ here, but resolve the called script path from given server environments.
319 *
320 * This path is important to calculate the document root (PATH_site). The strategy is to
321 * find out the script name that was called in the first place and to subtract the local
322 * part from it to find the document root.
323 *
324 * @return string Absolute path to entry script
325 */
326 static protected function getPathThisScript() {
327 if (defined('TYPO3_cliMode') && TYPO3_cliMode === TRUE) {
328 return self::getPathThisScriptCli();
329 } else {
330 return self::getPathThisScriptNonCli();
331 }
332 }
333
334 /**
335 * Calculate path to entry script if not in cli mode.
336 *
337 * Depending on the environment, the script path is found in different $_SERVER variables.
338 *
339 * @return string Absolute path to entry script
340 */
341 static protected function getPathThisScriptNonCli() {
342 $cgiPath = '';
343 if (isset($_SERVER['ORIG_PATH_TRANSLATED'])) {
344 $cgiPath = $_SERVER['ORIG_PATH_TRANSLATED'];
345 } elseif (isset($_SERVER['PATH_TRANSLATED'])) {
346 $cgiPath = $_SERVER['PATH_TRANSLATED'];
347 }
348 if ($cgiPath && in_array(PHP_SAPI, self::$supportedCgiServerApis, TRUE)) {
349 $scriptPath = $cgiPath;
350 } else {
351 if (isset($_SERVER['ORIG_SCRIPT_FILENAME'])) {
352 $scriptPath = $_SERVER['ORIG_SCRIPT_FILENAME'];
353 } else {
354 $scriptPath = $_SERVER['SCRIPT_FILENAME'];
355 }
356 }
357 // Replace \ to / for Windows
358 $scriptPath = str_replace('\\', '/', $scriptPath);
359 // Replace double // to /
360 $scriptPath = str_replace('//', '/', $scriptPath);
361 return $scriptPath;
362 }
363
364 /**
365 * Calculate path to entry script if in cli mode.
366 *
367 * First argument of a cli script is the path to the script that was called. If the script does not start
368 * with / (or A:\ for Windows), the path is not absolute yet, and the current working directory is added.
369 *
370 * @return string Absolute path to entry script
371 */
372 static protected function getPathThisScriptCli() {
373 // Possible relative path of the called script
374 if (isset($_SERVER['argv'][0])) {
375 $scriptPath = $_SERVER['argv'][0];
376 } elseif (isset($_ENV['_'])) {
377 $scriptPath = $_ENV['_'];
378 } else {
379 $scriptPath = $_SERVER['_'];
380 }
381 // Find out if path is relative or not
382 $isRelativePath = FALSE;
383 if (TYPO3_OS === 'WIN') {
384 if (!preg_match('/^([A-Z]:)?\\\\/', $scriptPath)) {
385 $isRelativePath = TRUE;
386 }
387 } else {
388 if ($scriptPath[0] !== '/') {
389 $isRelativePath = TRUE;
390 }
391 }
392 // Concatenate path to current working directory with relative path and remove "/./" constructs
393 if ($isRelativePath) {
394 if (isset($_SERVER['PWD'])) {
395 $workingDirectory = $_SERVER['PWD'];
396 } else {
397 $workingDirectory = getcwd();
398 }
399 $scriptPath = $workingDirectory . '/' . preg_replace('/\\.\\//', '', $scriptPath);
400 }
401 return $scriptPath;
402 }
403
404 /**
405 * Calculate the document root part to the instance from PATH_thisScript
406 *
407 * There are two ways to hint correct calculation:
408 * Either an explicit specified sub path or the defined constant TYPO3_MOD_PATH. Which one is
409 * used depends on which entry script was called in the first place.
410 *
411 * We have two main scenarios for entry points:
412 * - Directly called documentRoot/index.php (-> FE call or eiD include): index.php sets $relativePathPart to
413 * empty string to hint this code that the document root is identical to the directory the script is located at.
414 * - An indirect include of typo3/init.php (-> a backend module, the install tool, or scripts like thumbs.php).
415 * If init.php is included we distinguish two cases:
416 * -- A backend module defines 'TYPO3_MOD_PATH': This is the case for "old" modules that are not called through
417 * "mod.php" dispatcher, and in the install tool. The TYPO3_MOD_PATH defines the relative path to the typo3/
418 * directory. This is taken as base to calculate the document root.
419 * -- A script includes init.php and does not define 'TYPO3_MOD_PATH': This is the case for the mod.php dispatcher
420 * and other entry scripts like 'cli_dispatch.phpsh' or 'thumbs.php' that are located parallel to init.php. In
421 * this case init.php sets 'typo3/' as $relativePathPart as base to calculate the document root.
422 *
423 * This basically boils down to the following code:
424 * If TYPO3_MOD_PATH is defined, subtract this 'local' part from the entry point directory, else use
425 * $relativePathPart to subtract this from the the script entry point to find out the document root.
426 *
427 * @param string $relativePathPart Relative directory part from document root to script path if TYPO3_MOD_PATH is not used
428 * @return string Absolute path to document root of installation
429 */
430 static protected function getPathSite($relativePathPart) {
431 // If end of path is not "typo3/" and TYPO3_MOD_PATH is given
432 if (defined('TYPO3_MOD_PATH')) {
433 return self::getPathSiteByTypo3ModulePath();
434 } else {
435 return self::getPathSiteByRelativePathPart($relativePathPart);
436 }
437 }
438
439 /**
440 * Calculate document root by TYPO3_MOD_PATH
441 *
442 * TYPO3_MOD_PATH can have the following values:
443 * - "sysext/extensionName/path/entryScript.php" -> extension is below 'docRoot'/typo3/sysext
444 * - "ext/extensionName/path/entryScript.php" -> extension is below 'docRoot'/typo3/ext
445 * - "../typo3conf/ext/extensionName/path/entryScript.php" -> extension is below 'docRoot'/typo3conf/ext
446 * - "install/index.php" -> install tool in 'docRoot'/typo3/install/
447 *
448 * The method unifies the above and subtracts the calculated path part from PATH_thisScript
449 *
450 * @return string Absolute path to document root of installation
451 */
452 static protected function getPathSiteByTypo3ModulePath() {
453 if (substr(TYPO3_MOD_PATH, 0, 7) === 'sysext/' || substr(TYPO3_MOD_PATH, 0, 4) === 'ext/' || substr(TYPO3_MOD_PATH, 0, 8) === 'install/') {
454 $pathPartRelativeToDocumentRoot = TYPO3_mainDir . TYPO3_MOD_PATH;
455 } elseif (substr(TYPO3_MOD_PATH, 0, strlen('../typo3conf/')) === '../typo3conf/') {
456 $pathPartRelativeToDocumentRoot = substr(TYPO3_MOD_PATH, 3);
457 } else {
458 die('Unable to determine TYPO3 document root.');
459 }
460 $entryScriptDirectory = self::getUnifiedDirectoryNameWithTrailingSlash(PATH_thisScript);
461 return substr($entryScriptDirectory, 0, -strlen($pathPartRelativeToDocumentRoot));
462 }
463
464 /**
465 * Find out document root by subtracting $relativePathPart from PATH_thisScript
466 *
467 * @param string $relativePathPart Relative part of script from document root
468 * @return string Absolute path to document root of installation
469 */
470 static protected function getPathSiteByRelativePathPart($relativePathPart) {
471 $entryScriptDirectory = self::getUnifiedDirectoryNameWithTrailingSlash(PATH_thisScript);
472 if (strlen($relativePathPart) > 0) {
473 $pathSite = substr($entryScriptDirectory, 0, -strlen($relativePathPart));
474 } else {
475 $pathSite = $entryScriptDirectory;
476 }
477 return $pathSite;
478 }
479
480 /**
481 * Remove file name from script path and unify for Windows and Unix
482 *
483 * @param string $absolutePath Absolute path to script
484 * @return string Directory name of script file location, unified for Windows and Unix
485 */
486 static protected function getUnifiedDirectoryNameWithTrailingSlash($absolutePath) {
487 $directory = dirname($absolutePath);
488 if (TYPO3_OS === 'WIN') {
489 $directory = str_replace('\\', '/', $directory);
490 }
491 return $directory . '/';
492 }
493 }