Completed
Push — master ( 39c63d...c3f16a )
by John
27:19 queued 16s
created
lib/autoloader.php 2 patches
Indentation   +145 added lines, -145 removed lines patch added patch discarded remove patch
@@ -15,149 +15,149 @@
 block discarded – undo
15 15
 use Psr\Log\LoggerInterface;
16 16
 
17 17
 class Autoloader {
18
-	/** @var bool */
19
-	private $useGlobalClassPath = true;
20
-	/** @var array */
21
-	private $validRoots = [];
22
-
23
-	/**
24
-	 * Optional low-latency memory cache for class to path mapping.
25
-	 */
26
-	protected ?ICache $memoryCache = null;
27
-
28
-	/**
29
-	 * Autoloader constructor.
30
-	 *
31
-	 * @param string[] $validRoots
32
-	 */
33
-	public function __construct(array $validRoots) {
34
-		foreach ($validRoots as $root) {
35
-			$this->validRoots[$root] = true;
36
-		}
37
-	}
38
-
39
-	/**
40
-	 * Add a path to the list of valid php roots for auto loading
41
-	 *
42
-	 * @param string $root
43
-	 */
44
-	public function addValidRoot(string $root): void {
45
-		$root = stream_resolve_include_path($root);
46
-		$this->validRoots[$root] = true;
47
-	}
48
-
49
-	/**
50
-	 * disable the usage of the global classpath \OC::$CLASSPATH
51
-	 */
52
-	public function disableGlobalClassPath(): void {
53
-		$this->useGlobalClassPath = false;
54
-	}
55
-
56
-	/**
57
-	 * enable the usage of the global classpath \OC::$CLASSPATH
58
-	 */
59
-	public function enableGlobalClassPath(): void {
60
-		$this->useGlobalClassPath = true;
61
-	}
62
-
63
-	/**
64
-	 * get the possible paths for a class
65
-	 *
66
-	 * @param string $class
67
-	 * @return array an array of possible paths
68
-	 */
69
-	public function findClass(string $class): array {
70
-		$class = trim($class, '\\');
71
-
72
-		$paths = [];
73
-		if ($this->useGlobalClassPath && array_key_exists($class, \OC::$CLASSPATH)) {
74
-			$paths[] = \OC::$CLASSPATH[$class];
75
-			/**
76
-			 * @TODO: Remove this when necessary
77
-			 * Remove "apps/" from inclusion path for smooth migration to multi app dir
78
-			 */
79
-			if (strpos(\OC::$CLASSPATH[$class], 'apps/') === 0) {
80
-				\OCP\Server::get(LoggerInterface::class)->debug('include path for class "' . $class . '" starts with "apps/"', ['app' => 'core']);
81
-				$paths[] = str_replace('apps/', '', \OC::$CLASSPATH[$class]);
82
-			}
83
-		} elseif (strpos($class, 'OC_') === 0) {
84
-			$paths[] = \OC::$SERVERROOT . '/lib/private/legacy/' . strtolower(str_replace('_', '/', substr($class, 3)) . '.php');
85
-		} elseif (strpos($class, 'OCA\\') === 0) {
86
-			[, $app, $rest] = explode('\\', $class, 3);
87
-			$app = strtolower($app);
88
-			try {
89
-				$appPath = \OCP\Server::get(IAppManager::class)->getAppPath($app);
90
-				if (stream_resolve_include_path($appPath)) {
91
-					$paths[] = $appPath . '/' . strtolower(str_replace('\\', '/', $rest) . '.php');
92
-					// If not found in the root of the app directory, insert '/lib' after app id and try again.
93
-					$paths[] = $appPath . '/lib/' . strtolower(str_replace('\\', '/', $rest) . '.php');
94
-				}
95
-			} catch (AppPathNotFoundException) {
96
-				// App not found, ignore
97
-			}
98
-		}
99
-		return $paths;
100
-	}
101
-
102
-	/**
103
-	 * @param string $fullPath
104
-	 * @return bool
105
-	 * @throws AutoloadNotAllowedException
106
-	 */
107
-	protected function isValidPath(string $fullPath): bool {
108
-		foreach ($this->validRoots as $root => $true) {
109
-			if (substr($fullPath, 0, strlen($root) + 1) === $root . '/') {
110
-				return true;
111
-			}
112
-		}
113
-		throw new AutoloadNotAllowedException($fullPath);
114
-	}
115
-
116
-	/**
117
-	 * Load the specified class
118
-	 *
119
-	 * @param string $class
120
-	 * @return bool
121
-	 * @throws AutoloadNotAllowedException
122
-	 */
123
-	public function load(string $class): bool {
124
-		if (class_exists($class, false)) {
125
-			return false;
126
-		}
127
-
128
-		$pathsToRequire = null;
129
-		if ($this->memoryCache) {
130
-			$pathsToRequire = $this->memoryCache->get($class);
131
-		}
132
-
133
-		if (!is_array($pathsToRequire)) {
134
-			// No cache or cache miss
135
-			$pathsToRequire = [];
136
-			foreach ($this->findClass($class) as $path) {
137
-				$fullPath = stream_resolve_include_path($path);
138
-				if ($fullPath && $this->isValidPath($fullPath)) {
139
-					$pathsToRequire[] = $fullPath;
140
-				}
141
-			}
142
-
143
-			if ($this->memoryCache) {
144
-				$this->memoryCache->set($class, $pathsToRequire, 60); // cache 60 sec
145
-			}
146
-		}
147
-
148
-		foreach ($pathsToRequire as $fullPath) {
149
-			require_once $fullPath;
150
-		}
151
-
152
-		return false;
153
-	}
154
-
155
-	/**
156
-	 * Sets the optional low-latency cache for class to path mapping.
157
-	 *
158
-	 * @param ICache $memoryCache Instance of memory cache.
159
-	 */
160
-	public function setMemoryCache(?ICache $memoryCache = null): void {
161
-		$this->memoryCache = $memoryCache;
162
-	}
18
+    /** @var bool */
19
+    private $useGlobalClassPath = true;
20
+    /** @var array */
21
+    private $validRoots = [];
22
+
23
+    /**
24
+     * Optional low-latency memory cache for class to path mapping.
25
+     */
26
+    protected ?ICache $memoryCache = null;
27
+
28
+    /**
29
+     * Autoloader constructor.
30
+     *
31
+     * @param string[] $validRoots
32
+     */
33
+    public function __construct(array $validRoots) {
34
+        foreach ($validRoots as $root) {
35
+            $this->validRoots[$root] = true;
36
+        }
37
+    }
38
+
39
+    /**
40
+     * Add a path to the list of valid php roots for auto loading
41
+     *
42
+     * @param string $root
43
+     */
44
+    public function addValidRoot(string $root): void {
45
+        $root = stream_resolve_include_path($root);
46
+        $this->validRoots[$root] = true;
47
+    }
48
+
49
+    /**
50
+     * disable the usage of the global classpath \OC::$CLASSPATH
51
+     */
52
+    public function disableGlobalClassPath(): void {
53
+        $this->useGlobalClassPath = false;
54
+    }
55
+
56
+    /**
57
+     * enable the usage of the global classpath \OC::$CLASSPATH
58
+     */
59
+    public function enableGlobalClassPath(): void {
60
+        $this->useGlobalClassPath = true;
61
+    }
62
+
63
+    /**
64
+     * get the possible paths for a class
65
+     *
66
+     * @param string $class
67
+     * @return array an array of possible paths
68
+     */
69
+    public function findClass(string $class): array {
70
+        $class = trim($class, '\\');
71
+
72
+        $paths = [];
73
+        if ($this->useGlobalClassPath && array_key_exists($class, \OC::$CLASSPATH)) {
74
+            $paths[] = \OC::$CLASSPATH[$class];
75
+            /**
76
+             * @TODO: Remove this when necessary
77
+             * Remove "apps/" from inclusion path for smooth migration to multi app dir
78
+             */
79
+            if (strpos(\OC::$CLASSPATH[$class], 'apps/') === 0) {
80
+                \OCP\Server::get(LoggerInterface::class)->debug('include path for class "' . $class . '" starts with "apps/"', ['app' => 'core']);
81
+                $paths[] = str_replace('apps/', '', \OC::$CLASSPATH[$class]);
82
+            }
83
+        } elseif (strpos($class, 'OC_') === 0) {
84
+            $paths[] = \OC::$SERVERROOT . '/lib/private/legacy/' . strtolower(str_replace('_', '/', substr($class, 3)) . '.php');
85
+        } elseif (strpos($class, 'OCA\\') === 0) {
86
+            [, $app, $rest] = explode('\\', $class, 3);
87
+            $app = strtolower($app);
88
+            try {
89
+                $appPath = \OCP\Server::get(IAppManager::class)->getAppPath($app);
90
+                if (stream_resolve_include_path($appPath)) {
91
+                    $paths[] = $appPath . '/' . strtolower(str_replace('\\', '/', $rest) . '.php');
92
+                    // If not found in the root of the app directory, insert '/lib' after app id and try again.
93
+                    $paths[] = $appPath . '/lib/' . strtolower(str_replace('\\', '/', $rest) . '.php');
94
+                }
95
+            } catch (AppPathNotFoundException) {
96
+                // App not found, ignore
97
+            }
98
+        }
99
+        return $paths;
100
+    }
101
+
102
+    /**
103
+     * @param string $fullPath
104
+     * @return bool
105
+     * @throws AutoloadNotAllowedException
106
+     */
107
+    protected function isValidPath(string $fullPath): bool {
108
+        foreach ($this->validRoots as $root => $true) {
109
+            if (substr($fullPath, 0, strlen($root) + 1) === $root . '/') {
110
+                return true;
111
+            }
112
+        }
113
+        throw new AutoloadNotAllowedException($fullPath);
114
+    }
115
+
116
+    /**
117
+     * Load the specified class
118
+     *
119
+     * @param string $class
120
+     * @return bool
121
+     * @throws AutoloadNotAllowedException
122
+     */
123
+    public function load(string $class): bool {
124
+        if (class_exists($class, false)) {
125
+            return false;
126
+        }
127
+
128
+        $pathsToRequire = null;
129
+        if ($this->memoryCache) {
130
+            $pathsToRequire = $this->memoryCache->get($class);
131
+        }
132
+
133
+        if (!is_array($pathsToRequire)) {
134
+            // No cache or cache miss
135
+            $pathsToRequire = [];
136
+            foreach ($this->findClass($class) as $path) {
137
+                $fullPath = stream_resolve_include_path($path);
138
+                if ($fullPath && $this->isValidPath($fullPath)) {
139
+                    $pathsToRequire[] = $fullPath;
140
+                }
141
+            }
142
+
143
+            if ($this->memoryCache) {
144
+                $this->memoryCache->set($class, $pathsToRequire, 60); // cache 60 sec
145
+            }
146
+        }
147
+
148
+        foreach ($pathsToRequire as $fullPath) {
149
+            require_once $fullPath;
150
+        }
151
+
152
+        return false;
153
+    }
154
+
155
+    /**
156
+     * Sets the optional low-latency cache for class to path mapping.
157
+     *
158
+     * @param ICache $memoryCache Instance of memory cache.
159
+     */
160
+    public function setMemoryCache(?ICache $memoryCache = null): void {
161
+        $this->memoryCache = $memoryCache;
162
+    }
163 163
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -77,20 +77,20 @@  discard block
 block discarded – undo
77 77
 			 * Remove "apps/" from inclusion path for smooth migration to multi app dir
78 78
 			 */
79 79
 			if (strpos(\OC::$CLASSPATH[$class], 'apps/') === 0) {
80
-				\OCP\Server::get(LoggerInterface::class)->debug('include path for class "' . $class . '" starts with "apps/"', ['app' => 'core']);
80
+				\OCP\Server::get(LoggerInterface::class)->debug('include path for class "'.$class.'" starts with "apps/"', ['app' => 'core']);
81 81
 				$paths[] = str_replace('apps/', '', \OC::$CLASSPATH[$class]);
82 82
 			}
83 83
 		} elseif (strpos($class, 'OC_') === 0) {
84
-			$paths[] = \OC::$SERVERROOT . '/lib/private/legacy/' . strtolower(str_replace('_', '/', substr($class, 3)) . '.php');
84
+			$paths[] = \OC::$SERVERROOT.'/lib/private/legacy/'.strtolower(str_replace('_', '/', substr($class, 3)).'.php');
85 85
 		} elseif (strpos($class, 'OCA\\') === 0) {
86 86
 			[, $app, $rest] = explode('\\', $class, 3);
87 87
 			$app = strtolower($app);
88 88
 			try {
89 89
 				$appPath = \OCP\Server::get(IAppManager::class)->getAppPath($app);
90 90
 				if (stream_resolve_include_path($appPath)) {
91
-					$paths[] = $appPath . '/' . strtolower(str_replace('\\', '/', $rest) . '.php');
91
+					$paths[] = $appPath.'/'.strtolower(str_replace('\\', '/', $rest).'.php');
92 92
 					// If not found in the root of the app directory, insert '/lib' after app id and try again.
93
-					$paths[] = $appPath . '/lib/' . strtolower(str_replace('\\', '/', $rest) . '.php');
93
+					$paths[] = $appPath.'/lib/'.strtolower(str_replace('\\', '/', $rest).'.php');
94 94
 				}
95 95
 			} catch (AppPathNotFoundException) {
96 96
 				// App not found, ignore
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
 	 */
107 107
 	protected function isValidPath(string $fullPath): bool {
108 108
 		foreach ($this->validRoots as $root => $true) {
109
-			if (substr($fullPath, 0, strlen($root) + 1) === $root . '/') {
109
+			if (substr($fullPath, 0, strlen($root) + 1) === $root.'/') {
110 110
 				return true;
111 111
 			}
112 112
 		}
Please login to merge, or discard this patch.
lib/base.php 2 patches
Indentation   +1147 added lines, -1147 removed lines patch added patch discarded remove patch
@@ -39,1153 +39,1153 @@
 block discarded – undo
39 39
  * OC_autoload!
40 40
  */
41 41
 class OC {
42
-	/**
43
-	 * Associative array for autoloading. classname => filename
44
-	 */
45
-	public static array $CLASSPATH = [];
46
-	/**
47
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
48
-	 */
49
-	public static string $SERVERROOT = '';
50
-	/**
51
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
52
-	 */
53
-	private static string $SUBURI = '';
54
-	/**
55
-	 * the Nextcloud root path for http requests (e.g. /nextcloud)
56
-	 */
57
-	public static string $WEBROOT = '';
58
-	/**
59
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
60
-	 * web path in 'url'
61
-	 */
62
-	public static array $APPSROOTS = [];
63
-
64
-	public static string $configDir;
65
-
66
-	/**
67
-	 * requested app
68
-	 */
69
-	public static string $REQUESTEDAPP = '';
70
-
71
-	/**
72
-	 * check if Nextcloud runs in cli mode
73
-	 */
74
-	public static bool $CLI = false;
75
-
76
-	public static \OC\Autoloader $loader;
77
-
78
-	public static \Composer\Autoload\ClassLoader $composerAutoloader;
79
-
80
-	public static \OC\Server $server;
81
-
82
-	private static \OC\Config $config;
83
-
84
-	/**
85
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
86
-	 *                           the app path list is empty or contains an invalid path
87
-	 */
88
-	public static function initPaths(): void {
89
-		if (defined('PHPUNIT_CONFIG_DIR')) {
90
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
91
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
92
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
93
-		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
94
-			self::$configDir = rtrim($dir, '/') . '/';
95
-		} else {
96
-			self::$configDir = OC::$SERVERROOT . '/config/';
97
-		}
98
-		self::$config = new \OC\Config(self::$configDir);
99
-
100
-		OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT)));
101
-		/**
102
-		 * FIXME: The following lines are required because we can't yet instantiate
103
-		 *        Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist.
104
-		 */
105
-		$params = [
106
-			'server' => [
107
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null,
108
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null,
109
-			],
110
-		];
111
-		if (isset($_SERVER['REMOTE_ADDR'])) {
112
-			$params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
113
-		}
114
-		$fakeRequest = new \OC\AppFramework\Http\Request(
115
-			$params,
116
-			new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
117
-			new \OC\AllConfig(new \OC\SystemConfig(self::$config))
118
-		);
119
-		$scriptName = $fakeRequest->getScriptName();
120
-		if (substr($scriptName, -1) == '/') {
121
-			$scriptName .= 'index.php';
122
-			//make sure suburi follows the same rules as scriptName
123
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
124
-				if (substr(OC::$SUBURI, -1) != '/') {
125
-					OC::$SUBURI = OC::$SUBURI . '/';
126
-				}
127
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
128
-			}
129
-		}
130
-
131
-		if (OC::$CLI) {
132
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
133
-		} else {
134
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
135
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
136
-
137
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
138
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
139
-				}
140
-			} else {
141
-				// The scriptName is not ending with OC::$SUBURI
142
-				// This most likely means that we are calling from CLI.
143
-				// However some cron jobs still need to generate
144
-				// a web URL, so we use overwritewebroot as a fallback.
145
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
146
-			}
147
-
148
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
149
-			// slash which is required by URL generation.
150
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
151
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
152
-				header('Location: ' . \OC::$WEBROOT . '/');
153
-				exit();
154
-			}
155
-		}
156
-
157
-		// search the apps folder
158
-		$config_paths = self::$config->getValue('apps_paths', []);
159
-		if (!empty($config_paths)) {
160
-			foreach ($config_paths as $paths) {
161
-				if (isset($paths['url']) && isset($paths['path'])) {
162
-					$paths['url'] = rtrim($paths['url'], '/');
163
-					$paths['path'] = rtrim($paths['path'], '/');
164
-					OC::$APPSROOTS[] = $paths;
165
-				}
166
-			}
167
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
168
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
169
-		}
170
-
171
-		if (empty(OC::$APPSROOTS)) {
172
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
173
-				. '. You can also configure the location in the config.php file.');
174
-		}
175
-		$paths = [];
176
-		foreach (OC::$APPSROOTS as $path) {
177
-			$paths[] = $path['path'];
178
-			if (!is_dir($path['path'])) {
179
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
180
-					. ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
181
-			}
182
-		}
183
-
184
-		// set the right include path
185
-		set_include_path(
186
-			implode(PATH_SEPARATOR, $paths)
187
-		);
188
-	}
189
-
190
-	public static function checkConfig(): void {
191
-		// Create config if it does not already exist
192
-		$configFilePath = self::$configDir . '/config.php';
193
-		if (!file_exists($configFilePath)) {
194
-			@touch($configFilePath);
195
-		}
196
-
197
-		// Check if config is writable
198
-		$configFileWritable = is_writable($configFilePath);
199
-		$configReadOnly = Server::get(IConfig::class)->getSystemValueBool('config_is_read_only');
200
-		if (!$configFileWritable && !$configReadOnly
201
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
202
-			$urlGenerator = Server::get(IURLGenerator::class);
203
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
204
-
205
-			if (self::$CLI) {
206
-				echo $l->t('Cannot write into "config" directory!') . "\n";
207
-				echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n";
208
-				echo "\n";
209
-				echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . "\n";
210
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n";
211
-				exit;
212
-			} else {
213
-				Server::get(ITemplateManager::class)->printErrorPage(
214
-					$l->t('Cannot write into "config" directory!'),
215
-					$l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
216
-					. $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
217
-					. $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
218
-					503
219
-				);
220
-			}
221
-		}
222
-	}
223
-
224
-	public static function checkInstalled(\OC\SystemConfig $systemConfig): void {
225
-		if (defined('OC_CONSOLE')) {
226
-			return;
227
-		}
228
-		// Redirect to installer if not installed
229
-		if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
230
-			if (OC::$CLI) {
231
-				throw new Exception('Not installed');
232
-			} else {
233
-				$url = OC::$WEBROOT . '/index.php';
234
-				header('Location: ' . $url);
235
-			}
236
-			exit();
237
-		}
238
-	}
239
-
240
-	public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void {
241
-		// Allow ajax update script to execute without being stopped
242
-		if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
243
-			// send http status 503
244
-			http_response_code(503);
245
-			header('X-Nextcloud-Maintenance-Mode: 1');
246
-			header('Retry-After: 120');
247
-
248
-			// render error page
249
-			$template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest');
250
-			\OCP\Util::addScript('core', 'maintenance');
251
-			\OCP\Util::addStyle('core', 'guest');
252
-			$template->printPage();
253
-			die();
254
-		}
255
-	}
256
-
257
-	/**
258
-	 * Prints the upgrade page
259
-	 */
260
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
261
-		$cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', '');
262
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
263
-		$tooBig = false;
264
-		if (!$disableWebUpdater) {
265
-			$apps = Server::get(\OCP\App\IAppManager::class);
266
-			if ($apps->isEnabledForAnyone('user_ldap')) {
267
-				$qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
268
-
269
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
270
-					->from('ldap_user_mapping')
271
-					->executeQuery();
272
-				$row = $result->fetch();
273
-				$result->closeCursor();
274
-
275
-				$tooBig = ($row['user_count'] > 50);
276
-			}
277
-			if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) {
278
-				$qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
279
-
280
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
281
-					->from('user_saml_users')
282
-					->executeQuery();
283
-				$row = $result->fetch();
284
-				$result->closeCursor();
285
-
286
-				$tooBig = ($row['user_count'] > 50);
287
-			}
288
-			if (!$tooBig) {
289
-				// count users
290
-				$totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51);
291
-				$tooBig = ($totalUsers > 50);
292
-			}
293
-		}
294
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
295
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
296
-
297
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
298
-			// send http status 503
299
-			http_response_code(503);
300
-			header('Retry-After: 120');
301
-
302
-			$serverVersion = \OCP\Server::get(\OCP\ServerVersion::class);
303
-
304
-			// render error page
305
-			$template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest');
306
-			$template->assign('productName', 'nextcloud'); // for now
307
-			$template->assign('version', $serverVersion->getVersionString());
308
-			$template->assign('tooBig', $tooBig);
309
-			$template->assign('cliUpgradeLink', $cliUpgradeLink);
310
-
311
-			$template->printPage();
312
-			die();
313
-		}
314
-
315
-		// check whether this is a core update or apps update
316
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
317
-		$currentVersion = implode('.', \OCP\Util::getVersion());
318
-
319
-		// if not a core upgrade, then it's apps upgrade
320
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
321
-
322
-		$oldTheme = $systemConfig->getValue('theme');
323
-		$systemConfig->setValue('theme', '');
324
-		\OCP\Util::addScript('core', 'common');
325
-		\OCP\Util::addScript('core', 'main');
326
-		\OCP\Util::addTranslations('core');
327
-		\OCP\Util::addScript('core', 'update');
328
-
329
-		/** @var \OC\App\AppManager $appManager */
330
-		$appManager = Server::get(\OCP\App\IAppManager::class);
331
-
332
-		$tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest');
333
-		$tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString());
334
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
335
-
336
-		// get third party apps
337
-		$ocVersion = \OCP\Util::getVersion();
338
-		$ocVersion = implode('.', $ocVersion);
339
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
340
-		$incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []);
341
-		$incompatibleShippedApps = [];
342
-		$incompatibleDisabledApps = [];
343
-		foreach ($incompatibleApps as $appInfo) {
344
-			if ($appManager->isShipped($appInfo['id'])) {
345
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
346
-			}
347
-			if (!in_array($appInfo['id'], $incompatibleOverwrites)) {
348
-				$incompatibleDisabledApps[] = $appInfo;
349
-			}
350
-		}
351
-
352
-		if (!empty($incompatibleShippedApps)) {
353
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('core');
354
-			$hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]);
355
-			throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint);
356
-		}
357
-
358
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
359
-		$tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps);
360
-		try {
361
-			$defaults = new \OC_Defaults();
362
-			$tmpl->assign('productName', $defaults->getName());
363
-		} catch (Throwable $error) {
364
-			$tmpl->assign('productName', 'Nextcloud');
365
-		}
366
-		$tmpl->assign('oldTheme', $oldTheme);
367
-		$tmpl->printPage();
368
-	}
369
-
370
-	public static function initSession(): void {
371
-		$request = Server::get(IRequest::class);
372
-
373
-		// TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies
374
-		// TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments
375
-		// TODO: for further information.
376
-		// $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0;
377
-		// if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) {
378
-		// setcookie('cookie_test', 'test', time() + 3600);
379
-		// // Do not initialize the session if a request is authenticated directly
380
-		// // unless there is a session cookie already sent along
381
-		// return;
382
-		// }
383
-
384
-		if ($request->getServerProtocol() === 'https') {
385
-			ini_set('session.cookie_secure', 'true');
386
-		}
387
-
388
-		// prevents javascript from accessing php session cookies
389
-		ini_set('session.cookie_httponly', 'true');
390
-
391
-		// Do not initialize sessions for 'status.php' requests
392
-		// Monitoring endpoints can quickly flood session handlers
393
-		// and 'status.php' doesn't require sessions anyway
394
-		if (str_ends_with($request->getScriptName(), '/status.php')) {
395
-			return;
396
-		}
397
-
398
-		// set the cookie path to the Nextcloud directory
399
-		$cookie_path = OC::$WEBROOT ? : '/';
400
-		ini_set('session.cookie_path', $cookie_path);
401
-
402
-		// Let the session name be changed in the initSession Hook
403
-		$sessionName = OC_Util::getInstanceId();
404
-
405
-		try {
406
-			$logger = null;
407
-			if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) {
408
-				$logger = logger('core');
409
-			}
410
-
411
-			// set the session name to the instance id - which is unique
412
-			$session = new \OC\Session\Internal(
413
-				$sessionName,
414
-				$logger,
415
-			);
416
-
417
-			$cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class);
418
-			$session = $cryptoWrapper->wrapSession($session);
419
-			self::$server->setSession($session);
420
-
421
-			// if session can't be started break with http 500 error
422
-		} catch (Exception $e) {
423
-			Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
424
-			//show the user a detailed error page
425
-			Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500);
426
-			die();
427
-		}
428
-
429
-		//try to set the session lifetime
430
-		$sessionLifeTime = self::getSessionLifeTime();
431
-
432
-		// session timeout
433
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
434
-			if (isset($_COOKIE[session_name()])) {
435
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
436
-			}
437
-			Server::get(IUserSession::class)->logout();
438
-		}
439
-
440
-		if (!self::hasSessionRelaxedExpiry()) {
441
-			$session->set('LAST_ACTIVITY', time());
442
-		}
443
-		$session->close();
444
-	}
445
-
446
-	private static function getSessionLifeTime(): int {
447
-		return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24);
448
-	}
449
-
450
-	/**
451
-	 * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
452
-	 */
453
-	public static function hasSessionRelaxedExpiry(): bool {
454
-		return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false);
455
-	}
456
-
457
-	/**
458
-	 * Try to set some values to the required Nextcloud default
459
-	 */
460
-	public static function setRequiredIniValues(): void {
461
-		// Don't display errors and log them
462
-		@ini_set('display_errors', '0');
463
-		@ini_set('log_errors', '1');
464
-
465
-		// Try to configure php to enable big file uploads.
466
-		// This doesn't work always depending on the webserver and php configuration.
467
-		// Let's try to overwrite some defaults if they are smaller than 1 hour
468
-
469
-		if (intval(@ini_get('max_execution_time') ?: 0) < 3600) {
470
-			@ini_set('max_execution_time', strval(3600));
471
-		}
472
-
473
-		if (intval(@ini_get('max_input_time') ?: 0) < 3600) {
474
-			@ini_set('max_input_time', strval(3600));
475
-		}
476
-
477
-		// Try to set the maximum execution time to the largest time limit we have
478
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
479
-			@set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
480
-		}
481
-
482
-		@ini_set('default_charset', 'UTF-8');
483
-		@ini_set('gd.jpeg_ignore_warning', '1');
484
-	}
485
-
486
-	/**
487
-	 * Send the same site cookies
488
-	 */
489
-	private static function sendSameSiteCookies(): void {
490
-		$cookieParams = session_get_cookie_params();
491
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
492
-		$policies = [
493
-			'lax',
494
-			'strict',
495
-		];
496
-
497
-		// Append __Host to the cookie if it meets the requirements
498
-		$cookiePrefix = '';
499
-		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
500
-			$cookiePrefix = '__Host-';
501
-		}
502
-
503
-		foreach ($policies as $policy) {
504
-			header(
505
-				sprintf(
506
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
507
-					$cookiePrefix,
508
-					$policy,
509
-					$cookieParams['path'],
510
-					$policy
511
-				),
512
-				false
513
-			);
514
-		}
515
-	}
516
-
517
-	/**
518
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
519
-	 * be set in every request if cookies are sent to add a second level of
520
-	 * defense against CSRF.
521
-	 *
522
-	 * If the cookie is not sent this will set the cookie and reload the page.
523
-	 * We use an additional cookie since we want to protect logout CSRF and
524
-	 * also we can't directly interfere with PHP's session mechanism.
525
-	 */
526
-	private static function performSameSiteCookieProtection(IConfig $config): void {
527
-		$request = Server::get(IRequest::class);
528
-
529
-		// Some user agents are notorious and don't really properly follow HTTP
530
-		// specifications. For those, have an automated opt-out. Since the protection
531
-		// for remote.php is applied in base.php as starting point we need to opt out
532
-		// here.
533
-		$incompatibleUserAgents = $config->getSystemValue('csrf.optout');
534
-
535
-		// Fallback, if csrf.optout is unset
536
-		if (!is_array($incompatibleUserAgents)) {
537
-			$incompatibleUserAgents = [
538
-				// OS X Finder
539
-				'/^WebDAVFS/',
540
-				// Windows webdav drive
541
-				'/^Microsoft-WebDAV-MiniRedir/',
542
-			];
543
-		}
544
-
545
-		if ($request->isUserAgent($incompatibleUserAgents)) {
546
-			return;
547
-		}
548
-
549
-		if (count($_COOKIE) > 0) {
550
-			$requestUri = $request->getScriptName();
551
-			$processingScript = explode('/', $requestUri);
552
-			$processingScript = $processingScript[count($processingScript) - 1];
553
-
554
-			if ($processingScript === 'index.php' // index.php routes are handled in the middleware
555
-				|| $processingScript === 'cron.php' // and cron.php does not need any authentication at all
556
-				|| $processingScript === 'public.php' // For public.php, auth for password protected shares is done in the PublicAuth plugin
557
-			) {
558
-				return;
559
-			}
560
-
561
-			// All other endpoints require the lax and the strict cookie
562
-			if (!$request->passesStrictCookieCheck()) {
563
-				logger('core')->warning('Request does not pass strict cookie check');
564
-				self::sendSameSiteCookies();
565
-				// Debug mode gets access to the resources without strict cookie
566
-				// due to the fact that the SabreDAV browser also lives there.
567
-				if (!$config->getSystemValueBool('debug', false)) {
568
-					http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED);
569
-					header('Content-Type: application/json');
570
-					echo json_encode(['error' => 'Strict Cookie has not been found in request']);
571
-					exit();
572
-				}
573
-			}
574
-		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
575
-			self::sendSameSiteCookies();
576
-		}
577
-	}
578
-
579
-	public static function init(): void {
580
-		// First handle PHP configuration and copy auth headers to the expected
581
-		// $_SERVER variable before doing anything Server object related
582
-		self::setRequiredIniValues();
583
-		self::handleAuthHeaders();
584
-
585
-		// prevent any XML processing from loading external entities
586
-		libxml_set_external_entity_loader(static function () {
587
-			return null;
588
-		});
589
-
590
-		// Set default timezone before the Server object is booted
591
-		if (!date_default_timezone_set('UTC')) {
592
-			throw new \RuntimeException('Could not set timezone to UTC');
593
-		}
594
-
595
-		// calculate the root directories
596
-		OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4));
597
-
598
-		// register autoloader
599
-		$loaderStart = microtime(true);
600
-		require_once __DIR__ . '/autoloader.php';
601
-		self::$loader = new \OC\Autoloader([
602
-			OC::$SERVERROOT . '/lib/private/legacy',
603
-		]);
604
-		spl_autoload_register([self::$loader, 'load']);
605
-		$loaderEnd = microtime(true);
606
-
607
-		self::$CLI = (php_sapi_name() == 'cli');
608
-
609
-		// Add default composer PSR-4 autoloader, ensure apcu to be disabled
610
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
611
-		self::$composerAutoloader->setApcuPrefix(null);
612
-
613
-
614
-		try {
615
-			self::initPaths();
616
-			// setup 3rdparty autoloader
617
-			$vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php';
618
-			if (!file_exists($vendorAutoLoad)) {
619
-				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
620
-			}
621
-			require_once $vendorAutoLoad;
622
-		} catch (\RuntimeException $e) {
623
-			if (!self::$CLI) {
624
-				http_response_code(503);
625
-			}
626
-			// we can't use the template error page here, because this needs the
627
-			// DI container which isn't available yet
628
-			print($e->getMessage());
629
-			exit();
630
-		}
631
-
632
-		// setup the basic server
633
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
634
-		self::$server->boot();
635
-
636
-		try {
637
-			$profiler = new BuiltInProfiler(
638
-				Server::get(IConfig::class),
639
-				Server::get(IRequest::class),
640
-			);
641
-			$profiler->start();
642
-		} catch (\Throwable $e) {
643
-			logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']);
644
-		}
645
-
646
-		if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) {
647
-			\OC\Core\Listener\BeforeMessageLoggedEventListener::setup();
648
-		}
649
-
650
-		$eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
651
-		$eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
652
-		$eventLogger->start('boot', 'Initialize');
653
-
654
-		// Override php.ini and log everything if we're troubleshooting
655
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
656
-			error_reporting(E_ALL);
657
-		}
658
-
659
-		$systemConfig = Server::get(\OC\SystemConfig::class);
660
-		self::registerAutoloaderCache($systemConfig);
661
-
662
-		// initialize intl fallback if necessary
663
-		OC_Util::isSetLocaleWorking();
664
-
665
-		$config = Server::get(IConfig::class);
666
-		if (!defined('PHPUNIT_RUN')) {
667
-			$errorHandler = new OC\Log\ErrorHandler(
668
-				\OCP\Server::get(\Psr\Log\LoggerInterface::class),
669
-			);
670
-			$exceptionHandler = [$errorHandler, 'onException'];
671
-			if ($config->getSystemValueBool('debug', false)) {
672
-				set_error_handler([$errorHandler, 'onAll'], E_ALL);
673
-				if (\OC::$CLI) {
674
-					$exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage'];
675
-				}
676
-			} else {
677
-				set_error_handler([$errorHandler, 'onError']);
678
-			}
679
-			register_shutdown_function([$errorHandler, 'onShutdown']);
680
-			set_exception_handler($exceptionHandler);
681
-		}
682
-
683
-		/** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
684
-		$bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
685
-		$bootstrapCoordinator->runInitialRegistration();
686
-
687
-		$eventLogger->start('init_session', 'Initialize session');
688
-
689
-		// Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users
690
-		// see https://github.com/nextcloud/server/pull/2619
691
-		if (!function_exists('simplexml_load_file')) {
692
-			throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.');
693
-		}
694
-
695
-		$appManager = Server::get(\OCP\App\IAppManager::class);
696
-		if ($systemConfig->getValue('installed', false)) {
697
-			$appManager->loadApps(['session']);
698
-		}
699
-		if (!self::$CLI) {
700
-			self::initSession();
701
-		}
702
-		$eventLogger->end('init_session');
703
-		self::checkConfig();
704
-		self::checkInstalled($systemConfig);
705
-
706
-		OC_Response::addSecurityHeaders();
707
-
708
-		self::performSameSiteCookieProtection($config);
709
-
710
-		if (!defined('OC_CONSOLE')) {
711
-			$eventLogger->start('check_server', 'Run a few configuration checks');
712
-			$errors = OC_Util::checkServer($systemConfig);
713
-			if (count($errors) > 0) {
714
-				if (!self::$CLI) {
715
-					http_response_code(503);
716
-					Util::addStyle('guest');
717
-					try {
718
-						Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]);
719
-						exit;
720
-					} catch (\Exception $e) {
721
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
722
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
723
-					}
724
-				}
725
-
726
-				// Convert l10n string into regular string for usage in database
727
-				$staticErrors = [];
728
-				foreach ($errors as $error) {
729
-					echo $error['error'] . "\n";
730
-					echo $error['hint'] . "\n\n";
731
-					$staticErrors[] = [
732
-						'error' => (string)$error['error'],
733
-						'hint' => (string)$error['hint'],
734
-					];
735
-				}
736
-
737
-				try {
738
-					$config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
739
-				} catch (\Exception $e) {
740
-					echo('Writing to database failed');
741
-				}
742
-				exit(1);
743
-			} elseif (self::$CLI && $config->getSystemValueBool('installed', false)) {
744
-				$config->deleteAppValue('core', 'cronErrors');
745
-			}
746
-			$eventLogger->end('check_server');
747
-		}
748
-
749
-		// User and Groups
750
-		if (!$systemConfig->getValue('installed', false)) {
751
-			self::$server->getSession()->set('user_id', '');
752
-		}
753
-
754
-		$eventLogger->start('setup_backends', 'Setup group and user backends');
755
-		Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database());
756
-		Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
757
-
758
-		// Subscribe to the hook
759
-		\OCP\Util::connectHook(
760
-			'\OCA\Files_Sharing\API\Server2Server',
761
-			'preLoginNameUsedAsUserName',
762
-			'\OC\User\Database',
763
-			'preLoginNameUsedAsUserName'
764
-		);
765
-
766
-		//setup extra user backends
767
-		if (!\OCP\Util::needUpgrade()) {
768
-			OC_User::setupBackends();
769
-		} else {
770
-			// Run upgrades in incognito mode
771
-			OC_User::setIncognitoMode(true);
772
-		}
773
-		$eventLogger->end('setup_backends');
774
-
775
-		self::registerCleanupHooks($systemConfig);
776
-		self::registerShareHooks($systemConfig);
777
-		self::registerEncryptionWrapperAndHooks();
778
-		self::registerAccountHooks();
779
-		self::registerResourceCollectionHooks();
780
-		self::registerFileReferenceEventListener();
781
-		self::registerRenderReferenceEventListener();
782
-		self::registerAppRestrictionsHooks();
783
-
784
-		// Make sure that the application class is not loaded before the database is setup
785
-		if ($systemConfig->getValue('installed', false)) {
786
-			$appManager->loadApp('settings');
787
-			/* Build core application to make sure that listeners are registered */
788
-			Server::get(\OC\Core\Application::class);
789
-		}
790
-
791
-		//make sure temporary files are cleaned up
792
-		$tmpManager = Server::get(\OCP\ITempManager::class);
793
-		register_shutdown_function([$tmpManager, 'clean']);
794
-		$lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
795
-		register_shutdown_function([$lockProvider, 'releaseAll']);
796
-
797
-		// Check whether the sample configuration has been copied
798
-		if ($systemConfig->getValue('copied_sample_config', false)) {
799
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
800
-			Server::get(ITemplateManager::class)->printErrorPage(
801
-				$l->t('Sample configuration detected'),
802
-				$l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
803
-				503
804
-			);
805
-			return;
806
-		}
807
-
808
-		$request = Server::get(IRequest::class);
809
-		$host = $request->getInsecureServerHost();
810
-		/**
811
-		 * if the host passed in headers isn't trusted
812
-		 * FIXME: Should not be in here at all :see_no_evil:
813
-		 */
814
-		if (!OC::$CLI
815
-			&& !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
816
-			&& $config->getSystemValueBool('installed', false)
817
-		) {
818
-			// Allow access to CSS resources
819
-			$isScssRequest = false;
820
-			if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
821
-				$isScssRequest = true;
822
-			}
823
-
824
-			if (substr($request->getRequestUri(), -11) === '/status.php') {
825
-				http_response_code(400);
826
-				header('Content-Type: application/json');
827
-				echo '{"error": "Trusted domain error.", "code": 15}';
828
-				exit();
829
-			}
830
-
831
-			if (!$isScssRequest) {
832
-				http_response_code(400);
833
-				Server::get(LoggerInterface::class)->info(
834
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
835
-					[
836
-						'app' => 'core',
837
-						'remoteAddress' => $request->getRemoteAddress(),
838
-						'host' => $host,
839
-					]
840
-				);
841
-
842
-				$tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest');
843
-				$tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
844
-				$tmpl->printPage();
845
-
846
-				exit();
847
-			}
848
-		}
849
-		$eventLogger->end('boot');
850
-		$eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
851
-		$eventLogger->start('runtime', 'Runtime');
852
-		$eventLogger->start('request', 'Full request after boot');
853
-		register_shutdown_function(function () use ($eventLogger) {
854
-			$eventLogger->end('request');
855
-		});
856
-
857
-		register_shutdown_function(function () {
858
-			$memoryPeak = memory_get_peak_usage();
859
-			$logLevel = match (true) {
860
-				$memoryPeak > 500_000_000 => ILogger::FATAL,
861
-				$memoryPeak > 400_000_000 => ILogger::ERROR,
862
-				$memoryPeak > 300_000_000 => ILogger::WARN,
863
-				default => null,
864
-			};
865
-			if ($logLevel !== null) {
866
-				$message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak);
867
-				$logger = Server::get(LoggerInterface::class);
868
-				$logger->log($logLevel, $message, ['app' => 'core']);
869
-			}
870
-		});
871
-	}
872
-
873
-	/**
874
-	 * register hooks for the cleanup of cache and bruteforce protection
875
-	 */
876
-	public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
877
-		//don't try to do this before we are properly setup
878
-		if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
879
-			// NOTE: This will be replaced to use OCP
880
-			$userSession = Server::get(\OC\User\Session::class);
881
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
882
-				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
883
-					// reset brute force delay for this IP address and username
884
-					$uid = $userSession->getUser()->getUID();
885
-					$request = Server::get(IRequest::class);
886
-					$throttler = Server::get(IThrottler::class);
887
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
888
-				}
889
-
890
-				try {
891
-					$cache = new \OC\Cache\File();
892
-					$cache->gc();
893
-				} catch (\OC\ServerNotAvailableException $e) {
894
-					// not a GC exception, pass it on
895
-					throw $e;
896
-				} catch (\OC\ForbiddenException $e) {
897
-					// filesystem blocked for this request, ignore
898
-				} catch (\Exception $e) {
899
-					// a GC exception should not prevent users from using OC,
900
-					// so log the exception
901
-					Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
902
-						'app' => 'core',
903
-						'exception' => $e,
904
-					]);
905
-				}
906
-			});
907
-		}
908
-	}
909
-
910
-	private static function registerEncryptionWrapperAndHooks(): void {
911
-		/** @var \OC\Encryption\Manager */
912
-		$manager = Server::get(\OCP\Encryption\IManager::class);
913
-		Server::get(IEventDispatcher::class)->addListener(
914
-			BeforeFileSystemSetupEvent::class,
915
-			$manager->setupStorage(...),
916
-		);
917
-
918
-		$enabled = $manager->isEnabled();
919
-		if ($enabled) {
920
-			\OC\Encryption\EncryptionEventListener::register(Server::get(IEventDispatcher::class));
921
-		}
922
-	}
923
-
924
-	private static function registerAccountHooks(): void {
925
-		/** @var IEventDispatcher $dispatcher */
926
-		$dispatcher = Server::get(IEventDispatcher::class);
927
-		$dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
928
-	}
929
-
930
-	private static function registerAppRestrictionsHooks(): void {
931
-		/** @var \OC\Group\Manager $groupManager */
932
-		$groupManager = Server::get(\OCP\IGroupManager::class);
933
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
934
-			$appManager = Server::get(\OCP\App\IAppManager::class);
935
-			$apps = $appManager->getEnabledAppsForGroup($group);
936
-			foreach ($apps as $appId) {
937
-				$restrictions = $appManager->getAppRestriction($appId);
938
-				if (empty($restrictions)) {
939
-					continue;
940
-				}
941
-				$key = array_search($group->getGID(), $restrictions);
942
-				unset($restrictions[$key]);
943
-				$restrictions = array_values($restrictions);
944
-				if (empty($restrictions)) {
945
-					$appManager->disableApp($appId);
946
-				} else {
947
-					$appManager->enableAppForGroups($appId, $restrictions);
948
-				}
949
-			}
950
-		});
951
-	}
952
-
953
-	private static function registerResourceCollectionHooks(): void {
954
-		\OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class));
955
-	}
956
-
957
-	private static function registerFileReferenceEventListener(): void {
958
-		\OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
959
-	}
960
-
961
-	private static function registerRenderReferenceEventListener() {
962
-		\OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
963
-	}
964
-
965
-	/**
966
-	 * register hooks for sharing
967
-	 */
968
-	public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
969
-		if ($systemConfig->getValue('installed')) {
970
-
971
-			$dispatcher = Server::get(IEventDispatcher::class);
972
-			$dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class);
973
-			$dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class);
974
-			$dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class);
975
-		}
976
-	}
977
-
978
-	protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
979
-		// The class loader takes an optional low-latency cache, which MUST be
980
-		// namespaced. The instanceid is used for namespacing, but might be
981
-		// unavailable at this point. Furthermore, it might not be possible to
982
-		// generate an instanceid via \OC_Util::getInstanceId() because the
983
-		// config file may not be writable. As such, we only register a class
984
-		// loader cache if instanceid is available without trying to create one.
985
-		$instanceId = $systemConfig->getValue('instanceid', null);
986
-		if ($instanceId) {
987
-			try {
988
-				$memcacheFactory = Server::get(\OCP\ICacheFactory::class);
989
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
990
-			} catch (\Exception $ex) {
991
-			}
992
-		}
993
-	}
994
-
995
-	/**
996
-	 * Handle the request
997
-	 */
998
-	public static function handleRequest(): void {
999
-		Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
1000
-		$systemConfig = Server::get(\OC\SystemConfig::class);
1001
-
1002
-		// Check if Nextcloud is installed or in maintenance (update) mode
1003
-		if (!$systemConfig->getValue('installed', false)) {
1004
-			\OC::$server->getSession()->clear();
1005
-			$controller = Server::get(\OC\Core\Controller\SetupController::class);
1006
-			$controller->run($_POST);
1007
-			exit();
1008
-		}
1009
-
1010
-		$request = Server::get(IRequest::class);
1011
-		$requestPath = $request->getRawPathInfo();
1012
-		if ($requestPath === '/heartbeat') {
1013
-			return;
1014
-		}
1015
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
1016
-			self::checkMaintenanceMode($systemConfig);
1017
-
1018
-			if (\OCP\Util::needUpgrade()) {
1019
-				if (function_exists('opcache_reset')) {
1020
-					opcache_reset();
1021
-				}
1022
-				if (!((bool)$systemConfig->getValue('maintenance', false))) {
1023
-					self::printUpgradePage($systemConfig);
1024
-					exit();
1025
-				}
1026
-			}
1027
-		}
1028
-
1029
-		$appManager = Server::get(\OCP\App\IAppManager::class);
1030
-
1031
-		// Always load authentication apps
1032
-		$appManager->loadApps(['authentication']);
1033
-		$appManager->loadApps(['extended_authentication']);
1034
-
1035
-		// Load minimum set of apps
1036
-		if (!\OCP\Util::needUpgrade()
1037
-			&& !((bool)$systemConfig->getValue('maintenance', false))) {
1038
-			// For logged-in users: Load everything
1039
-			if (Server::get(IUserSession::class)->isLoggedIn()) {
1040
-				$appManager->loadApps();
1041
-			} else {
1042
-				// For guests: Load only filesystem and logging
1043
-				$appManager->loadApps(['filesystem', 'logging']);
1044
-
1045
-				// Don't try to login when a client is trying to get a OAuth token.
1046
-				// OAuth needs to support basic auth too, so the login is not valid
1047
-				// inside Nextcloud and the Login exception would ruin it.
1048
-				if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1049
-					self::handleLogin($request);
1050
-				}
1051
-			}
1052
-		}
1053
-
1054
-		if (!self::$CLI) {
1055
-			try {
1056
-				if (!\OCP\Util::needUpgrade()) {
1057
-					$appManager->loadApps(['filesystem', 'logging']);
1058
-					$appManager->loadApps();
1059
-				}
1060
-				Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1061
-				return;
1062
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1063
-				//header('HTTP/1.0 404 Not Found');
1064
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1065
-				http_response_code(405);
1066
-				return;
1067
-			}
1068
-		}
1069
-
1070
-		// Handle WebDAV
1071
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1072
-			// not allowed any more to prevent people
1073
-			// mounting this root directly.
1074
-			// Users need to mount remote.php/webdav instead.
1075
-			http_response_code(405);
1076
-			return;
1077
-		}
1078
-
1079
-		// Handle requests for JSON or XML
1080
-		$acceptHeader = $request->getHeader('Accept');
1081
-		if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1082
-			http_response_code(404);
1083
-			return;
1084
-		}
1085
-
1086
-		// Handle resources that can't be found
1087
-		// This prevents browsers from redirecting to the default page and then
1088
-		// attempting to parse HTML as CSS and similar.
1089
-		$destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1090
-		if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1091
-			http_response_code(404);
1092
-			return;
1093
-		}
1094
-
1095
-		// Redirect to the default app or login only as an entry point
1096
-		if ($requestPath === '') {
1097
-			// Someone is logged in
1098
-			if (Server::get(IUserSession::class)->isLoggedIn()) {
1099
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1100
-			} else {
1101
-				// Not handled and not logged in
1102
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1103
-			}
1104
-			return;
1105
-		}
1106
-
1107
-		try {
1108
-			Server::get(\OC\Route\Router::class)->match('/error/404');
1109
-		} catch (\Exception $e) {
1110
-			if (!$e instanceof MethodNotAllowedException) {
1111
-				logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1112
-			}
1113
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
1114
-			Server::get(ITemplateManager::class)->printErrorPage(
1115
-				'404',
1116
-				$l->t('The page could not be found on the server.'),
1117
-				404
1118
-			);
1119
-		}
1120
-	}
1121
-
1122
-	/**
1123
-	 * Check login: apache auth, auth token, basic auth
1124
-	 */
1125
-	public static function handleLogin(OCP\IRequest $request): bool {
1126
-		if ($request->getHeader('X-Nextcloud-Federation')) {
1127
-			return false;
1128
-		}
1129
-		$userSession = Server::get(\OC\User\Session::class);
1130
-		if (OC_User::handleApacheAuth()) {
1131
-			return true;
1132
-		}
1133
-		if (self::tryAppAPILogin($request)) {
1134
-			return true;
1135
-		}
1136
-		if ($userSession->tryTokenLogin($request)) {
1137
-			return true;
1138
-		}
1139
-		if (isset($_COOKIE['nc_username'])
1140
-			&& isset($_COOKIE['nc_token'])
1141
-			&& isset($_COOKIE['nc_session_id'])
1142
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1143
-			return true;
1144
-		}
1145
-		if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) {
1146
-			return true;
1147
-		}
1148
-		return false;
1149
-	}
1150
-
1151
-	protected static function handleAuthHeaders(): void {
1152
-		//copy http auth headers for apache+php-fcgid work around
1153
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1154
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1155
-		}
1156
-
1157
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1158
-		$vars = [
1159
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1160
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1161
-		];
1162
-		foreach ($vars as $var) {
1163
-			if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1164
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1165
-				if (count($credentials) === 2) {
1166
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1167
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1168
-					break;
1169
-				}
1170
-			}
1171
-		}
1172
-	}
1173
-
1174
-	protected static function tryAppAPILogin(OCP\IRequest $request): bool {
1175
-		if (!$request->getHeader('AUTHORIZATION-APP-API')) {
1176
-			return false;
1177
-		}
1178
-		$appManager = Server::get(OCP\App\IAppManager::class);
1179
-		if (!$appManager->isEnabledForAnyone('app_api')) {
1180
-			return false;
1181
-		}
1182
-		try {
1183
-			$appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class);
1184
-			return $appAPIService->validateExAppRequestToNC($request);
1185
-		} catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) {
1186
-			return false;
1187
-		}
1188
-	}
42
+    /**
43
+     * Associative array for autoloading. classname => filename
44
+     */
45
+    public static array $CLASSPATH = [];
46
+    /**
47
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
48
+     */
49
+    public static string $SERVERROOT = '';
50
+    /**
51
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
52
+     */
53
+    private static string $SUBURI = '';
54
+    /**
55
+     * the Nextcloud root path for http requests (e.g. /nextcloud)
56
+     */
57
+    public static string $WEBROOT = '';
58
+    /**
59
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
60
+     * web path in 'url'
61
+     */
62
+    public static array $APPSROOTS = [];
63
+
64
+    public static string $configDir;
65
+
66
+    /**
67
+     * requested app
68
+     */
69
+    public static string $REQUESTEDAPP = '';
70
+
71
+    /**
72
+     * check if Nextcloud runs in cli mode
73
+     */
74
+    public static bool $CLI = false;
75
+
76
+    public static \OC\Autoloader $loader;
77
+
78
+    public static \Composer\Autoload\ClassLoader $composerAutoloader;
79
+
80
+    public static \OC\Server $server;
81
+
82
+    private static \OC\Config $config;
83
+
84
+    /**
85
+     * @throws \RuntimeException when the 3rdparty directory is missing or
86
+     *                           the app path list is empty or contains an invalid path
87
+     */
88
+    public static function initPaths(): void {
89
+        if (defined('PHPUNIT_CONFIG_DIR')) {
90
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
91
+        } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
92
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
93
+        } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
94
+            self::$configDir = rtrim($dir, '/') . '/';
95
+        } else {
96
+            self::$configDir = OC::$SERVERROOT . '/config/';
97
+        }
98
+        self::$config = new \OC\Config(self::$configDir);
99
+
100
+        OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT)));
101
+        /**
102
+         * FIXME: The following lines are required because we can't yet instantiate
103
+         *        Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist.
104
+         */
105
+        $params = [
106
+            'server' => [
107
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null,
108
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null,
109
+            ],
110
+        ];
111
+        if (isset($_SERVER['REMOTE_ADDR'])) {
112
+            $params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
113
+        }
114
+        $fakeRequest = new \OC\AppFramework\Http\Request(
115
+            $params,
116
+            new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
117
+            new \OC\AllConfig(new \OC\SystemConfig(self::$config))
118
+        );
119
+        $scriptName = $fakeRequest->getScriptName();
120
+        if (substr($scriptName, -1) == '/') {
121
+            $scriptName .= 'index.php';
122
+            //make sure suburi follows the same rules as scriptName
123
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
124
+                if (substr(OC::$SUBURI, -1) != '/') {
125
+                    OC::$SUBURI = OC::$SUBURI . '/';
126
+                }
127
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
128
+            }
129
+        }
130
+
131
+        if (OC::$CLI) {
132
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
133
+        } else {
134
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
135
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
136
+
137
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
138
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
139
+                }
140
+            } else {
141
+                // The scriptName is not ending with OC::$SUBURI
142
+                // This most likely means that we are calling from CLI.
143
+                // However some cron jobs still need to generate
144
+                // a web URL, so we use overwritewebroot as a fallback.
145
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
146
+            }
147
+
148
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
149
+            // slash which is required by URL generation.
150
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
151
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
152
+                header('Location: ' . \OC::$WEBROOT . '/');
153
+                exit();
154
+            }
155
+        }
156
+
157
+        // search the apps folder
158
+        $config_paths = self::$config->getValue('apps_paths', []);
159
+        if (!empty($config_paths)) {
160
+            foreach ($config_paths as $paths) {
161
+                if (isset($paths['url']) && isset($paths['path'])) {
162
+                    $paths['url'] = rtrim($paths['url'], '/');
163
+                    $paths['path'] = rtrim($paths['path'], '/');
164
+                    OC::$APPSROOTS[] = $paths;
165
+                }
166
+            }
167
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
168
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
169
+        }
170
+
171
+        if (empty(OC::$APPSROOTS)) {
172
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
173
+                . '. You can also configure the location in the config.php file.');
174
+        }
175
+        $paths = [];
176
+        foreach (OC::$APPSROOTS as $path) {
177
+            $paths[] = $path['path'];
178
+            if (!is_dir($path['path'])) {
179
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
180
+                    . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
181
+            }
182
+        }
183
+
184
+        // set the right include path
185
+        set_include_path(
186
+            implode(PATH_SEPARATOR, $paths)
187
+        );
188
+    }
189
+
190
+    public static function checkConfig(): void {
191
+        // Create config if it does not already exist
192
+        $configFilePath = self::$configDir . '/config.php';
193
+        if (!file_exists($configFilePath)) {
194
+            @touch($configFilePath);
195
+        }
196
+
197
+        // Check if config is writable
198
+        $configFileWritable = is_writable($configFilePath);
199
+        $configReadOnly = Server::get(IConfig::class)->getSystemValueBool('config_is_read_only');
200
+        if (!$configFileWritable && !$configReadOnly
201
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
202
+            $urlGenerator = Server::get(IURLGenerator::class);
203
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
204
+
205
+            if (self::$CLI) {
206
+                echo $l->t('Cannot write into "config" directory!') . "\n";
207
+                echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n";
208
+                echo "\n";
209
+                echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . "\n";
210
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n";
211
+                exit;
212
+            } else {
213
+                Server::get(ITemplateManager::class)->printErrorPage(
214
+                    $l->t('Cannot write into "config" directory!'),
215
+                    $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
216
+                    . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
217
+                    . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
218
+                    503
219
+                );
220
+            }
221
+        }
222
+    }
223
+
224
+    public static function checkInstalled(\OC\SystemConfig $systemConfig): void {
225
+        if (defined('OC_CONSOLE')) {
226
+            return;
227
+        }
228
+        // Redirect to installer if not installed
229
+        if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
230
+            if (OC::$CLI) {
231
+                throw new Exception('Not installed');
232
+            } else {
233
+                $url = OC::$WEBROOT . '/index.php';
234
+                header('Location: ' . $url);
235
+            }
236
+            exit();
237
+        }
238
+    }
239
+
240
+    public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void {
241
+        // Allow ajax update script to execute without being stopped
242
+        if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
243
+            // send http status 503
244
+            http_response_code(503);
245
+            header('X-Nextcloud-Maintenance-Mode: 1');
246
+            header('Retry-After: 120');
247
+
248
+            // render error page
249
+            $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest');
250
+            \OCP\Util::addScript('core', 'maintenance');
251
+            \OCP\Util::addStyle('core', 'guest');
252
+            $template->printPage();
253
+            die();
254
+        }
255
+    }
256
+
257
+    /**
258
+     * Prints the upgrade page
259
+     */
260
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
261
+        $cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', '');
262
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
263
+        $tooBig = false;
264
+        if (!$disableWebUpdater) {
265
+            $apps = Server::get(\OCP\App\IAppManager::class);
266
+            if ($apps->isEnabledForAnyone('user_ldap')) {
267
+                $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
268
+
269
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
270
+                    ->from('ldap_user_mapping')
271
+                    ->executeQuery();
272
+                $row = $result->fetch();
273
+                $result->closeCursor();
274
+
275
+                $tooBig = ($row['user_count'] > 50);
276
+            }
277
+            if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) {
278
+                $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
279
+
280
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
281
+                    ->from('user_saml_users')
282
+                    ->executeQuery();
283
+                $row = $result->fetch();
284
+                $result->closeCursor();
285
+
286
+                $tooBig = ($row['user_count'] > 50);
287
+            }
288
+            if (!$tooBig) {
289
+                // count users
290
+                $totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51);
291
+                $tooBig = ($totalUsers > 50);
292
+            }
293
+        }
294
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
295
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
296
+
297
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
298
+            // send http status 503
299
+            http_response_code(503);
300
+            header('Retry-After: 120');
301
+
302
+            $serverVersion = \OCP\Server::get(\OCP\ServerVersion::class);
303
+
304
+            // render error page
305
+            $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest');
306
+            $template->assign('productName', 'nextcloud'); // for now
307
+            $template->assign('version', $serverVersion->getVersionString());
308
+            $template->assign('tooBig', $tooBig);
309
+            $template->assign('cliUpgradeLink', $cliUpgradeLink);
310
+
311
+            $template->printPage();
312
+            die();
313
+        }
314
+
315
+        // check whether this is a core update or apps update
316
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
317
+        $currentVersion = implode('.', \OCP\Util::getVersion());
318
+
319
+        // if not a core upgrade, then it's apps upgrade
320
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
321
+
322
+        $oldTheme = $systemConfig->getValue('theme');
323
+        $systemConfig->setValue('theme', '');
324
+        \OCP\Util::addScript('core', 'common');
325
+        \OCP\Util::addScript('core', 'main');
326
+        \OCP\Util::addTranslations('core');
327
+        \OCP\Util::addScript('core', 'update');
328
+
329
+        /** @var \OC\App\AppManager $appManager */
330
+        $appManager = Server::get(\OCP\App\IAppManager::class);
331
+
332
+        $tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest');
333
+        $tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString());
334
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
335
+
336
+        // get third party apps
337
+        $ocVersion = \OCP\Util::getVersion();
338
+        $ocVersion = implode('.', $ocVersion);
339
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
340
+        $incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []);
341
+        $incompatibleShippedApps = [];
342
+        $incompatibleDisabledApps = [];
343
+        foreach ($incompatibleApps as $appInfo) {
344
+            if ($appManager->isShipped($appInfo['id'])) {
345
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
346
+            }
347
+            if (!in_array($appInfo['id'], $incompatibleOverwrites)) {
348
+                $incompatibleDisabledApps[] = $appInfo;
349
+            }
350
+        }
351
+
352
+        if (!empty($incompatibleShippedApps)) {
353
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('core');
354
+            $hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]);
355
+            throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint);
356
+        }
357
+
358
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
359
+        $tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps);
360
+        try {
361
+            $defaults = new \OC_Defaults();
362
+            $tmpl->assign('productName', $defaults->getName());
363
+        } catch (Throwable $error) {
364
+            $tmpl->assign('productName', 'Nextcloud');
365
+        }
366
+        $tmpl->assign('oldTheme', $oldTheme);
367
+        $tmpl->printPage();
368
+    }
369
+
370
+    public static function initSession(): void {
371
+        $request = Server::get(IRequest::class);
372
+
373
+        // TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies
374
+        // TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments
375
+        // TODO: for further information.
376
+        // $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0;
377
+        // if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) {
378
+        // setcookie('cookie_test', 'test', time() + 3600);
379
+        // // Do not initialize the session if a request is authenticated directly
380
+        // // unless there is a session cookie already sent along
381
+        // return;
382
+        // }
383
+
384
+        if ($request->getServerProtocol() === 'https') {
385
+            ini_set('session.cookie_secure', 'true');
386
+        }
387
+
388
+        // prevents javascript from accessing php session cookies
389
+        ini_set('session.cookie_httponly', 'true');
390
+
391
+        // Do not initialize sessions for 'status.php' requests
392
+        // Monitoring endpoints can quickly flood session handlers
393
+        // and 'status.php' doesn't require sessions anyway
394
+        if (str_ends_with($request->getScriptName(), '/status.php')) {
395
+            return;
396
+        }
397
+
398
+        // set the cookie path to the Nextcloud directory
399
+        $cookie_path = OC::$WEBROOT ? : '/';
400
+        ini_set('session.cookie_path', $cookie_path);
401
+
402
+        // Let the session name be changed in the initSession Hook
403
+        $sessionName = OC_Util::getInstanceId();
404
+
405
+        try {
406
+            $logger = null;
407
+            if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) {
408
+                $logger = logger('core');
409
+            }
410
+
411
+            // set the session name to the instance id - which is unique
412
+            $session = new \OC\Session\Internal(
413
+                $sessionName,
414
+                $logger,
415
+            );
416
+
417
+            $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class);
418
+            $session = $cryptoWrapper->wrapSession($session);
419
+            self::$server->setSession($session);
420
+
421
+            // if session can't be started break with http 500 error
422
+        } catch (Exception $e) {
423
+            Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
424
+            //show the user a detailed error page
425
+            Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500);
426
+            die();
427
+        }
428
+
429
+        //try to set the session lifetime
430
+        $sessionLifeTime = self::getSessionLifeTime();
431
+
432
+        // session timeout
433
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
434
+            if (isset($_COOKIE[session_name()])) {
435
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
436
+            }
437
+            Server::get(IUserSession::class)->logout();
438
+        }
439
+
440
+        if (!self::hasSessionRelaxedExpiry()) {
441
+            $session->set('LAST_ACTIVITY', time());
442
+        }
443
+        $session->close();
444
+    }
445
+
446
+    private static function getSessionLifeTime(): int {
447
+        return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24);
448
+    }
449
+
450
+    /**
451
+     * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
452
+     */
453
+    public static function hasSessionRelaxedExpiry(): bool {
454
+        return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false);
455
+    }
456
+
457
+    /**
458
+     * Try to set some values to the required Nextcloud default
459
+     */
460
+    public static function setRequiredIniValues(): void {
461
+        // Don't display errors and log them
462
+        @ini_set('display_errors', '0');
463
+        @ini_set('log_errors', '1');
464
+
465
+        // Try to configure php to enable big file uploads.
466
+        // This doesn't work always depending on the webserver and php configuration.
467
+        // Let's try to overwrite some defaults if they are smaller than 1 hour
468
+
469
+        if (intval(@ini_get('max_execution_time') ?: 0) < 3600) {
470
+            @ini_set('max_execution_time', strval(3600));
471
+        }
472
+
473
+        if (intval(@ini_get('max_input_time') ?: 0) < 3600) {
474
+            @ini_set('max_input_time', strval(3600));
475
+        }
476
+
477
+        // Try to set the maximum execution time to the largest time limit we have
478
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
479
+            @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
480
+        }
481
+
482
+        @ini_set('default_charset', 'UTF-8');
483
+        @ini_set('gd.jpeg_ignore_warning', '1');
484
+    }
485
+
486
+    /**
487
+     * Send the same site cookies
488
+     */
489
+    private static function sendSameSiteCookies(): void {
490
+        $cookieParams = session_get_cookie_params();
491
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
492
+        $policies = [
493
+            'lax',
494
+            'strict',
495
+        ];
496
+
497
+        // Append __Host to the cookie if it meets the requirements
498
+        $cookiePrefix = '';
499
+        if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
500
+            $cookiePrefix = '__Host-';
501
+        }
502
+
503
+        foreach ($policies as $policy) {
504
+            header(
505
+                sprintf(
506
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
507
+                    $cookiePrefix,
508
+                    $policy,
509
+                    $cookieParams['path'],
510
+                    $policy
511
+                ),
512
+                false
513
+            );
514
+        }
515
+    }
516
+
517
+    /**
518
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
519
+     * be set in every request if cookies are sent to add a second level of
520
+     * defense against CSRF.
521
+     *
522
+     * If the cookie is not sent this will set the cookie and reload the page.
523
+     * We use an additional cookie since we want to protect logout CSRF and
524
+     * also we can't directly interfere with PHP's session mechanism.
525
+     */
526
+    private static function performSameSiteCookieProtection(IConfig $config): void {
527
+        $request = Server::get(IRequest::class);
528
+
529
+        // Some user agents are notorious and don't really properly follow HTTP
530
+        // specifications. For those, have an automated opt-out. Since the protection
531
+        // for remote.php is applied in base.php as starting point we need to opt out
532
+        // here.
533
+        $incompatibleUserAgents = $config->getSystemValue('csrf.optout');
534
+
535
+        // Fallback, if csrf.optout is unset
536
+        if (!is_array($incompatibleUserAgents)) {
537
+            $incompatibleUserAgents = [
538
+                // OS X Finder
539
+                '/^WebDAVFS/',
540
+                // Windows webdav drive
541
+                '/^Microsoft-WebDAV-MiniRedir/',
542
+            ];
543
+        }
544
+
545
+        if ($request->isUserAgent($incompatibleUserAgents)) {
546
+            return;
547
+        }
548
+
549
+        if (count($_COOKIE) > 0) {
550
+            $requestUri = $request->getScriptName();
551
+            $processingScript = explode('/', $requestUri);
552
+            $processingScript = $processingScript[count($processingScript) - 1];
553
+
554
+            if ($processingScript === 'index.php' // index.php routes are handled in the middleware
555
+                || $processingScript === 'cron.php' // and cron.php does not need any authentication at all
556
+                || $processingScript === 'public.php' // For public.php, auth for password protected shares is done in the PublicAuth plugin
557
+            ) {
558
+                return;
559
+            }
560
+
561
+            // All other endpoints require the lax and the strict cookie
562
+            if (!$request->passesStrictCookieCheck()) {
563
+                logger('core')->warning('Request does not pass strict cookie check');
564
+                self::sendSameSiteCookies();
565
+                // Debug mode gets access to the resources without strict cookie
566
+                // due to the fact that the SabreDAV browser also lives there.
567
+                if (!$config->getSystemValueBool('debug', false)) {
568
+                    http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED);
569
+                    header('Content-Type: application/json');
570
+                    echo json_encode(['error' => 'Strict Cookie has not been found in request']);
571
+                    exit();
572
+                }
573
+            }
574
+        } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
575
+            self::sendSameSiteCookies();
576
+        }
577
+    }
578
+
579
+    public static function init(): void {
580
+        // First handle PHP configuration and copy auth headers to the expected
581
+        // $_SERVER variable before doing anything Server object related
582
+        self::setRequiredIniValues();
583
+        self::handleAuthHeaders();
584
+
585
+        // prevent any XML processing from loading external entities
586
+        libxml_set_external_entity_loader(static function () {
587
+            return null;
588
+        });
589
+
590
+        // Set default timezone before the Server object is booted
591
+        if (!date_default_timezone_set('UTC')) {
592
+            throw new \RuntimeException('Could not set timezone to UTC');
593
+        }
594
+
595
+        // calculate the root directories
596
+        OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4));
597
+
598
+        // register autoloader
599
+        $loaderStart = microtime(true);
600
+        require_once __DIR__ . '/autoloader.php';
601
+        self::$loader = new \OC\Autoloader([
602
+            OC::$SERVERROOT . '/lib/private/legacy',
603
+        ]);
604
+        spl_autoload_register([self::$loader, 'load']);
605
+        $loaderEnd = microtime(true);
606
+
607
+        self::$CLI = (php_sapi_name() == 'cli');
608
+
609
+        // Add default composer PSR-4 autoloader, ensure apcu to be disabled
610
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
611
+        self::$composerAutoloader->setApcuPrefix(null);
612
+
613
+
614
+        try {
615
+            self::initPaths();
616
+            // setup 3rdparty autoloader
617
+            $vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php';
618
+            if (!file_exists($vendorAutoLoad)) {
619
+                throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
620
+            }
621
+            require_once $vendorAutoLoad;
622
+        } catch (\RuntimeException $e) {
623
+            if (!self::$CLI) {
624
+                http_response_code(503);
625
+            }
626
+            // we can't use the template error page here, because this needs the
627
+            // DI container which isn't available yet
628
+            print($e->getMessage());
629
+            exit();
630
+        }
631
+
632
+        // setup the basic server
633
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
634
+        self::$server->boot();
635
+
636
+        try {
637
+            $profiler = new BuiltInProfiler(
638
+                Server::get(IConfig::class),
639
+                Server::get(IRequest::class),
640
+            );
641
+            $profiler->start();
642
+        } catch (\Throwable $e) {
643
+            logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']);
644
+        }
645
+
646
+        if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) {
647
+            \OC\Core\Listener\BeforeMessageLoggedEventListener::setup();
648
+        }
649
+
650
+        $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
651
+        $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
652
+        $eventLogger->start('boot', 'Initialize');
653
+
654
+        // Override php.ini and log everything if we're troubleshooting
655
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
656
+            error_reporting(E_ALL);
657
+        }
658
+
659
+        $systemConfig = Server::get(\OC\SystemConfig::class);
660
+        self::registerAutoloaderCache($systemConfig);
661
+
662
+        // initialize intl fallback if necessary
663
+        OC_Util::isSetLocaleWorking();
664
+
665
+        $config = Server::get(IConfig::class);
666
+        if (!defined('PHPUNIT_RUN')) {
667
+            $errorHandler = new OC\Log\ErrorHandler(
668
+                \OCP\Server::get(\Psr\Log\LoggerInterface::class),
669
+            );
670
+            $exceptionHandler = [$errorHandler, 'onException'];
671
+            if ($config->getSystemValueBool('debug', false)) {
672
+                set_error_handler([$errorHandler, 'onAll'], E_ALL);
673
+                if (\OC::$CLI) {
674
+                    $exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage'];
675
+                }
676
+            } else {
677
+                set_error_handler([$errorHandler, 'onError']);
678
+            }
679
+            register_shutdown_function([$errorHandler, 'onShutdown']);
680
+            set_exception_handler($exceptionHandler);
681
+        }
682
+
683
+        /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
684
+        $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
685
+        $bootstrapCoordinator->runInitialRegistration();
686
+
687
+        $eventLogger->start('init_session', 'Initialize session');
688
+
689
+        // Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users
690
+        // see https://github.com/nextcloud/server/pull/2619
691
+        if (!function_exists('simplexml_load_file')) {
692
+            throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.');
693
+        }
694
+
695
+        $appManager = Server::get(\OCP\App\IAppManager::class);
696
+        if ($systemConfig->getValue('installed', false)) {
697
+            $appManager->loadApps(['session']);
698
+        }
699
+        if (!self::$CLI) {
700
+            self::initSession();
701
+        }
702
+        $eventLogger->end('init_session');
703
+        self::checkConfig();
704
+        self::checkInstalled($systemConfig);
705
+
706
+        OC_Response::addSecurityHeaders();
707
+
708
+        self::performSameSiteCookieProtection($config);
709
+
710
+        if (!defined('OC_CONSOLE')) {
711
+            $eventLogger->start('check_server', 'Run a few configuration checks');
712
+            $errors = OC_Util::checkServer($systemConfig);
713
+            if (count($errors) > 0) {
714
+                if (!self::$CLI) {
715
+                    http_response_code(503);
716
+                    Util::addStyle('guest');
717
+                    try {
718
+                        Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]);
719
+                        exit;
720
+                    } catch (\Exception $e) {
721
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
722
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
723
+                    }
724
+                }
725
+
726
+                // Convert l10n string into regular string for usage in database
727
+                $staticErrors = [];
728
+                foreach ($errors as $error) {
729
+                    echo $error['error'] . "\n";
730
+                    echo $error['hint'] . "\n\n";
731
+                    $staticErrors[] = [
732
+                        'error' => (string)$error['error'],
733
+                        'hint' => (string)$error['hint'],
734
+                    ];
735
+                }
736
+
737
+                try {
738
+                    $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
739
+                } catch (\Exception $e) {
740
+                    echo('Writing to database failed');
741
+                }
742
+                exit(1);
743
+            } elseif (self::$CLI && $config->getSystemValueBool('installed', false)) {
744
+                $config->deleteAppValue('core', 'cronErrors');
745
+            }
746
+            $eventLogger->end('check_server');
747
+        }
748
+
749
+        // User and Groups
750
+        if (!$systemConfig->getValue('installed', false)) {
751
+            self::$server->getSession()->set('user_id', '');
752
+        }
753
+
754
+        $eventLogger->start('setup_backends', 'Setup group and user backends');
755
+        Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database());
756
+        Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
757
+
758
+        // Subscribe to the hook
759
+        \OCP\Util::connectHook(
760
+            '\OCA\Files_Sharing\API\Server2Server',
761
+            'preLoginNameUsedAsUserName',
762
+            '\OC\User\Database',
763
+            'preLoginNameUsedAsUserName'
764
+        );
765
+
766
+        //setup extra user backends
767
+        if (!\OCP\Util::needUpgrade()) {
768
+            OC_User::setupBackends();
769
+        } else {
770
+            // Run upgrades in incognito mode
771
+            OC_User::setIncognitoMode(true);
772
+        }
773
+        $eventLogger->end('setup_backends');
774
+
775
+        self::registerCleanupHooks($systemConfig);
776
+        self::registerShareHooks($systemConfig);
777
+        self::registerEncryptionWrapperAndHooks();
778
+        self::registerAccountHooks();
779
+        self::registerResourceCollectionHooks();
780
+        self::registerFileReferenceEventListener();
781
+        self::registerRenderReferenceEventListener();
782
+        self::registerAppRestrictionsHooks();
783
+
784
+        // Make sure that the application class is not loaded before the database is setup
785
+        if ($systemConfig->getValue('installed', false)) {
786
+            $appManager->loadApp('settings');
787
+            /* Build core application to make sure that listeners are registered */
788
+            Server::get(\OC\Core\Application::class);
789
+        }
790
+
791
+        //make sure temporary files are cleaned up
792
+        $tmpManager = Server::get(\OCP\ITempManager::class);
793
+        register_shutdown_function([$tmpManager, 'clean']);
794
+        $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
795
+        register_shutdown_function([$lockProvider, 'releaseAll']);
796
+
797
+        // Check whether the sample configuration has been copied
798
+        if ($systemConfig->getValue('copied_sample_config', false)) {
799
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
800
+            Server::get(ITemplateManager::class)->printErrorPage(
801
+                $l->t('Sample configuration detected'),
802
+                $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
803
+                503
804
+            );
805
+            return;
806
+        }
807
+
808
+        $request = Server::get(IRequest::class);
809
+        $host = $request->getInsecureServerHost();
810
+        /**
811
+         * if the host passed in headers isn't trusted
812
+         * FIXME: Should not be in here at all :see_no_evil:
813
+         */
814
+        if (!OC::$CLI
815
+            && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
816
+            && $config->getSystemValueBool('installed', false)
817
+        ) {
818
+            // Allow access to CSS resources
819
+            $isScssRequest = false;
820
+            if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
821
+                $isScssRequest = true;
822
+            }
823
+
824
+            if (substr($request->getRequestUri(), -11) === '/status.php') {
825
+                http_response_code(400);
826
+                header('Content-Type: application/json');
827
+                echo '{"error": "Trusted domain error.", "code": 15}';
828
+                exit();
829
+            }
830
+
831
+            if (!$isScssRequest) {
832
+                http_response_code(400);
833
+                Server::get(LoggerInterface::class)->info(
834
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
835
+                    [
836
+                        'app' => 'core',
837
+                        'remoteAddress' => $request->getRemoteAddress(),
838
+                        'host' => $host,
839
+                    ]
840
+                );
841
+
842
+                $tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest');
843
+                $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
844
+                $tmpl->printPage();
845
+
846
+                exit();
847
+            }
848
+        }
849
+        $eventLogger->end('boot');
850
+        $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
851
+        $eventLogger->start('runtime', 'Runtime');
852
+        $eventLogger->start('request', 'Full request after boot');
853
+        register_shutdown_function(function () use ($eventLogger) {
854
+            $eventLogger->end('request');
855
+        });
856
+
857
+        register_shutdown_function(function () {
858
+            $memoryPeak = memory_get_peak_usage();
859
+            $logLevel = match (true) {
860
+                $memoryPeak > 500_000_000 => ILogger::FATAL,
861
+                $memoryPeak > 400_000_000 => ILogger::ERROR,
862
+                $memoryPeak > 300_000_000 => ILogger::WARN,
863
+                default => null,
864
+            };
865
+            if ($logLevel !== null) {
866
+                $message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak);
867
+                $logger = Server::get(LoggerInterface::class);
868
+                $logger->log($logLevel, $message, ['app' => 'core']);
869
+            }
870
+        });
871
+    }
872
+
873
+    /**
874
+     * register hooks for the cleanup of cache and bruteforce protection
875
+     */
876
+    public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
877
+        //don't try to do this before we are properly setup
878
+        if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
879
+            // NOTE: This will be replaced to use OCP
880
+            $userSession = Server::get(\OC\User\Session::class);
881
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
882
+                if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
883
+                    // reset brute force delay for this IP address and username
884
+                    $uid = $userSession->getUser()->getUID();
885
+                    $request = Server::get(IRequest::class);
886
+                    $throttler = Server::get(IThrottler::class);
887
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
888
+                }
889
+
890
+                try {
891
+                    $cache = new \OC\Cache\File();
892
+                    $cache->gc();
893
+                } catch (\OC\ServerNotAvailableException $e) {
894
+                    // not a GC exception, pass it on
895
+                    throw $e;
896
+                } catch (\OC\ForbiddenException $e) {
897
+                    // filesystem blocked for this request, ignore
898
+                } catch (\Exception $e) {
899
+                    // a GC exception should not prevent users from using OC,
900
+                    // so log the exception
901
+                    Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
902
+                        'app' => 'core',
903
+                        'exception' => $e,
904
+                    ]);
905
+                }
906
+            });
907
+        }
908
+    }
909
+
910
+    private static function registerEncryptionWrapperAndHooks(): void {
911
+        /** @var \OC\Encryption\Manager */
912
+        $manager = Server::get(\OCP\Encryption\IManager::class);
913
+        Server::get(IEventDispatcher::class)->addListener(
914
+            BeforeFileSystemSetupEvent::class,
915
+            $manager->setupStorage(...),
916
+        );
917
+
918
+        $enabled = $manager->isEnabled();
919
+        if ($enabled) {
920
+            \OC\Encryption\EncryptionEventListener::register(Server::get(IEventDispatcher::class));
921
+        }
922
+    }
923
+
924
+    private static function registerAccountHooks(): void {
925
+        /** @var IEventDispatcher $dispatcher */
926
+        $dispatcher = Server::get(IEventDispatcher::class);
927
+        $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
928
+    }
929
+
930
+    private static function registerAppRestrictionsHooks(): void {
931
+        /** @var \OC\Group\Manager $groupManager */
932
+        $groupManager = Server::get(\OCP\IGroupManager::class);
933
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
934
+            $appManager = Server::get(\OCP\App\IAppManager::class);
935
+            $apps = $appManager->getEnabledAppsForGroup($group);
936
+            foreach ($apps as $appId) {
937
+                $restrictions = $appManager->getAppRestriction($appId);
938
+                if (empty($restrictions)) {
939
+                    continue;
940
+                }
941
+                $key = array_search($group->getGID(), $restrictions);
942
+                unset($restrictions[$key]);
943
+                $restrictions = array_values($restrictions);
944
+                if (empty($restrictions)) {
945
+                    $appManager->disableApp($appId);
946
+                } else {
947
+                    $appManager->enableAppForGroups($appId, $restrictions);
948
+                }
949
+            }
950
+        });
951
+    }
952
+
953
+    private static function registerResourceCollectionHooks(): void {
954
+        \OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class));
955
+    }
956
+
957
+    private static function registerFileReferenceEventListener(): void {
958
+        \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
959
+    }
960
+
961
+    private static function registerRenderReferenceEventListener() {
962
+        \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
963
+    }
964
+
965
+    /**
966
+     * register hooks for sharing
967
+     */
968
+    public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
969
+        if ($systemConfig->getValue('installed')) {
970
+
971
+            $dispatcher = Server::get(IEventDispatcher::class);
972
+            $dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class);
973
+            $dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class);
974
+            $dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class);
975
+        }
976
+    }
977
+
978
+    protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
979
+        // The class loader takes an optional low-latency cache, which MUST be
980
+        // namespaced. The instanceid is used for namespacing, but might be
981
+        // unavailable at this point. Furthermore, it might not be possible to
982
+        // generate an instanceid via \OC_Util::getInstanceId() because the
983
+        // config file may not be writable. As such, we only register a class
984
+        // loader cache if instanceid is available without trying to create one.
985
+        $instanceId = $systemConfig->getValue('instanceid', null);
986
+        if ($instanceId) {
987
+            try {
988
+                $memcacheFactory = Server::get(\OCP\ICacheFactory::class);
989
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
990
+            } catch (\Exception $ex) {
991
+            }
992
+        }
993
+    }
994
+
995
+    /**
996
+     * Handle the request
997
+     */
998
+    public static function handleRequest(): void {
999
+        Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
1000
+        $systemConfig = Server::get(\OC\SystemConfig::class);
1001
+
1002
+        // Check if Nextcloud is installed or in maintenance (update) mode
1003
+        if (!$systemConfig->getValue('installed', false)) {
1004
+            \OC::$server->getSession()->clear();
1005
+            $controller = Server::get(\OC\Core\Controller\SetupController::class);
1006
+            $controller->run($_POST);
1007
+            exit();
1008
+        }
1009
+
1010
+        $request = Server::get(IRequest::class);
1011
+        $requestPath = $request->getRawPathInfo();
1012
+        if ($requestPath === '/heartbeat') {
1013
+            return;
1014
+        }
1015
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
1016
+            self::checkMaintenanceMode($systemConfig);
1017
+
1018
+            if (\OCP\Util::needUpgrade()) {
1019
+                if (function_exists('opcache_reset')) {
1020
+                    opcache_reset();
1021
+                }
1022
+                if (!((bool)$systemConfig->getValue('maintenance', false))) {
1023
+                    self::printUpgradePage($systemConfig);
1024
+                    exit();
1025
+                }
1026
+            }
1027
+        }
1028
+
1029
+        $appManager = Server::get(\OCP\App\IAppManager::class);
1030
+
1031
+        // Always load authentication apps
1032
+        $appManager->loadApps(['authentication']);
1033
+        $appManager->loadApps(['extended_authentication']);
1034
+
1035
+        // Load minimum set of apps
1036
+        if (!\OCP\Util::needUpgrade()
1037
+            && !((bool)$systemConfig->getValue('maintenance', false))) {
1038
+            // For logged-in users: Load everything
1039
+            if (Server::get(IUserSession::class)->isLoggedIn()) {
1040
+                $appManager->loadApps();
1041
+            } else {
1042
+                // For guests: Load only filesystem and logging
1043
+                $appManager->loadApps(['filesystem', 'logging']);
1044
+
1045
+                // Don't try to login when a client is trying to get a OAuth token.
1046
+                // OAuth needs to support basic auth too, so the login is not valid
1047
+                // inside Nextcloud and the Login exception would ruin it.
1048
+                if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1049
+                    self::handleLogin($request);
1050
+                }
1051
+            }
1052
+        }
1053
+
1054
+        if (!self::$CLI) {
1055
+            try {
1056
+                if (!\OCP\Util::needUpgrade()) {
1057
+                    $appManager->loadApps(['filesystem', 'logging']);
1058
+                    $appManager->loadApps();
1059
+                }
1060
+                Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1061
+                return;
1062
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1063
+                //header('HTTP/1.0 404 Not Found');
1064
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1065
+                http_response_code(405);
1066
+                return;
1067
+            }
1068
+        }
1069
+
1070
+        // Handle WebDAV
1071
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1072
+            // not allowed any more to prevent people
1073
+            // mounting this root directly.
1074
+            // Users need to mount remote.php/webdav instead.
1075
+            http_response_code(405);
1076
+            return;
1077
+        }
1078
+
1079
+        // Handle requests for JSON or XML
1080
+        $acceptHeader = $request->getHeader('Accept');
1081
+        if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1082
+            http_response_code(404);
1083
+            return;
1084
+        }
1085
+
1086
+        // Handle resources that can't be found
1087
+        // This prevents browsers from redirecting to the default page and then
1088
+        // attempting to parse HTML as CSS and similar.
1089
+        $destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1090
+        if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1091
+            http_response_code(404);
1092
+            return;
1093
+        }
1094
+
1095
+        // Redirect to the default app or login only as an entry point
1096
+        if ($requestPath === '') {
1097
+            // Someone is logged in
1098
+            if (Server::get(IUserSession::class)->isLoggedIn()) {
1099
+                header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1100
+            } else {
1101
+                // Not handled and not logged in
1102
+                header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1103
+            }
1104
+            return;
1105
+        }
1106
+
1107
+        try {
1108
+            Server::get(\OC\Route\Router::class)->match('/error/404');
1109
+        } catch (\Exception $e) {
1110
+            if (!$e instanceof MethodNotAllowedException) {
1111
+                logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1112
+            }
1113
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
1114
+            Server::get(ITemplateManager::class)->printErrorPage(
1115
+                '404',
1116
+                $l->t('The page could not be found on the server.'),
1117
+                404
1118
+            );
1119
+        }
1120
+    }
1121
+
1122
+    /**
1123
+     * Check login: apache auth, auth token, basic auth
1124
+     */
1125
+    public static function handleLogin(OCP\IRequest $request): bool {
1126
+        if ($request->getHeader('X-Nextcloud-Federation')) {
1127
+            return false;
1128
+        }
1129
+        $userSession = Server::get(\OC\User\Session::class);
1130
+        if (OC_User::handleApacheAuth()) {
1131
+            return true;
1132
+        }
1133
+        if (self::tryAppAPILogin($request)) {
1134
+            return true;
1135
+        }
1136
+        if ($userSession->tryTokenLogin($request)) {
1137
+            return true;
1138
+        }
1139
+        if (isset($_COOKIE['nc_username'])
1140
+            && isset($_COOKIE['nc_token'])
1141
+            && isset($_COOKIE['nc_session_id'])
1142
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1143
+            return true;
1144
+        }
1145
+        if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) {
1146
+            return true;
1147
+        }
1148
+        return false;
1149
+    }
1150
+
1151
+    protected static function handleAuthHeaders(): void {
1152
+        //copy http auth headers for apache+php-fcgid work around
1153
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1154
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1155
+        }
1156
+
1157
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1158
+        $vars = [
1159
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1160
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1161
+        ];
1162
+        foreach ($vars as $var) {
1163
+            if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1164
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1165
+                if (count($credentials) === 2) {
1166
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1167
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1168
+                    break;
1169
+                }
1170
+            }
1171
+        }
1172
+    }
1173
+
1174
+    protected static function tryAppAPILogin(OCP\IRequest $request): bool {
1175
+        if (!$request->getHeader('AUTHORIZATION-APP-API')) {
1176
+            return false;
1177
+        }
1178
+        $appManager = Server::get(OCP\App\IAppManager::class);
1179
+        if (!$appManager->isEnabledForAnyone('app_api')) {
1180
+            return false;
1181
+        }
1182
+        try {
1183
+            $appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class);
1184
+            return $appAPIService->validateExAppRequestToNC($request);
1185
+        } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) {
1186
+            return false;
1187
+        }
1188
+    }
1189 1189
 }
1190 1190
 
1191 1191
 OC::init();
Please login to merge, or discard this patch.
Spacing   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -87,13 +87,13 @@  discard block
 block discarded – undo
87 87
 	 */
88 88
 	public static function initPaths(): void {
89 89
 		if (defined('PHPUNIT_CONFIG_DIR')) {
90
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
91
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
92
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
90
+			self::$configDir = OC::$SERVERROOT.'/'.PHPUNIT_CONFIG_DIR.'/';
91
+		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT.'/tests/config/')) {
92
+			self::$configDir = OC::$SERVERROOT.'/tests/config/';
93 93
 		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
94
-			self::$configDir = rtrim($dir, '/') . '/';
94
+			self::$configDir = rtrim($dir, '/').'/';
95 95
 		} else {
96
-			self::$configDir = OC::$SERVERROOT . '/config/';
96
+			self::$configDir = OC::$SERVERROOT.'/config/';
97 97
 		}
98 98
 		self::$config = new \OC\Config(self::$configDir);
99 99
 
@@ -122,9 +122,9 @@  discard block
 block discarded – undo
122 122
 			//make sure suburi follows the same rules as scriptName
123 123
 			if (substr(OC::$SUBURI, -9) != 'index.php') {
124 124
 				if (substr(OC::$SUBURI, -1) != '/') {
125
-					OC::$SUBURI = OC::$SUBURI . '/';
125
+					OC::$SUBURI = OC::$SUBURI.'/';
126 126
 				}
127
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
127
+				OC::$SUBURI = OC::$SUBURI.'index.php';
128 128
 			}
129 129
 		}
130 130
 
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
136 136
 
137 137
 				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
138
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
138
+					OC::$WEBROOT = '/'.OC::$WEBROOT;
139 139
 				}
140 140
 			} else {
141 141
 				// The scriptName is not ending with OC::$SUBURI
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 			// slash which is required by URL generation.
150 150
 			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
151 151
 					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
152
-				header('Location: ' . \OC::$WEBROOT . '/');
152
+				header('Location: '.\OC::$WEBROOT.'/');
153 153
 				exit();
154 154
 			}
155 155
 		}
@@ -164,8 +164,8 @@  discard block
 block discarded – undo
164 164
 					OC::$APPSROOTS[] = $paths;
165 165
 				}
166 166
 			}
167
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
168
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
167
+		} elseif (file_exists(OC::$SERVERROOT.'/apps')) {
168
+			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT.'/apps', 'url' => '/apps', 'writable' => true];
169 169
 		}
170 170
 
171 171
 		if (empty(OC::$APPSROOTS)) {
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 
190 190
 	public static function checkConfig(): void {
191 191
 		// Create config if it does not already exist
192
-		$configFilePath = self::$configDir . '/config.php';
192
+		$configFilePath = self::$configDir.'/config.php';
193 193
 		if (!file_exists($configFilePath)) {
194 194
 			@touch($configFilePath);
195 195
 		}
@@ -203,18 +203,18 @@  discard block
 block discarded – undo
203 203
 			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
204 204
 
205 205
 			if (self::$CLI) {
206
-				echo $l->t('Cannot write into "config" directory!') . "\n";
207
-				echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n";
206
+				echo $l->t('Cannot write into "config" directory!')."\n";
207
+				echo $l->t('This can usually be fixed by giving the web server write access to the config directory.')."\n";
208 208
 				echo "\n";
209
-				echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . "\n";
210
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n";
209
+				echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
210
+				echo $l->t('See %s', [$urlGenerator->linkToDocs('admin-config')])."\n";
211 211
 				exit;
212 212
 			} else {
213 213
 				Server::get(ITemplateManager::class)->printErrorPage(
214 214
 					$l->t('Cannot write into "config" directory!'),
215
-					$l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
216
-					. $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
217
-					. $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
215
+					$l->t('This can usually be fixed by giving the web server write access to the config directory.').' '
216
+					. $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.').' '
217
+					. $l->t('See %s', [$urlGenerator->linkToDocs('admin-config')]),
218 218
 					503
219 219
 				);
220 220
 			}
@@ -230,8 +230,8 @@  discard block
 block discarded – undo
230 230
 			if (OC::$CLI) {
231 231
 				throw new Exception('Not installed');
232 232
 			} else {
233
-				$url = OC::$WEBROOT . '/index.php';
234
-				header('Location: ' . $url);
233
+				$url = OC::$WEBROOT.'/index.php';
234
+				header('Location: '.$url);
235 235
 			}
236 236
 			exit();
237 237
 		}
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 
240 240
 	public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void {
241 241
 		// Allow ajax update script to execute without being stopped
242
-		if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
242
+		if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
243 243
 			// send http status 503
244 244
 			http_response_code(503);
245 245
 			header('X-Nextcloud-Maintenance-Mode: 1');
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
 		$incompatibleDisabledApps = [];
343 343
 		foreach ($incompatibleApps as $appInfo) {
344 344
 			if ($appManager->isShipped($appInfo['id'])) {
345
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
345
+				$incompatibleShippedApps[] = $appInfo['name'].' ('.$appInfo['id'].')';
346 346
 			}
347 347
 			if (!in_array($appInfo['id'], $incompatibleOverwrites)) {
348 348
 				$incompatibleDisabledApps[] = $appInfo;
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
 		if (!empty($incompatibleShippedApps)) {
353 353
 			$l = Server::get(\OCP\L10N\IFactory::class)->get('core');
354 354
 			$hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]);
355
-			throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint);
355
+			throw new \OCP\HintException('Application '.implode(', ', $incompatibleShippedApps).' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint);
356 356
 		}
357 357
 
358 358
 		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
@@ -396,7 +396,7 @@  discard block
 block discarded – undo
396 396
 		}
397 397
 
398 398
 		// set the cookie path to the Nextcloud directory
399
-		$cookie_path = OC::$WEBROOT ? : '/';
399
+		$cookie_path = OC::$WEBROOT ?: '/';
400 400
 		ini_set('session.cookie_path', $cookie_path);
401 401
 
402 402
 		// Let the session name be changed in the initSession Hook
@@ -420,7 +420,7 @@  discard block
 block discarded – undo
420 420
 
421 421
 			// if session can't be started break with http 500 error
422 422
 		} catch (Exception $e) {
423
-			Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
423
+			Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base', 'exception' => $e]);
424 424
 			//show the user a detailed error page
425 425
 			Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500);
426 426
 			die();
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
 		// session timeout
433 433
 		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
434 434
 			if (isset($_COOKIE[session_name()])) {
435
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
435
+				setcookie(session_name(), '', -1, self::$WEBROOT ?: '/');
436 436
 			}
437 437
 			Server::get(IUserSession::class)->logout();
438 438
 		}
@@ -503,7 +503,7 @@  discard block
 block discarded – undo
503 503
 		foreach ($policies as $policy) {
504 504
 			header(
505 505
 				sprintf(
506
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
506
+					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;'.$secureCookie.'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
507 507
 					$cookiePrefix,
508 508
 					$policy,
509 509
 					$cookieParams['path'],
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
 		self::handleAuthHeaders();
584 584
 
585 585
 		// prevent any XML processing from loading external entities
586
-		libxml_set_external_entity_loader(static function () {
586
+		libxml_set_external_entity_loader(static function() {
587 587
 			return null;
588 588
 		});
589 589
 
@@ -597,9 +597,9 @@  discard block
 block discarded – undo
597 597
 
598 598
 		// register autoloader
599 599
 		$loaderStart = microtime(true);
600
-		require_once __DIR__ . '/autoloader.php';
600
+		require_once __DIR__.'/autoloader.php';
601 601
 		self::$loader = new \OC\Autoloader([
602
-			OC::$SERVERROOT . '/lib/private/legacy',
602
+			OC::$SERVERROOT.'/lib/private/legacy',
603 603
 		]);
604 604
 		spl_autoload_register([self::$loader, 'load']);
605 605
 		$loaderEnd = microtime(true);
@@ -607,14 +607,14 @@  discard block
 block discarded – undo
607 607
 		self::$CLI = (php_sapi_name() == 'cli');
608 608
 
609 609
 		// Add default composer PSR-4 autoloader, ensure apcu to be disabled
610
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
610
+		self::$composerAutoloader = require_once OC::$SERVERROOT.'/lib/composer/autoload.php';
611 611
 		self::$composerAutoloader->setApcuPrefix(null);
612 612
 
613 613
 
614 614
 		try {
615 615
 			self::initPaths();
616 616
 			// setup 3rdparty autoloader
617
-			$vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php';
617
+			$vendorAutoLoad = OC::$SERVERROOT.'/3rdparty/autoload.php';
618 618
 			if (!file_exists($vendorAutoLoad)) {
619 619
 				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
620 620
 			}
@@ -640,10 +640,10 @@  discard block
 block discarded – undo
640 640
 			);
641 641
 			$profiler->start();
642 642
 		} catch (\Throwable $e) {
643
-			logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']);
643
+			logger('core')->error('Failed to start profiler: '.$e->getMessage(), ['app' => 'base']);
644 644
 		}
645 645
 
646
-		if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) {
646
+		if (self::$CLI && in_array('--'.\OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) {
647 647
 			\OC\Core\Listener\BeforeMessageLoggedEventListener::setup();
648 648
 		}
649 649
 
@@ -726,11 +726,11 @@  discard block
 block discarded – undo
726 726
 				// Convert l10n string into regular string for usage in database
727 727
 				$staticErrors = [];
728 728
 				foreach ($errors as $error) {
729
-					echo $error['error'] . "\n";
730
-					echo $error['hint'] . "\n\n";
729
+					echo $error['error']."\n";
730
+					echo $error['hint']."\n\n";
731 731
 					$staticErrors[] = [
732
-						'error' => (string)$error['error'],
733
-						'hint' => (string)$error['hint'],
732
+						'error' => (string) $error['error'],
733
+						'hint' => (string) $error['hint'],
734 734
 					];
735 735
 				}
736 736
 
@@ -850,11 +850,11 @@  discard block
 block discarded – undo
850 850
 		$eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
851 851
 		$eventLogger->start('runtime', 'Runtime');
852 852
 		$eventLogger->start('request', 'Full request after boot');
853
-		register_shutdown_function(function () use ($eventLogger) {
853
+		register_shutdown_function(function() use ($eventLogger) {
854 854
 			$eventLogger->end('request');
855 855
 		});
856 856
 
857
-		register_shutdown_function(function () {
857
+		register_shutdown_function(function() {
858 858
 			$memoryPeak = memory_get_peak_usage();
859 859
 			$logLevel = match (true) {
860 860
 				$memoryPeak > 500_000_000 => ILogger::FATAL,
@@ -863,7 +863,7 @@  discard block
 block discarded – undo
863 863
 				default => null,
864 864
 			};
865 865
 			if ($logLevel !== null) {
866
-				$message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak);
866
+				$message = 'Request used more than 300 MB of RAM: '.Util::humanFileSize($memoryPeak);
867 867
 				$logger = Server::get(LoggerInterface::class);
868 868
 				$logger->log($logLevel, $message, ['app' => 'core']);
869 869
 			}
@@ -878,7 +878,7 @@  discard block
 block discarded – undo
878 878
 		if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
879 879
 			// NOTE: This will be replaced to use OCP
880 880
 			$userSession = Server::get(\OC\User\Session::class);
881
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
881
+			$userSession->listen('\OC\User', 'postLogin', function() use ($userSession) {
882 882
 				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
883 883
 					// reset brute force delay for this IP address and username
884 884
 					$uid = $userSession->getUser()->getUID();
@@ -930,7 +930,7 @@  discard block
 block discarded – undo
930 930
 	private static function registerAppRestrictionsHooks(): void {
931 931
 		/** @var \OC\Group\Manager $groupManager */
932 932
 		$groupManager = Server::get(\OCP\IGroupManager::class);
933
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
933
+		$groupManager->listen('\OC\Group', 'postDelete', function(\OCP\IGroup $group) {
934 934
 			$appManager = Server::get(\OCP\App\IAppManager::class);
935 935
 			$apps = $appManager->getEnabledAppsForGroup($group);
936 936
 			foreach ($apps as $appId) {
@@ -1019,7 +1019,7 @@  discard block
 block discarded – undo
1019 1019
 				if (function_exists('opcache_reset')) {
1020 1020
 					opcache_reset();
1021 1021
 				}
1022
-				if (!((bool)$systemConfig->getValue('maintenance', false))) {
1022
+				if (!((bool) $systemConfig->getValue('maintenance', false))) {
1023 1023
 					self::printUpgradePage($systemConfig);
1024 1024
 					exit();
1025 1025
 				}
@@ -1034,7 +1034,7 @@  discard block
 block discarded – undo
1034 1034
 
1035 1035
 		// Load minimum set of apps
1036 1036
 		if (!\OCP\Util::needUpgrade()
1037
-			&& !((bool)$systemConfig->getValue('maintenance', false))) {
1037
+			&& !((bool) $systemConfig->getValue('maintenance', false))) {
1038 1038
 			// For logged-in users: Load everything
1039 1039
 			if (Server::get(IUserSession::class)->isLoggedIn()) {
1040 1040
 				$appManager->loadApps();
@@ -1096,10 +1096,10 @@  discard block
 block discarded – undo
1096 1096
 		if ($requestPath === '') {
1097 1097
 			// Someone is logged in
1098 1098
 			if (Server::get(IUserSession::class)->isLoggedIn()) {
1099
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1099
+				header('Location: '.Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1100 1100
 			} else {
1101 1101
 				// Not handled and not logged in
1102
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1102
+				header('Location: '.Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1103 1103
 			}
1104 1104
 			return;
1105 1105
 		}
@@ -1182,7 +1182,7 @@  discard block
 block discarded – undo
1182 1182
 		try {
1183 1183
 			$appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class);
1184 1184
 			return $appAPIService->validateExAppRequestToNC($request);
1185
-		} catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) {
1185
+		} catch (\Psr\Container\NotFoundExceptionInterface | \Psr\Container\ContainerExceptionInterface $e) {
1186 1186
 			return false;
1187 1187
 		}
1188 1188
 	}
Please login to merge, or discard this patch.
tests/lib/AutoLoaderTest.php 2 patches
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -8,44 +8,44 @@
 block discarded – undo
8 8
 namespace Test;
9 9
 
10 10
 class AutoLoaderTest extends TestCase {
11
-	/**
12
-	 * @var \OC\Autoloader $loader
13
-	 */
14
-	private $loader;
15
-
16
-	protected function setUp(): void {
17
-		parent::setUp();
18
-		$this->loader = new \OC\AutoLoader([]);
19
-	}
20
-
21
-	public function testLegacyPath(): void {
22
-		$this->assertEquals([
23
-			\OC::$SERVERROOT . '/lib/private/legacy/json.php',
24
-		], $this->loader->findClass('OC_JSON'));
25
-	}
26
-
27
-	public function testLoadCore(): void {
28
-		$this->assertEquals([
29
-			\OC::$SERVERROOT . '/lib/private/legacy/foo/bar.php',
30
-		], $this->loader->findClass('OC_Foo_Bar'));
31
-	}
32
-
33
-	public function testLoadPublicNamespace(): void {
34
-		$this->assertEquals([], $this->loader->findClass('OCP\Foo\Bar'));
35
-	}
36
-
37
-	public function testLoadAppNamespace(): void {
38
-		$result = $this->loader->findClass('OCA\Files\Foobar');
39
-		$this->assertEquals(2, count($result));
40
-		$this->assertStringEndsWith('apps/files/foobar.php', $result[0]);
41
-		$this->assertStringEndsWith('apps/files/lib/foobar.php', $result[1]);
42
-	}
43
-
44
-	public function testLoadCoreNamespaceCore(): void {
45
-		$this->assertEquals([], $this->loader->findClass('OC\Core\Foo\Bar'));
46
-	}
47
-
48
-	public function testLoadCoreNamespaceSettings(): void {
49
-		$this->assertEquals([], $this->loader->findClass('OC\Settings\Foo\Bar'));
50
-	}
11
+    /**
12
+     * @var \OC\Autoloader $loader
13
+     */
14
+    private $loader;
15
+
16
+    protected function setUp(): void {
17
+        parent::setUp();
18
+        $this->loader = new \OC\AutoLoader([]);
19
+    }
20
+
21
+    public function testLegacyPath(): void {
22
+        $this->assertEquals([
23
+            \OC::$SERVERROOT . '/lib/private/legacy/json.php',
24
+        ], $this->loader->findClass('OC_JSON'));
25
+    }
26
+
27
+    public function testLoadCore(): void {
28
+        $this->assertEquals([
29
+            \OC::$SERVERROOT . '/lib/private/legacy/foo/bar.php',
30
+        ], $this->loader->findClass('OC_Foo_Bar'));
31
+    }
32
+
33
+    public function testLoadPublicNamespace(): void {
34
+        $this->assertEquals([], $this->loader->findClass('OCP\Foo\Bar'));
35
+    }
36
+
37
+    public function testLoadAppNamespace(): void {
38
+        $result = $this->loader->findClass('OCA\Files\Foobar');
39
+        $this->assertEquals(2, count($result));
40
+        $this->assertStringEndsWith('apps/files/foobar.php', $result[0]);
41
+        $this->assertStringEndsWith('apps/files/lib/foobar.php', $result[1]);
42
+    }
43
+
44
+    public function testLoadCoreNamespaceCore(): void {
45
+        $this->assertEquals([], $this->loader->findClass('OC\Core\Foo\Bar'));
46
+    }
47
+
48
+    public function testLoadCoreNamespaceSettings(): void {
49
+        $this->assertEquals([], $this->loader->findClass('OC\Settings\Foo\Bar'));
50
+    }
51 51
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -20,13 +20,13 @@
 block discarded – undo
20 20
 
21 21
 	public function testLegacyPath(): void {
22 22
 		$this->assertEquals([
23
-			\OC::$SERVERROOT . '/lib/private/legacy/json.php',
23
+			\OC::$SERVERROOT.'/lib/private/legacy/json.php',
24 24
 		], $this->loader->findClass('OC_JSON'));
25 25
 	}
26 26
 
27 27
 	public function testLoadCore(): void {
28 28
 		$this->assertEquals([
29
-			\OC::$SERVERROOT . '/lib/private/legacy/foo/bar.php',
29
+			\OC::$SERVERROOT.'/lib/private/legacy/foo/bar.php',
30 30
 		], $this->loader->findClass('OC_Foo_Bar'));
31 31
 	}
32 32
 
Please login to merge, or discard this patch.