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