[!!!][TASK] Remove deprecated Extbase Domain Models / Repositories / Converters
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Core / SystemEnvironmentBuilder.php
1 <?php
2
3 /*
4 * This file is part of the TYPO3 CMS project.
5 *
6 * It is free software; you can redistribute it and/or modify it under
7 * the terms of the GNU General Public License, either version 2
8 * of the License, or any later version.
9 *
10 * For the full copyright and license information, please read the
11 * LICENSE.txt file that was distributed with this source code.
12 *
13 * The TYPO3 project - inspiring people to share!
14 */
15
16 namespace TYPO3\CMS\Core\Core;
17
18 use TYPO3\CMS\Core\Utility\GeneralUtility;
19 use TYPO3\CMS\Core\Utility\PathUtility;
20
21 /**
22 * Class to encapsulate base setup of bootstrap.
23 *
24 * This class contains all code that must be executed by every entry script.
25 *
26 * It sets up all basic paths, constants, global variables and checks
27 * the basic environment TYPO3 runs in.
28 *
29 * This class does not use any TYPO3 instance specific configuration, it only
30 * sets up things based on the server environment and core code. Even with a
31 * missing typo3conf/LocalConfiguration.php this script will be successful.
32 *
33 * The script aborts execution with an error message if
34 * some part fails or conditions are not met.
35 *
36 * This script is internal code and subject to change.
37 * DO NOT use it in own code, or be prepared your code might
38 * break in future versions of the core.
39 */
40 class SystemEnvironmentBuilder
41 {
42 /** @internal */
43 const REQUESTTYPE_FE = 1;
44 /** @internal */
45 const REQUESTTYPE_BE = 2;
46 /** @internal */
47 const REQUESTTYPE_CLI = 4;
48 /** @internal */
49 const REQUESTTYPE_AJAX = 8;
50 /** @internal */
51 const REQUESTTYPE_INSTALL = 16;
52
53 /**
54 * Run base setup.
55 * This entry method is used in all scopes (FE, BE, Install Tool and CLI)
56 *
57 * @internal This method should not be used by 3rd party code. It will change without further notice.
58 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
59 * @param int $requestType
60 */
61 public static function run(int $entryPointLevel = 0, int $requestType = self::REQUESTTYPE_FE)
62 {
63 self::defineBaseConstants();
64 self::defineTypo3RequestTypes();
65 self::setRequestType($requestType | ($requestType === self::REQUESTTYPE_BE && strpos($_REQUEST['route'] ?? '', '/ajax/') === 0 ? TYPO3_REQUESTTYPE_AJAX : 0));
66 self::defineLegacyConstants($requestType === self::REQUESTTYPE_FE ? 'FE' : 'BE');
67 $scriptPath = self::calculateScriptPath($entryPointLevel, $requestType);
68 $rootPath = self::calculateRootPath($entryPointLevel, $requestType);
69
70 self::initializeGlobalVariables();
71 self::initializeGlobalTimeTrackingVariables();
72 self::initializeEnvironment($requestType, $scriptPath, $rootPath);
73 }
74
75 /**
76 * Some notes:
77 *
78 * HTTP_TYPO3_CONTEXT -> used with Apache suexec support
79 * REDIRECT_TYPO3_CONTEXT -> used under some circumstances when value is set in the webserver and proxying the values to FPM
80 * @return ApplicationContext
81 * @throws \TYPO3\CMS\Core\Exception
82 */
83 protected static function createApplicationContext(): ApplicationContext
84 {
85 $applicationContext = getenv('TYPO3_CONTEXT') ?: (getenv('REDIRECT_TYPO3_CONTEXT') ?: (getenv('HTTP_TYPO3_CONTEXT') ?: 'Production'));
86 return new ApplicationContext($applicationContext);
87 }
88
89 /**
90 * Define all simple constants that have no dependency to local configuration
91 */
92 protected static function defineBaseConstants()
93 {
94 // A linefeed, a carriage return, a CR-LF combination
95 defined('LF') ?: define('LF', chr(10));
96 defined('CR') ?: define('CR', chr(13));
97 defined('CRLF') ?: define('CRLF', CR . LF);
98
99 // Relative path from document root to typo3/ directory, hardcoded to "typo3/"
100 if (!defined('TYPO3_mainDir')) {
101 define('TYPO3_mainDir', 'typo3/');
102 }
103 }
104
105 /**
106 * Calculate script path. This is the absolute path to the entry script.
107 * Can be something like '.../public/index.php' or '.../public/typo3/index.php' for
108 * web calls, or '.../bin/typo3' or similar for cli calls.
109 *
110 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
111 * @param int $requestType
112 * @return string Absolute path to entry script
113 */
114 protected static function calculateScriptPath(int $entryPointLevel, int $requestType): string
115 {
116 $isCli = self::isCliRequestType($requestType);
117 // Absolute path of the entry script that was called
118 $scriptPath = GeneralUtility::fixWindowsFilePath(self::getPathThisScript($isCli));
119 $rootPath = self::getRootPathFromScriptPath($scriptPath, $entryPointLevel);
120 // Check if the root path has been set in the environment (e.g. by the composer installer)
121 if (getenv('TYPO3_PATH_ROOT')) {
122 if ($isCli && self::usesComposerClassLoading()) {
123 // $scriptPath is used for various path calculations based on the document root
124 // Therefore we assume it is always a subdirectory of the document root, which is not the case
125 // in composer mode on cli, as the binary is in the composer bin directory.
126 // Because of that, we enforce the document root path of this binary to be set
127 $scriptName = 'typo3/sysext/core/bin/typo3';
128 } else {
129 // Base the script path on the path taken from the environment
130 // to make relative path calculations work in case only one of both is symlinked
131 // or has the real path
132 $scriptName = ltrim(substr($scriptPath, strlen($rootPath)), '/');
133 }
134 $rootPath = rtrim(GeneralUtility::fixWindowsFilePath(getenv('TYPO3_PATH_ROOT')), '/');
135 $scriptPath = $rootPath . '/' . $scriptName;
136 }
137 return $scriptPath;
138 }
139
140 /**
141 * Absolute path to the "classic" site root of the TYPO3 application.
142 * This semantically refers to the directory where executable server-side code, configuration
143 * and runtime files are located (e.g. typo3conf/ext, typo3/sysext, typo3temp/var).
144 * In practice this is always identical to the public web document root path which contains
145 * files that are served by the webserver directly (fileadmin/ and public resources).
146 *
147 * This is not to be confused with the app-path that is used in composer-mode installations (by default).
148 * Resources in app-path are located outside the document root.
149 *
150 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
151 * @param int $requestType
152 * @return string Absolute path without trailing slash
153 */
154 protected static function calculateRootPath(int $entryPointLevel, int $requestType): string
155 {
156 // Check if the root path has been set in the environment (e.g. by the composer installer)
157 if (getenv('TYPO3_PATH_ROOT')) {
158 return rtrim(GeneralUtility::fixWindowsFilePath(getenv('TYPO3_PATH_ROOT')), '/');
159 }
160 $isCli = self::isCliRequestType($requestType);
161 // Absolute path of the entry script that was called
162 $scriptPath = GeneralUtility::fixWindowsFilePath(self::getPathThisScript($isCli));
163 return self::getRootPathFromScriptPath($scriptPath, $entryPointLevel);
164 }
165
166 /**
167 * Set up / initialize several globals variables
168 */
169 protected static function initializeGlobalVariables()
170 {
171 // Unset variable(s) in global scope (security issue #13959)
172 $GLOBALS['T3_SERVICES'] = [];
173 }
174
175 /**
176 * Initialize global time tracking variables.
177 * These are helpers to for example output script parsetime at the end of a script.
178 */
179 protected static function initializeGlobalTimeTrackingVariables()
180 {
181 // EXEC_TIME is set so that the rest of the script has a common value for the script execution time
182 $GLOBALS['EXEC_TIME'] = time();
183 // $ACCESS_TIME is a common time in minutes for access control
184 $GLOBALS['ACCESS_TIME'] = $GLOBALS['EXEC_TIME'] - $GLOBALS['EXEC_TIME'] % 60;
185 // $SIM_EXEC_TIME is set to $EXEC_TIME but can be altered later in the script if we want to
186 // simulate another execution-time when selecting from eg. a database
187 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
188 // If $SIM_EXEC_TIME is changed this value must be set accordingly
189 $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
190 }
191
192 /**
193 * Initialize the Environment class
194 *
195 * @param int $requestType
196 * @param string $scriptPath
197 * @param string $sitePath
198 */
199 protected static function initializeEnvironment(int $requestType, string $scriptPath, string $sitePath)
200 {
201 if (getenv('TYPO3_PATH_ROOT')) {
202 $rootPathFromEnvironment = rtrim(GeneralUtility::fixWindowsFilePath(getenv('TYPO3_PATH_ROOT')), '/');
203 if ($sitePath !== $rootPathFromEnvironment) {
204 // This means, that we re-initialized the environment during a single request
205 // This currently only happens in custom code or during functional testing
206 // Once the constants are removed, we might be able to remove this code here as well and directly pass an environment to the application
207 $scriptPath = $rootPathFromEnvironment . substr($scriptPath, strlen($sitePath));
208 $sitePath = $rootPathFromEnvironment;
209 }
210 }
211
212 $projectRootPath = GeneralUtility::fixWindowsFilePath(getenv('TYPO3_PATH_APP'));
213 $isDifferentRootPath = ($projectRootPath && $projectRootPath !== $sitePath);
214 Environment::initialize(
215 static::createApplicationContext(),
216 self::isCliRequestType($requestType),
217 self::usesComposerClassLoading(),
218 $isDifferentRootPath ? $projectRootPath : $sitePath,
219 $sitePath,
220 $isDifferentRootPath ? $projectRootPath . '/var' : $sitePath . '/typo3temp/var',
221 $isDifferentRootPath ? $projectRootPath . '/config' : $sitePath . '/typo3conf',
222 $scriptPath,
223 self::isRunningOnWindows() ? 'WINDOWS' : 'UNIX'
224 );
225 }
226
227 /**
228 * Determine if the operating system TYPO3 is running on is windows.
229 */
230 protected static function isRunningOnWindows(): bool
231 {
232 return stripos(PHP_OS, 'darwin') === false
233 && stripos(PHP_OS, 'cygwin') === false
234 && stripos(PHP_OS, 'win') !== false;
235 }
236
237 /**
238 * Calculate script path.
239 *
240 * First step in path calculation: Goal is to find the absolute path of the entry script
241 * that was called without resolving any links. This is important since the TYPO3 entry
242 * points are often linked to a central core location, so we can not use the php magic
243 * __FILE__ here, but resolve the called script path from given server environments.
244 *
245 * This path is important to calculate the document root. The strategy is to
246 * find out the script name that was called in the first place and to subtract the local
247 * part from it to find the document root.
248 *
249 * @param bool $isCli
250 * @return string Absolute path to entry script
251 */
252 protected static function getPathThisScript(bool $isCli)
253 {
254 if ($isCli) {
255 return self::getPathThisScriptCli();
256 }
257 return self::getPathThisScriptNonCli();
258 }
259
260 /**
261 * Calculate path to entry script if not in cli mode.
262 *
263 * Depending on the environment, the script path is found in different $_SERVER variables.
264 *
265 * @return string Absolute path to entry script
266 */
267 protected static function getPathThisScriptNonCli()
268 {
269 $cgiPath = $_SERVER['ORIG_PATH_TRANSLATED'] ?? $_SERVER['PATH_TRANSLATED'] ?? '';
270 if ($cgiPath && Environment::isRunningOnCgiServer()) {
271 return $cgiPath;
272 }
273 return $_SERVER['ORIG_SCRIPT_FILENAME'] ?? $_SERVER['SCRIPT_FILENAME'];
274 }
275
276 /**
277 * Calculate path to entry script if in cli mode.
278 *
279 * First argument of a cli script is the path to the script that was called. If the script does not start
280 * with / (or A:\ for Windows), the path is not absolute yet, and the current working directory is added.
281 *
282 * @return string Absolute path to entry script
283 */
284 protected static function getPathThisScriptCli()
285 {
286 // Possible relative path of the called script
287 $scriptPath = $_SERVER['argv'][0] ?? $_ENV['_'] ?? $_SERVER['_'];
288 // Find out if path is relative or not
289 $isRelativePath = false;
290 if (self::isRunningOnWindows()) {
291 if (!preg_match('/^([a-zA-Z]:)?\\\\/', $scriptPath)) {
292 $isRelativePath = true;
293 }
294 } elseif ($scriptPath[0] !== '/') {
295 $isRelativePath = true;
296 }
297 // Concatenate path to current working directory with relative path and remove "/./" constructs
298 if ($isRelativePath) {
299 $workingDirectory = $_SERVER['PWD'] ?? getcwd();
300 $scriptPath = $workingDirectory . '/' . preg_replace('/\\.\\//', '', $scriptPath);
301 }
302 return $scriptPath;
303 }
304
305 /**
306 * Calculate the document root part to the instance from $scriptPath.
307 * This is based on the amount of subdirectories "under" root path where $scriptPath is located.
308 *
309 * The following main scenarios for entry points exist by default in the TYPO3 core:
310 * - Directly called documentRoot/index.php (-> FE call or eiD include): index.php is located in the same directory
311 * as the main project. The document root is identical to the directory the script is located at.
312 * - The install tool, located under typo3/install.php.
313 * - A Backend script: This is the case for the typo3/index.php dispatcher and other entry scripts like 'typo3/sysext/core/bin/typo3'
314 * or 'typo3/index.php' that are located inside typo3/ directly.
315 *
316 * @param string $scriptPath Calculated path to the entry script
317 * @param int $entryPointLevel Number of subdirectories where the entry script is located under the document root
318 * @return string Absolute path to document root of installation without trailing slash
319 */
320 protected static function getRootPathFromScriptPath($scriptPath, $entryPointLevel)
321 {
322 $entryScriptDirectory = PathUtility::dirnameDuringBootstrap($scriptPath);
323 if ($entryPointLevel > 0) {
324 [$rootPath] = GeneralUtility::revExplode('/', $entryScriptDirectory, $entryPointLevel + 1);
325 } else {
326 $rootPath = $entryScriptDirectory;
327 }
328 return $rootPath;
329 }
330
331 /**
332 * @return bool
333 */
334 protected static function usesComposerClassLoading(): bool
335 {
336 return defined('TYPO3_COMPOSER_MODE') && TYPO3_COMPOSER_MODE;
337 }
338
339 /**
340 * Define TYPO3_REQUESTTYPE* constants that can be used for developers to see if any context has been hit
341 * also see setRequestType(). Is done at the very beginning so these parameters are always available.
342 */
343 protected static function defineTypo3RequestTypes()
344 {
345 // Check one of the constants and return early if already defined,
346 // needed if multiple requests are handled in one process, for instance in functional testing.
347 if (defined('TYPO3_REQUESTTYPE_FE')) {
348 return;
349 }
350 define('TYPO3_REQUESTTYPE_FE', self::REQUESTTYPE_FE);
351 define('TYPO3_REQUESTTYPE_BE', self::REQUESTTYPE_BE);
352 define('TYPO3_REQUESTTYPE_CLI', self::REQUESTTYPE_CLI);
353 define('TYPO3_REQUESTTYPE_AJAX', self::REQUESTTYPE_AJAX);
354 define('TYPO3_REQUESTTYPE_INSTALL', self::REQUESTTYPE_INSTALL);
355 }
356
357 /**
358 * Defines the TYPO3_REQUESTTYPE constant so the environment knows which context the request is running.
359 *
360 * @param int $requestType
361 */
362 protected static function setRequestType(int $requestType)
363 {
364 // Return early if already defined,
365 // needed if multiple requests are handled in one process, for instance in functional testing.
366 if (defined('TYPO3_REQUESTTYPE')) {
367 return;
368 }
369 define('TYPO3_REQUESTTYPE', $requestType);
370 }
371
372 /**
373 * Define constants and variables
374 *
375 * @param string $mode
376 */
377 protected static function defineLegacyConstants(string $mode)
378 {
379 // Return early if already defined,
380 // needed if multiple requests are handled in one process, for instance in functional testing.
381 if (defined('TYPO3_MODE')) {
382 return;
383 }
384 define('TYPO3_MODE', $mode);
385 }
386
387 /**
388 * Checks if request type is cli.
389 * Falls back to check PHP_SAPI in case request type is not provided
390 *
391 * @param int|null $requestType
392 * @return bool
393 */
394 protected static function isCliRequestType(?int $requestType): bool
395 {
396 if ($requestType === null) {
397 $requestType = PHP_SAPI === 'cli' ? self::REQUESTTYPE_CLI : self::REQUESTTYPE_FE;
398 }
399
400 return ($requestType & self::REQUESTTYPE_CLI) === self::REQUESTTYPE_CLI;
401 }
402 }