From bf119ecd4e408cabace9791b3216e08001664f5d Mon Sep 17 00:00:00 2001
From: Christian Kuhn <lolli@schwarzbu.ch>
Date: Sat, 5 May 2012 16:26:47 +0200
Subject: [PATCH] [!!!][TASK] Bootstrap: Central constants and path handling

Introduce a class to define main constants and all basic
path evaluations at an early point in bootstrap.

The patch streamlines a lot of the duplicated code for the different
entry points to TYPO3 and moves especially the path handling to a
well documented central location.

Until now, it was documented that is is possible to define own names
for the directories "typo3/", "tslib", "typo3conf/" and "t3lib/".
This never worked without core hacks and was probably never used in
production by anyone for that reason.
This feature is now officially dropped.

Change-Id: Id1ec1082a2572f20500c23357ef5fdbdb05c8498
Resolves: #36889
Releases: 6.0
Reviewed-on: http://review.typo3.org/11030
Reviewed-by: Tolleiv Nietsch
Tested-by: Tolleiv Nietsch
Reviewed-by: Susanne Moog
Tested-by: Susanne Moog
Reviewed-by: Christian Kuhn
Tested-by: Christian Kuhn
---
 NEWS.txt                                      |   8 +
 index.php                                     |  37 +-
 t3lib/class.t3lib_div.php                     |  16 +-
 t3lib/config_default.php                      |  30 --
 typo3/Bootstrap.php                           | 358 ++++++++++++++++++
 typo3/cli_dispatch.phpsh                      |  36 +-
 typo3/init.php                                | 106 +-----
 typo3/sysext/beuser/mod/conf.php              |   3 -
 typo3/sysext/cms/tslib/index_ts.php           |   9 -
 typo3/sysext/em/classes/conf.php              |   3 -
 .../install/mod/class.tx_install_ajax.php     |  33 --
 typo3/thumbs.php                              |  14 +-
 12 files changed, 376 insertions(+), 277 deletions(-)
 create mode 100644 typo3/Bootstrap.php

diff --git a/NEWS.txt b/NEWS.txt
index e9a013353f99..6d452f9496a5 100644
--- a/NEWS.txt
+++ b/NEWS.txt
@@ -14,6 +14,14 @@ http://wiki.typo3.org/TYPO3_6.0
 Compatibility
 ===============================================================================
 
+* Refactored bootstrap
+
+With a bootstrap refactoring the index.php file located in the document root of
+the installation was changed. If you are running a typo3 core source with a
+symlink, make sure that this file is also a symlink to the cores index.php,
+otherwise the frontend will be broken. If index.php is a copy of the source
+file, make sure to install a fresh version from 6.0 sources.
+
 * Deprecated methods
 
 Deprecated methods that were initially targeted to be removed in TYPO3 4.8/6.0
diff --git a/index.php b/index.php
index 70b82bc0b493..b74cccc51ebf 100644
--- a/index.php
+++ b/index.php
@@ -36,45 +36,14 @@
 // *******************************
 // Set error reporting
 // *******************************
-
 error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
 
-
-// ******************
-// Constants defined
-// ******************
-
-define('PATH_thisScript', str_replace('//', '/', str_replace('\\', '/',
-	(PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == 'isapi' || PHP_SAPI == 'cgi-fcgi') &&
-	($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) ?
-	($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) :
-	($_SERVER['ORIG_SCRIPT_FILENAME'] ? $_SERVER['ORIG_SCRIPT_FILENAME'] : $_SERVER['SCRIPT_FILENAME']))));
-
-define('PATH_site', dirname(PATH_thisScript).'/');
-
-if (@is_dir(PATH_site.'typo3/sysext/cms/tslib/')) {
-	define('PATH_tslib', PATH_site.'typo3/sysext/cms/tslib/');
-} elseif (@is_dir(PATH_site.'tslib/')) {
-	define('PATH_tslib', PATH_site.'tslib/');
-} else {
-
-	// define path to tslib/ here:
-	$configured_tslib_path = '';
-
-	// example:
-	// $configured_tslib_path = '/var/www/mysite/typo3/sysext/cms/tslib/';
-
-	define('PATH_tslib', $configured_tslib_path);
-}
-
-if (PATH_tslib=='') {
-	die('Cannot find tslib/. Please set path by defining $configured_tslib_path in ' . htmlspecialchars(basename(PATH_thisScript)) . '.');
-}
+require('typo3/Bootstrap.php');
+Typo3_Bootstrap::defineBaseConstants();
+Typo3_Bootstrap::defineAndCheckPaths('');
 
 // ******************
 // include TSFE
 // ******************
-
 require (PATH_tslib.'index_ts.php');
-
 ?>
\ No newline at end of file
diff --git a/t3lib/class.t3lib_div.php b/t3lib/class.t3lib_div.php
index 92841fc72234..f8525fed69f3 100644
--- a/t3lib/class.t3lib_div.php
+++ b/t3lib/class.t3lib_div.php
@@ -25,15 +25,6 @@
  *  This copyright notice MUST APPEAR in all copies of the script!
  ***************************************************************/
 
-	// a tabulator
-define('TAB', chr(9));
-	// a linefeed
-define('LF', chr(10));
-	// a carriage return
-define('CR', chr(13));
-	// a CR-LF combination
-define('CRLF', CR . LF);
-
 /**
  * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
  * Most of the functions do not relate specifically to TYPO3
@@ -3398,12 +3389,7 @@ final class t3lib_div {
 				}
 				break;
 			case 'SCRIPT_FILENAME':
-				$retVal = str_replace('//', '/', str_replace('\\', '/',
-					(PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == 'isapi' || PHP_SAPI == 'cgi-fcgi') &&
-							($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) ?
-							($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) :
-							($_SERVER['ORIG_SCRIPT_FILENAME'] ? $_SERVER['ORIG_SCRIPT_FILENAME'] : $_SERVER['SCRIPT_FILENAME'])));
-
+				$retVal = PATH_thisScript;
 				break;
 			case 'REQUEST_URI':
 					// Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
diff --git a/t3lib/config_default.php b/t3lib/config_default.php
index bf20b9a02013..7c715bb187ff 100644
--- a/t3lib/config_default.php
+++ b/t3lib/config_default.php
@@ -14,15 +14,6 @@
 
 if (!defined ('PATH_typo3conf')) 	die ('The configuration path was not properly defined!');
 
-//Security related constant: Default value of fileDenyPattern
-define('FILE_DENY_PATTERN_DEFAULT', '\.(php[3-6]?|phpsh|phtml)(\..*)?$|^\.htaccess$');
-
-//Security related constant: Comma separated list of file extensions that should be registered as php script file extensions
-define('PHP_EXTENSIONS_DEFAULT', 'php,php3,php4,php5,php6,phpsh,inc,phtml');
-
-// Defines a list that are basically required by a TYPO3 system.
-define('REQUIRED_EXTENSIONS', 'cms,lang,sv,em,recordlist,extbase,fluid');
-
 $TYPO3_CONF_VARS = array(
 	'GFX' => array(		// Configuration of the image processing features in TYPO3. 'IM' and 'GD' are short for ImageMagick and GD library respectively.
 		'image_processing' => TRUE,				// Boolean: Enables image processing features. Disabling this means NO image processing with either GD or IM!
@@ -736,11 +727,6 @@ if (TYPO3_MODE === 'BE') {
 
 $T3_VAR = array();	// Initialize.
 
-	// TYPO3 version
-define('TYPO3_version', '6.0-dev');
-define('TYPO3_branch', '6.0');
-define('TYPO3_copyright_year', '1998-2012');
-
 	// Handle $GLOBALS['TYPO3_CONF_VARS']['HTTP']['userAgent']. We can not set the default above
 	// because TYPO3_version is not yet defined.
 if (empty($GLOBALS['TYPO3_CONF_VARS']['HTTP']['userAgent'])) {
@@ -756,22 +742,6 @@ $typo_db_host = '';				// The database host
 $typo_db_tables_script = '';	// The filename of the tables.php script in typo3conf/ folder IF the default t3lib/stddb/tables.php should NOT be used for some reason. It's recommended to use the default and modify it through the extTableDef-script, see below.
 $typo_db_extTableDef_script = '';	// The filename of an additional script in typo3conf/-folder which is included after tables.php. Code in this script should modify the tables.php-configuration only, and this provides a good way to extend the standard-distributed tables.php file.
 
-// TYPO3 links
-define('TYPO3_URL_GENERAL', 'http://typo3.org/');
-define('TYPO3_URL_ORG', 'http://typo3.org/');
-define('TYPO3_URL_LICENSE', 'http://typo3.org/license');
-define('TYPO3_URL_EXCEPTION', 'http://typo3.org/go/exception/v4/');
-define('TYPO3_URL_MAILINGLISTS', 'http://lists.typo3.org/cgi-bin/mailman/listinfo');
-define('TYPO3_URL_DOCUMENTATION', 'http://typo3.org/documentation/');
-define('TYPO3_URL_DOCUMENTATION_TSREF', 'http://typo3.org/documentation/document-library/references/doc_core_tsref/current/view/');
-define('TYPO3_URL_DOCUMENTATION_TSCONFIG', 'http://typo3.org/documentation/document-library/references/doc_core_tsconfig/current/view/');
-define('TYPO3_URL_CONSULTANCY', 'http://typo3.com/Consultancies.1248.0.html');
-define('TYPO3_URL_CONTRIBUTE', 'http://typo3.org/community/participate/');
-define('TYPO3_URL_SECURITY', 'http://typo3.org/teams/security/');
-define('TYPO3_URL_DOWNLOAD', 'http://typo3.org/download/packages/');
-define('TYPO3_URL_SYSTEMREQUIREMENTS', 'http://typo3.org/1275.0.html');
-define('TYPO3_URL_DONATE', 'http://typo3.org/donate/');
-
 	// Include localconf.php. Use this file to configure TYPO3 for your needs and database
 if (!@is_file(PATH_typo3conf . 'localconf.php')) {
 	throw new RuntimeException('localconf.php is not found!', 1333754332);
diff --git a/typo3/Bootstrap.php b/typo3/Bootstrap.php
new file mode 100644
index 000000000000..6b562eb54210
--- /dev/null
+++ b/typo3/Bootstrap.php
@@ -0,0 +1,358 @@
+<?php
+/***************************************************************
+ *  Copyright notice
+ *
+ *  (c) 2012 Christian Kuhn <lolli@schwarzbu.ch>
+ *  All rights reserved
+ *
+ *  This script is part of the TYPO3 project. The TYPO3 project is
+ *  free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  The GNU General Public License can be found at
+ *  http://www.gnu.org/copyleft/gpl.html.
+ *  A copy is found in the textfile GPL.txt and important notices to the license
+ *  from the author is found in LICENSE.txt distributed with these scripts.
+ *
+ *
+ *  This script is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  This copyright notice MUST APPEAR in all copies of the script!
+ ***************************************************************/
+
+/**
+ * This class encapsulates bootstrap related methods.
+ * It is required directly as the very first thing in entry scripts and
+ * used to define all base things like constants and pathes and so on.
+ *
+ * @author Christian Kuhn <lolli@schwarzbu.ch>
+ * @package TYPO3
+ * @subpackage core
+ */
+class Typo3_Bootstrap {
+
+	/**
+	 * Define all simple base constants
+	 *
+	 * @return void
+	 */
+	public static function defineBaseConstants() {
+			// This version, branch and copyright
+		define('TYPO3_version', '6.0-dev');
+		define('TYPO3_branch', '6.0');
+		define('TYPO3_copyright_year', '1998-2012');
+
+			// TYPO3 external links
+		define('TYPO3_URL_GENERAL', 'http://typo3.org/');
+		define('TYPO3_URL_ORG', 'http://typo3.org/');
+		define('TYPO3_URL_LICENSE', 'http://typo3.org/licenses');
+		define('TYPO3_URL_EXCEPTION', 'http://typo3.org/go/exception/v4/');
+		define('TYPO3_URL_MAILINGLISTS', 'http://lists.typo3.org/cgi-bin/mailman/listinfo');
+		define('TYPO3_URL_DOCUMENTATION', 'http://typo3.org/documentation/');
+		define('TYPO3_URL_DOCUMENTATION_TSREF', 'http://typo3.org/documentation/document-library/core-documentation/doc_core_tsref/current/view/');
+		define('TYPO3_URL_DOCUMENTATION_TSCONFIG', 'http://typo3.org/documentation/document-library/core-documentation/doc_core_tsconfig/current/view/');
+		define('TYPO3_URL_CONSULTANCY', 'http://typo3.org/support/professional-services/');
+		define('TYPO3_URL_CONTRIBUTE', 'http://typo3.org/contribute/');
+		define('TYPO3_URL_SECURITY', 'http://typo3.org/teams/security/');
+		define('TYPO3_URL_DOWNLOAD', 'http://typo3.org/download/');
+		define('TYPO3_URL_SYSTEMREQUIREMENTS', 'http://typo3.org/about/typo3-the-cms/system-requirements/');
+		define('TYPO3_URL_DONATE', 'http://typo3.org/donate/online-donation/');
+
+			// A tabulator, a linefeed, a carriage return, a CR-LF combination
+		define('TAB', chr(9));
+		define('LF', chr(10));
+		define('CR', chr(13));
+		define('CRLF', CR . LF);
+
+			// Security related constant: Default value of fileDenyPattern
+		define('FILE_DENY_PATTERN_DEFAULT', '\.(php[3-6]?|phpsh|phtml)(\..*)?$|^\.htaccess$');
+
+			// Security related constant: List of file extensions that should be registered as php script file extensions
+		define('PHP_EXTENSIONS_DEFAULT', 'php,php3,php4,php5,php6,phpsh,inc,phtml');
+
+			// List of extensions required to run the core
+		define('REQUIRED_EXTENSIONS', 'cms,lang,sv,em,recordlist,extbase,fluid');
+
+			// Operating system identifier
+			// Either "WIN" or empty string
+		define('TYPO3_OS', self::getTypo3Os());
+	}
+
+	/**
+	 * Calculate all required base paths and set as constants.
+	 * The script execution will be aborted if this fails.
+	 *
+	 * @param string $relativePathPart The relative path of the entry script to the document root
+	 * @return void
+	 */
+	public static function defineAndCheckPaths($relativePathPart = '') {
+			// Relative path from document root to typo3/ directory
+			// Hardcoded to "typo3/"
+		define('TYPO3_mainDir', 'typo3/');
+
+			// Absolute path of the entry script that was called
+			// All paths are unified between Windows and Unix, so the \ of Windows is substituted to a /
+			// Example "/var/www/instance-name/htdocs/typo3conf/ext/wec_map/mod1/index.php"
+			// Example "c:/var/www/instance-name/htdocs/typo3/backend.php" for a path in Windows
+		define('PATH_thisScript', self::getPathThisScript());
+
+			// Absolute path of the document root of the instance with trailing slash
+			// Example "/var/www/instance-name/htdocs/"
+		define('PATH_site', self::getPathSite($relativePathPart));
+
+			// Absolute path of the typo3 directory of the instance with trailing slash
+			// Example "/var/www/instance-name/htdocs/typo3/"
+		define('PATH_typo3', PATH_site . TYPO3_mainDir);
+
+			// Relative path (from the PATH_typo3) to a BE module NOT using mod.php dispatcher with trailing slash
+			// Example "sysext/perms/mod/" for an extension installed in typo3/sysext/
+			// Example "install/" for the install tool entry script
+			// Example "../typo3conf/ext/templavoila/mod2/ for an extension installed in typo3conf/ext/
+		define('PATH_typo3_mod', defined('TYPO3_MOD_PATH') ? TYPO3_MOD_PATH : '');
+
+			// Absolute path to the t3lib directory with trailing slash
+			// Example "/var/www/instance-name/htdocs/t3lib/"
+		define('PATH_t3lib', PATH_site . 't3lib/');
+
+			// Absolute path to the typo3conf directory with trailing slash
+			// Example "/var/www/instance-name/htdocs/typo3conf/"
+		define('PATH_typo3conf', PATH_site . 'typo3conf/');
+
+			// Absolute path to the tslib directory with trailing slash
+			// Example "/var/www/instance-name/htdocs/typo3/sysext/cms/tslib/"
+		define('PATH_tslib', PATH_typo3 . 'sysext/cms/tslib/');
+
+			// Check above defines and exit with error message on error
+		self::checkMainPathsExist();
+	}
+
+	/**
+	 * Determine the operating system TYPO3 is running on.
+	 *
+	 * @return string Either 'WIN' if running on Windows, else empty string
+	 */
+	protected static function getTypo3Os() {
+		$typoOs = '';
+		if (!stristr(PHP_OS, 'darwin') && stristr(PHP_OS, 'win')) {
+			$typoOs = 'WIN';
+		}
+		return $typoOs;
+	}
+
+	/**
+	 * Calculate PATH_thisScript
+	 *
+	 * First step in path calculation: Goal is to find the absolute path of the entry script
+	 * that was called without resolving any links. This is important since the TYPO3 entry
+	 * points are often linked to a central core location, so we can not use the php magic
+	 * __FILE__ here, but resolve the called script path from given server environments.
+	 *
+	 * This path is important to calculate the document root (PATH_site). The strategy is to
+	 * find out the script name that was called in the first place and to subtract the local
+	 * part from it to find the document root.
+	 *
+	 * @return string Absolute path to entry script
+	 */
+	protected static function getPathThisScript() {
+		if (defined('TYPO3_cliMode') && TYPO3_cliMode === TRUE) {
+			return self::getPathThisScriptCli();
+		} else {
+			return self::getPathThisScriptNonCli();
+		}
+	}
+
+	/**
+	 * Calculate path to entry script if not in cli mode.
+	 *
+	 * Depending on the environment, the script path is found in different $_SERVER variables.
+	 *
+	 * @return string Absolute path to entry script
+	 */
+	protected static function getPathThisScriptNonCli() {
+		if ($_SERVER['ORIG_PATH_TRANSLATED']) {
+			$cgiPath = $_SERVER['ORIG_PATH_TRANSLATED'];
+		} else {
+			$cgiPath = $_SERVER['PATH_TRANSLATED'];
+		}
+		if ($cgiPath && (PHP_SAPI === 'fpm-fcgi' || PHP_SAPI === 'cgi' || PHP_SAPI === 'isapi' || PHP_SAPI === 'cgi-fcgi')) {
+			$scriptPath = $cgiPath;
+		} else {
+			if ($_SERVER['ORIG_SCRIPT_FILENAME']) {
+				$scriptPath = $_SERVER['ORIG_SCRIPT_FILENAME'];
+			} else {
+				$scriptPath = $_SERVER['SCRIPT_FILENAME'];
+			}
+		}
+			// Replace \ to / for Windows
+		$scriptPath = str_replace('\\', '/', $scriptPath);
+			// Replace double // to /
+		$scriptPath = str_replace('//', '/', $scriptPath);
+
+		return $scriptPath;
+	}
+
+	/**
+	 * Calculate path to entry script if in cli mode.
+	 *
+	 * First argument of a cli script is the path to the script that was called. If the script does not start
+	 * with / (or A:\ for Windows), the path is not absolute yet, and the current working directory is added.
+	 *
+	 * @return string Absolute path to entry script
+	 */
+	protected static function getPathThisScriptCli() {
+			// Possible relative path of the called script
+		if (isset($_SERVER['argv'][0])) {
+			$scriptPath = $_SERVER['argv'][0];
+		} elseif (isset($_ENV['_'])) {
+			$scriptPath = $_ENV['_'];
+		} else {
+			$scriptPath = $_SERVER['_'];
+		}
+
+			// Find out if path is relative or not
+		$isRelativePath = FALSE;
+		if (TYPO3_OS === 'WIN') {
+			if (!preg_match('/^([A-Z]:)?\\\/', $scriptPath)) {
+				$isRelativePath = TRUE;
+			}
+		} else {
+			if (substr($scriptPath, 0, 1) !== '/') {
+				$isRelativePath = TRUE;
+			}
+		}
+
+			// Concatenate path to current working directory with relative path and remove "/./" constructs
+		if ($isRelativePath) {
+			if (isset($_SERVER['PWD'])) {
+				$workingDirectory = $_SERVER['PWD'];
+			} else {
+				$workingDirectory = getcwd();
+			}
+			$scriptPath = $workingDirectory . '/' . preg_replace('/\.\//', '', $scriptPath);
+		}
+
+		return $scriptPath;
+	}
+
+	/**
+	 * Calculate the document root part to the instance from PATH_thisScript
+	 *
+	 * There are two ways to hint correct calculation:
+	 * Either an explicit specified sub path or the defined constant TYPO3_MOD_PATH. Which one is
+	 * used depends on which entry script was called in the first place.
+	 *
+	 * We have two main scenarios for entry points:
+	 * - Directly called documentRoot/index.php (-> FE call or eiD include): index.php sets $relativePathPart to
+	 *   empty string to hint this code that the document root is identical to the directory the script is located at.
+	 * - An indirect include of typo3/init.php (-> a backend module, the install tool, or scripts like thumbs.php).
+	 *   If init.php is included we distinguish two cases:
+	 *   -- A backend module defines 'TYPO3_MOD_PATH': This is the case for "old" modules that are not called through
+	 *      "mod.php" dispatcher, and in the install tool. The TYPO3_MOD_PATH defines the relative path to the typo3/
+	 *      directory. This is taken as base to calculate the document root.
+	 *   -- A script includes init.php and does not define 'TYPO3_MOD_PATH': This is the case for the mod.php dispatcher
+	 *      and other entry scripts like 'cli_dispatch.phpsh' or 'thumbs.php' that are located parallel to init.php. In
+	 *      this case init.php sets 'typo3/' as $relativePathPart as base to calculate the document root.
+	 *
+	 * This basically boils down to the following code:
+	 * If TYPO3_MOD_PATH is defined, subtract this 'local' part from the entry point directory, else use
+	 * $relativePathPart to subtract this from the the script entry point to find out the document root.
+	 *
+	 * @param string $relativePathPart Relative directory part from document root to script path if TYPO3_MOD_PATH is not used
+	 * @return string Absolute path to document root of installation
+	 */
+	protected static function getPathSite($relativePathPart) {
+			// If end of path is not "typo3/" and TYPO3_MOD_PATH is given
+		if (defined('TYPO3_MOD_PATH')) {
+			return self::getPathSiteByTypo3ModulePath();
+		} else {
+			return self::getPathSiteByRelativePathPart($relativePathPart);
+		}
+	}
+
+	/**
+	 * Calculate document root by TYPO3_MOD_PATH
+	 *
+	 * TYPO3_MOD_PATH can have the following values:
+	 * - "sysext/extensionName/path/entryScript.php" -> extension is below 'docRoot'/typo3/sysext
+	 * - "ext/extensionName/path/entryScript.php" -> extension is below 'docRoot'/typo3/ext
+	 * - "../typo3conf/ext/extensionName/path/entryScript.php" -> extension is below 'docRoot'/typo3conf/ext
+	 *- "install/index.php" -> install tool in 'docRoot'/typo3/install/
+	 *
+	 * The method unifies the above and subtracts the calculated path part from PATH_thisScript
+	 *
+	 * @return string Absolute path to document root of installation
+	 */
+	protected static function getPathSiteByTypo3ModulePath() {
+		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/'
+		) {
+			$pathPartRelativeToDocumentRoot = TYPO3_mainDir . TYPO3_MOD_PATH;
+		} elseif (substr(TYPO3_MOD_PATH, 0, strlen('../typo3conf/')) === '../typo3conf/') {
+			$pathPartRelativeToDocumentRoot = substr(TYPO3_MOD_PATH, 3);
+		} else {
+			die('Unable to determine TYPO3 document root.');
+		}
+
+		$entryScriptDirectory = self::getUnifiedDirectoryNameWithTrailingSlash(PATH_thisScript);
+
+		return substr($entryScriptDirectory, 0, -strlen($pathPartRelativeToDocumentRoot));
+	}
+
+	/**
+	 * Find out document root by subtracting $relativePathPart from PATH_thisScript
+	 *
+	 * @param string $relativePathPart Relative part of script from document root
+	 * @return string Absolute path to document root of installation
+	 */
+	protected static function getPathSiteByRelativePathPart($relativePathPart) {
+		$entryScriptDirectory = self::getUnifiedDirectoryNameWithTrailingSlash(PATH_thisScript);
+		if (strlen($relativePathPart) > 0) {
+			$pathSite = substr($entryScriptDirectory, 0, -strlen($relativePathPart));
+		} else {
+			$pathSite = $entryScriptDirectory;
+		}
+		return $pathSite;
+	}
+
+	/**
+	 * Remove file name from script path and unify for Windows and Unix
+	 *
+	 * @param string $absolutePath Absolute path to script
+	 * @return string Directory name of script file location, unified for Windows and Unix
+	 */
+	protected static function getUnifiedDirectoryNameWithTrailingSlash($absolutePath) {
+		$directory = dirname($absolutePath);
+		if (TYPO3_OS === 'WIN') {
+			$directory = str_replace('\\', '/', $directory);
+		}
+		return $directory . '/';
+	}
+
+	/**
+	 * Check if path and script file name calculation was successful, exit if not.
+	 *
+	 * @return void
+	 */
+	protected static function checkMainPathsExist() {
+		if (!is_file(PATH_thisScript)) {
+			die('Unable to determine path to entry script.');
+		}
+		if (!is_dir(PATH_t3lib)) {
+			die('Calculated absolute path to t3lib directory does not exist.');
+		}
+		if (!is_dir(PATH_tslib)) {
+			die('Calculated absolute path to tslib directory does not exist.');
+		}
+		if (!is_dir(PATH_typo3conf)) {
+			die('Calculated absolute path to typo3conf directory does not exist');
+		}
+	}
+}
+?>
\ No newline at end of file
diff --git a/typo3/cli_dispatch.phpsh b/typo3/cli_dispatch.phpsh
index e2979ad76172..a76860938759 100755
--- a/typo3/cli_dispatch.phpsh
+++ b/typo3/cli_dispatch.phpsh
@@ -69,41 +69,7 @@ if (substr(php_sapi_name(), 0, 3) == 'cgi') {
 	// Defining circumstances for CLI mode:
 define('TYPO3_cliMode', TRUE);
 
-	// Get path to this script
-$temp_PATH_thisScript = isset($_SERVER['argv'][0]) ? $_SERVER['argv'][0] : (isset($_ENV['_']) ? $_ENV['_'] : $_SERVER['_']);
 
-	// Figure out if the path is relative
-$relativePath = FALSE;
-if (stristr(PHP_OS,'win') && !stristr(PHP_OS,'darwin')) {
-		// Windows
-	if (!preg_match('/^([A-Z]:)?\\\/', $temp_PATH_thisScript)) {
-		$relativePath = TRUE;
-	}
-} else {
-		// *nix, et al
-	if ($temp_PATH_thisScript{0} != '/') {
-		$relativePath = TRUE;
-	}
-}
-
-	// Resolve path
-if ($relativePath) {
-	$workingDirectory = $_SERVER['PWD'] ? $_SERVER['PWD'] : getcwd();
-	if ($workingDirectory) {
-		$temp_PATH_thisScript =
-			$workingDirectory.'/'.preg_replace('/\.\//','',$temp_PATH_thisScript);
-		if (!@is_file($temp_PATH_thisScript)) {
-			fwrite(STDERR, 'Relative path found, but an error occurred while resolving the absolute path: ' . $temp_PATH_thisScript . chr(10));
-			exit(1);
-		}
-	} else {
-		fwrite(STDERR, 'Relative path found, but resolving absolute path is not supported on this platform.' . chr(10));
-		exit(1);
-	}
-}
-
-	// Define absolute path to this script
-define('PATH_thisScript',$temp_PATH_thisScript);
 
 if (!isset($_SERVER['argv'][1]))	{
 	fwrite(STDERR, 'The first argument must be a valid key.' . chr(10));
@@ -114,7 +80,7 @@ if (!isset($_SERVER['argv'][1]))	{
 define('TYPO3_cliKey', $_SERVER['argv'][1]);
 
 	// Include init file:
-require(dirname(PATH_thisScript).'/init.php');
+require(dirname(__FILE__) . '/init.php');
 
 	// Make sure output is not buffered,
 	// so that command-line output and interaction can take place
diff --git a/typo3/init.php b/typo3/init.php
index 83395ff84652..a5763088e95d 100644
--- a/typo3/init.php
+++ b/typo3/init.php
@@ -76,113 +76,13 @@ ob_start();
 // *******************************
 // Define constants
 // *******************************
-define('TYPO3_OS', stristr(PHP_OS,'win')&&!stristr(PHP_OS,'darwin')?'WIN':'');
 define('TYPO3_MODE','BE');
-define('PATH_thisScript', str_replace('//', '/', str_replace('\\', '/',
-	(PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == 'isapi' || PHP_SAPI == 'cgi-fcgi') &&
-	($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) ?
-	($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) :
-	($_SERVER['ORIG_SCRIPT_FILENAME'] ? $_SERVER['ORIG_SCRIPT_FILENAME'] : $_SERVER['SCRIPT_FILENAME']))));
 
-define('TYPO3_mainDir', 'typo3/');		// This is the directory of the backend administration for the sites of this TYPO3 installation.
+require_once('Bootstrap.php');
+Typo3_Bootstrap::defineBaseConstants();
+Typo3_Bootstrap::defineAndCheckPaths('typo3/');
 
 
-// *******************************
-// Fix BACK_PATH, if the TYPO3_mainDir is set to something else than
-// typo3/, this is a workaround because the conf.php of the old modules
-// still have "typo3/" hardcoded. Can be removed once we don't have to worry about
-// legacy modules (with conf.php and $BACK_PATH) anymore. See RFC / Bug #13262 for more details.
-// *******************************
-if (isset($BACK_PATH) && strlen($BACK_PATH) > 0 && TYPO3_mainDir != 'typo3/' && substr($BACK_PATH, -7) == '/typo3/') {
-	$BACK_PATH = substr($BACK_PATH, 0, -6) . TYPO3_mainDir;
-}
-
-// *******************************
-// Checking path
-// *******************************
-$temp_path = str_replace('\\','/',dirname(PATH_thisScript).'/');
-$temp_modPath='';
-	// If TYPO3_MOD_PATH is defined we must calculate the modPath since init.php must be included by a module
-if (substr($temp_path,-strlen(TYPO3_mainDir))!=TYPO3_mainDir)	{
-	if (defined('TYPO3_MOD_PATH'))	{
-		if (substr($temp_path,-strlen(TYPO3_MOD_PATH))==TYPO3_MOD_PATH)	{
-			$temp_path=substr($temp_path,0,-strlen(TYPO3_MOD_PATH));
-			$temp_modPath=TYPO3_MOD_PATH;
-		} elseif (substr(TYPO3_MOD_PATH,0,13)=='../typo3conf/' && (substr(TYPO3_MOD_PATH,3)==substr($temp_path,-strlen(substr(TYPO3_MOD_PATH,3))))) {
-			$temp_path = substr($temp_path,0,-strlen(substr(TYPO3_MOD_PATH,3))).TYPO3_mainDir;
-			$temp_modPath=TYPO3_MOD_PATH;
-		}
-		if (!@is_dir($temp_path))	{
-			$temp_path='';
-		}
-	}
-}
-
-// OUTPUT error message and exit if there are problems with the path. Otherwise define constants and continue.
-if (!$temp_path || substr($temp_path,-strlen(TYPO3_mainDir))!=TYPO3_mainDir)	{	// This must be the case in order to proceed
-	if (TYPO3_OS=='WIN')	{
-		$thisPath_base = basename(substr($temp_path,-strlen(TYPO3_mainDir)));
-		$mainPath_base = basename(TYPO3_mainDir);
-		if (!strcasecmp($thisPath, $mainPath))	{	// Seems like the requested URL is not case-specific. This may happen on Windows only. -case. Otherwise, redirect to the correct URL. TYPO3_mainDir must be lower-case!!
-			$script_name = (PHP_SAPI=='fpm-fcgi' || PHP_SAPI=='cgi' || PHP_SAPI=='cgi-fcgi') &&
-				($_SERVER['ORIG_PATH_INFO'] ? $_SERVER['ORIG_PATH_INFO'] : $_SERVER['PATH_INFO']) ?
-				($_SERVER['ORIG_PATH_INFO'] ? $_SERVER['ORIG_PATH_INFO'] : $_SERVER['PATH_INFO']) :
-				($_SERVER['ORIG_SCRIPT_NAME']?$_SERVER['ORIG_SCRIPT_NAME']:$_SERVER['SCRIPT_NAME']);	// Copied from t3lib_div::getIndpEnv()
-
-			header('Location: '.str_replace($thisPath_base, $mainPath_base, $script_name));
-			exit;
-		}
-	}
-
-	echo 'Error in init.php: Path to TYPO3 main dir could not be resolved correctly. <br /><br />';
-
-	echo '<font color="red"><strong>';
-	if (strstr($temp_path,'typo3_src')) {
-		echo 'It seems you are trying to run the TYPO3 source libraries DIRECTLY! You cannot do that.<br />
-		Please read the installation documents for more information.';
-	} else {
-		$temp_path_parts = explode('/', $temp_path);
-		$temp_path_parts = array_slice($temp_path_parts, count($temp_path_parts) - 3);
-		$temp_path = '..../' . implode('/', $temp_path_parts);
-		echo 'This happens if the last ' . strlen(TYPO3_mainDir) . ' characters of this path, ' . $temp_path . ' (end of $temp_path), is NOT "' . TYPO3_mainDir . '" for some reason.<br />
-		You may have a strange server configuration.
-		Or maybe you didn\'t set constant TYPO3_MOD_PATH in your module?';
-	}
-	echo '</strong></font>';
-
-	echo '<br /><br />If you want to debug this issue, please edit typo3/init.php of your TYPO3 source and search for the die() call right after this line (search for this text to find)...';
-
-// Remove this line if you want to debug this problem a little more...
-die();
-	echo '<br /><br /><strong>If you expect any help from anybody on this issue, you should save this page as an html document and send it along with your request for help!</strong>';
-	echo '<hr /><pre>';
-	print_r(array(
-		'TYPO3_OS'=>TYPO3_OS,
-		'PATH_thisScript'=>PATH_thisScript,
-		'php_sapi_name()'=>PHP_SAPI,
-		'TYPO3_MOD_PATH'=>TYPO3_MOD_PATH,
-		'PATH_TRANSLATED'=>$_SERVER['PATH_TRANSLATED'],
-		'SCRIPT_FILENAME'=>$_SERVER['SCRIPT_FILENAME']
-	));
-	echo '</pre><hr />';
-	phpinfo();
-	exit;
-} else {
-	define('PATH_typo3', $temp_path);			// Abs. path of the TYPO3 admin dir (PATH_site + TYPO3_mainDir).
-	define('PATH_typo3_mod', $temp_modPath);	// Relative path (from the PATH_typo3) to a properly configured module
-	define('PATH_site', substr(PATH_typo3,0,-strlen(TYPO3_mainDir)));	// Abs. path to directory with the frontend (one above the admin-dir)
-	$temp_path_t3lib = @is_dir(PATH_site.'t3lib/') ? PATH_site.'t3lib/' : PATH_typo3.'t3lib/';
-	define('PATH_t3lib', $temp_path_t3lib);			// Abs. path to t3lib/ (general TYPO3 library) within the TYPO3 admin dir
-	define('PATH_typo3conf', PATH_site.'typo3conf/');	// Abs. TYPO3 configuration path (local, not part of source)
-
-	if (!defined('PATH_tslib')) {
-		if (@is_dir(PATH_site . TYPO3_mainDir . 'sysext/cms/tslib/')) {
-			define('PATH_tslib', PATH_site . TYPO3_mainDir . 'sysext/cms/tslib/');
-		} elseif (@is_dir(PATH_site . 'tslib/')) {
-			define('PATH_tslib', PATH_site . 'tslib/');
-		}
-	}
-}
 
 // *********************
 // Unset variable(s) in global scope (fixes #13959)
diff --git a/typo3/sysext/beuser/mod/conf.php b/typo3/sysext/beuser/mod/conf.php
index 37839794f23f..694d8aa1b737 100755
--- a/typo3/sysext/beuser/mod/conf.php
+++ b/typo3/sysext/beuser/mod/conf.php
@@ -1,7 +1,4 @@
 <?php
-#define('TYPO3_MOD_PATH', 'sysext/beuser/mod/');
-#$BACK_PATH='../../../';
-
 $MLANG['default']['tabs_images']['tab'] = 'beuser.gif';
 $MLANG['default']['ll_ref']='LLL:EXT:beuser/mod/locallang_mod.xml';
 
diff --git a/typo3/sysext/cms/tslib/index_ts.php b/typo3/sysext/cms/tslib/index_ts.php
index 2879349d9427..ac78e7ddb9ff 100644
--- a/typo3/sysext/cms/tslib/index_ts.php
+++ b/typo3/sysext/cms/tslib/index_ts.php
@@ -47,17 +47,8 @@ if (version_compare(phpversion(), '5.3', '<'))	die ('TYPO3 requires PHP 5.3.0 or
 // Constants defined
 // ******************
 $TYPO3_MISC['microtime_start'] = microtime(TRUE);
-define('TYPO3_OS', stristr(PHP_OS,'win')&&!stristr(PHP_OS,'darwin')?'WIN':'');
 define('TYPO3_MODE','FE');
 
-if (!defined('PATH_t3lib')) 		define('PATH_t3lib', PATH_site.'t3lib/');
-
-define('TYPO3_mainDir', 'typo3/');		// This is the directory of the backend administration for the sites of this TYPO3 installation.
-define('PATH_typo3', PATH_site.TYPO3_mainDir);
-define('PATH_typo3conf', PATH_site.'typo3conf/');
-
-if (!@is_dir(PATH_typo3conf))	die('Cannot find configuration. This file is probably executed from the wrong location.');
-
 // *********************
 // Unset variable(s) in global scope (fixes #13959)
 // *********************
diff --git a/typo3/sysext/em/classes/conf.php b/typo3/sysext/em/classes/conf.php
index d7824a6453af..e08f0526ba05 100644
--- a/typo3/sysext/em/classes/conf.php
+++ b/typo3/sysext/em/classes/conf.php
@@ -1,7 +1,4 @@
 <?php
-define('TYPO3_MOD_PATH', 'typo3/sysext/em/classes/');
-$BACK_PATH='';
-
 $MLANG['default']['tabs_images']['tab'] = 'em.gif';
 $MLANG['default']['ll_ref'] = 'LLL:EXT:em/language/locallang.xml';
 
diff --git a/typo3/sysext/install/mod/class.tx_install_ajax.php b/typo3/sysext/install/mod/class.tx_install_ajax.php
index c67863b193d6..c872d6bbf416 100644
--- a/typo3/sysext/install/mod/class.tx_install_ajax.php
+++ b/typo3/sysext/install/mod/class.tx_install_ajax.php
@@ -25,39 +25,6 @@
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/
 
-
-
-// *******************************
-// Set error reporting
-// *******************************
-error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
-
-
-// ***********************
-// Paths are setup
-// ***********************
-define('TYPO3_OS', stristr(PHP_OS,'win')&&!stristr(PHP_OS,'darwin')?'WIN':'');
-define('TYPO3_MODE','FE');
-
-if(!defined('PATH_thisScript')) {
-	define('PATH_thisScript', str_replace('//', '/', str_replace('\\', '/',
-		(PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == 'isapi' || PHP_SAPI == 'cgi-fcgi') &&
-		($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) ?
-		($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) :
-		($_SERVER['ORIG_SCRIPT_FILENAME'] ? $_SERVER['ORIG_SCRIPT_FILENAME'] : $_SERVER['SCRIPT_FILENAME']))));
-}
-
-if (!defined('PATH_site')) 			define('PATH_site', dirname(PATH_thisScript).'/');
-if (!defined('PATH_t3lib')) 		define('PATH_t3lib', PATH_site.'t3lib/');
-define('PATH_tslib', PATH_site.'tslib/');
-define('PATH_typo3conf', PATH_site.'typo3conf/');
-define('TYPO3_mainDir', 'typo3/');		// This is the directory of the backend administration for the sites of this TYPO3 installation.
-
-if (!@is_dir(PATH_typo3conf))	die('Cannot find configuration. This file is probably executed from the wrong location.');
-
-
-require_once(PATH_t3lib.'class.t3lib_div.php');
-
 /**
  * This is the eID handler for install tool AJAX calls.
  *
diff --git a/typo3/thumbs.php b/typo3/thumbs.php
index 7d42d7c75d35..62931381e372 100644
--- a/typo3/thumbs.php
+++ b/typo3/thumbs.php
@@ -35,21 +35,11 @@
 // *******************************
 error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
 
-
-define('PATH_thisScript', str_replace('//', '/', str_replace('\\', '/',
-	(PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == 'isapi' || PHP_SAPI == 'cgi-fcgi') &&
-	($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) ?
-	($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) :
-	($_SERVER['ORIG_SCRIPT_FILENAME'] ? $_SERVER['ORIG_SCRIPT_FILENAME'] : $_SERVER['SCRIPT_FILENAME']))));
-
-define('PATH_site', substr(dirname(PATH_thisScript).'/',0,-strlen('typo3/')));	// Abs. path to directory with the frontend (one above the admin-dir)
-define('PATH_t3lib', PATH_site.'t3lib/');
-
+require('init.php');
 
 // ******************
 // include thumbs script
 // ******************
-require ('init.php');
-require (PATH_t3lib.'thumbs.php');
+require (PATH_t3lib . 'thumbs.php');
 
 ?>
\ No newline at end of file
-- 
GitLab