Completed
Push — master ( 13f230...5ba9bc )
by
unknown
26:52 queued 14s
created
lib/private/legacy/OC_Helper.php 1 patch
Indentation   +385 added lines, -385 removed lines patch added patch discarded remove patch
@@ -32,392 +32,392 @@
 block discarded – undo
32 32
  * }
33 33
  */
34 34
 class OC_Helper {
35
-	private static $templateManager;
36
-	private static ?ICacheFactory $cacheFactory = null;
37
-	private static ?bool $quotaIncludeExternalStorage = null;
38
-
39
-	/**
40
-	 * Recursive copying of folders
41
-	 * @param string $src source folder
42
-	 * @param string $dest target folder
43
-	 * @return void
44
-	 * @deprecated 32.0.0 - use \OCP\Files\Folder::copy
45
-	 */
46
-	public static function copyr($src, $dest) {
47
-		if (!file_exists($src)) {
48
-			return;
49
-		}
50
-
51
-		if (is_dir($src)) {
52
-			if (!is_dir($dest)) {
53
-				mkdir($dest);
54
-			}
55
-			$files = scandir($src);
56
-			foreach ($files as $file) {
57
-				if ($file != '.' && $file != '..') {
58
-					self::copyr("$src/$file", "$dest/$file");
59
-				}
60
-			}
61
-		} else {
62
-			$validator = \OCP\Server::get(FilenameValidator::class);
63
-			if (!$validator->isForbidden($src)) {
64
-				copy($src, $dest);
65
-			}
66
-		}
67
-	}
68
-
69
-	/**
70
-	 * @deprecated 18.0.0
71
-	 * @return \OC\Files\Type\TemplateManager
72
-	 */
73
-	public static function getFileTemplateManager() {
74
-		if (!self::$templateManager) {
75
-			self::$templateManager = new \OC\Files\Type\TemplateManager();
76
-		}
77
-		return self::$templateManager;
78
-	}
79
-
80
-	/**
81
-	 * detect if a given program is found in the search PATH
82
-	 *
83
-	 * @param string $name
84
-	 * @param bool $path
85
-	 * @internal param string $program name
86
-	 * @internal param string $optional search path, defaults to $PATH
87
-	 * @return bool true if executable program found in path
88
-	 * @deprecated 32.0.0 use the \OCP\IBinaryFinder
89
-	 */
90
-	public static function canExecute($name, $path = false) {
91
-		// path defaults to PATH from environment if not set
92
-		if ($path === false) {
93
-			$path = getenv('PATH');
94
-		}
95
-		// we look for an executable file of that name
96
-		$exts = [''];
97
-		$check_fn = 'is_executable';
98
-		// Default check will be done with $path directories :
99
-		$dirs = explode(PATH_SEPARATOR, (string)$path);
100
-		// WARNING : We have to check if open_basedir is enabled :
101
-		$obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
102
-		if ($obd != 'none') {
103
-			$obd_values = explode(PATH_SEPARATOR, $obd);
104
-			if (count($obd_values) > 0 and $obd_values[0]) {
105
-				// open_basedir is in effect !
106
-				// We need to check if the program is in one of these dirs :
107
-				$dirs = $obd_values;
108
-			}
109
-		}
110
-		foreach ($dirs as $dir) {
111
-			foreach ($exts as $ext) {
112
-				if ($check_fn("$dir/$name" . $ext)) {
113
-					return true;
114
-				}
115
-			}
116
-		}
117
-		return false;
118
-	}
119
-
120
-	/**
121
-	 * copy the contents of one stream to another
122
-	 *
123
-	 * @param resource $source
124
-	 * @param resource $target
125
-	 * @return array the number of bytes copied and result
126
-	 * @deprecated 5.0.0 - Use \OCP\Files::streamCopy
127
-	 */
128
-	public static function streamCopy($source, $target) {
129
-		return \OCP\Files::streamCopy($source, $target, true);
130
-	}
131
-
132
-	/**
133
-	 * Adds a suffix to the name in case the file exists
134
-	 *
135
-	 * @param string $path
136
-	 * @param string $filename
137
-	 * @return string
138
-	 */
139
-	public static function buildNotExistingFileName($path, $filename) {
140
-		$view = \OC\Files\Filesystem::getView();
141
-		return self::buildNotExistingFileNameForView($path, $filename, $view);
142
-	}
143
-
144
-	/**
145
-	 * Adds a suffix to the name in case the file exists
146
-	 *
147
-	 * @param string $path
148
-	 * @param string $filename
149
-	 * @return string
150
-	 */
151
-	public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
152
-		if ($path === '/') {
153
-			$path = '';
154
-		}
155
-		if ($pos = strrpos($filename, '.')) {
156
-			$name = substr($filename, 0, $pos);
157
-			$ext = substr($filename, $pos);
158
-		} else {
159
-			$name = $filename;
160
-			$ext = '';
161
-		}
162
-
163
-		$newpath = $path . '/' . $filename;
164
-		if ($view->file_exists($newpath)) {
165
-			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
166
-				//Replace the last "(number)" with "(number+1)"
167
-				$last_match = count($matches[0]) - 1;
168
-				$counter = $matches[1][$last_match][0] + 1;
169
-				$offset = $matches[0][$last_match][1];
170
-				$match_length = strlen($matches[0][$last_match][0]);
171
-			} else {
172
-				$counter = 2;
173
-				$match_length = 0;
174
-				$offset = false;
175
-			}
176
-			do {
177
-				if ($offset) {
178
-					//Replace the last "(number)" with "(number+1)"
179
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
180
-				} else {
181
-					$newname = $name . ' (' . $counter . ')';
182
-				}
183
-				$newpath = $path . '/' . $newname . $ext;
184
-				$counter++;
185
-			} while ($view->file_exists($newpath));
186
-		}
187
-
188
-		return $newpath;
189
-	}
190
-
191
-	/**
192
-	 * Checks if a function is available
193
-	 *
194
-	 * @deprecated 25.0.0 use \OCP\Util::isFunctionEnabled instead
195
-	 */
196
-	public static function is_function_enabled(string $function_name): bool {
197
-		return Util::isFunctionEnabled($function_name);
198
-	}
199
-
200
-	/**
201
-	 * Try to find a program
202
-	 * @deprecated 25.0.0 Use \OCP\IBinaryFinder directly
203
-	 */
204
-	public static function findBinaryPath(string $program): ?string {
205
-		$result = Server::get(IBinaryFinder::class)->findBinaryPath($program);
206
-		return $result !== false ? $result : null;
207
-	}
208
-
209
-	/**
210
-	 * Calculate the disc space for the given path
211
-	 *
212
-	 * BEWARE: this requires that Util::setupFS() was called
213
-	 * already !
214
-	 *
215
-	 * @param string $path
216
-	 * @param \OCP\Files\FileInfo $rootInfo (optional)
217
-	 * @param bool $includeMountPoints whether to include mount points in the size calculation
218
-	 * @param bool $useCache whether to use the cached quota values
219
-	 * @psalm-suppress LessSpecificReturnStatement Legacy code outputs weird types - manually validated that they are correct
220
-	 * @return StorageInfo
221
-	 * @throws \OCP\Files\NotFoundException
222
-	 */
223
-	public static function getStorageInfo($path, $rootInfo = null, $includeMountPoints = true, $useCache = true) {
224
-		if (!self::$cacheFactory) {
225
-			self::$cacheFactory = Server::get(ICacheFactory::class);
226
-		}
227
-		$memcache = self::$cacheFactory->createLocal('storage_info');
228
-
229
-		// return storage info without adding mount points
230
-		if (self::$quotaIncludeExternalStorage === null) {
231
-			self::$quotaIncludeExternalStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
232
-		}
233
-
234
-		$view = Filesystem::getView();
235
-		if (!$view) {
236
-			throw new \OCP\Files\NotFoundException();
237
-		}
238
-		$fullPath = Filesystem::normalizePath($view->getAbsolutePath($path));
239
-
240
-		$cacheKey = $fullPath . '::' . ($includeMountPoints ? 'include' : 'exclude');
241
-		if ($useCache) {
242
-			$cached = $memcache->get($cacheKey);
243
-			if ($cached) {
244
-				return $cached;
245
-			}
246
-		}
247
-
248
-		if (!$rootInfo) {
249
-			$rootInfo = \OC\Files\Filesystem::getFileInfo($path, self::$quotaIncludeExternalStorage ? 'ext' : false);
250
-		}
251
-		if (!$rootInfo instanceof \OCP\Files\FileInfo) {
252
-			throw new \OCP\Files\NotFoundException('The root directory of the user\'s files is missing');
253
-		}
254
-		$used = $rootInfo->getSize($includeMountPoints);
255
-		if ($used < 0) {
256
-			$used = 0.0;
257
-		}
258
-		/** @var int|float $quota */
259
-		$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
260
-		$mount = $rootInfo->getMountPoint();
261
-		$storage = $mount->getStorage();
262
-		$sourceStorage = $storage;
263
-		if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
264
-			self::$quotaIncludeExternalStorage = false;
265
-		}
266
-		if (self::$quotaIncludeExternalStorage) {
267
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
268
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
269
-			) {
270
-				/** @var \OC\Files\Storage\Home $storage */
271
-				$user = $storage->getUser();
272
-			} else {
273
-				$user = \OC::$server->getUserSession()->getUser();
274
-			}
275
-			$quota = OC_Util::getUserQuota($user);
276
-			if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
277
-				// always get free space / total space from root + mount points
278
-				return self::getGlobalStorageInfo($quota, $user, $mount);
279
-			}
280
-		}
281
-
282
-		// TODO: need a better way to get total space from storage
283
-		if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
284
-			/** @var \OC\Files\Storage\Wrapper\Quota $storage */
285
-			$quota = $sourceStorage->getQuota();
286
-		}
287
-		try {
288
-			$free = $sourceStorage->free_space($rootInfo->getInternalPath());
289
-			if (is_bool($free)) {
290
-				$free = 0.0;
291
-			}
292
-		} catch (\Exception $e) {
293
-			if ($path === '') {
294
-				throw $e;
295
-			}
296
-			/** @var LoggerInterface $logger */
297
-			$logger = \OC::$server->get(LoggerInterface::class);
298
-			$logger->warning('Error while getting quota info, using root quota', ['exception' => $e]);
299
-			$rootInfo = self::getStorageInfo('');
300
-			$memcache->set($cacheKey, $rootInfo, 5 * 60);
301
-			return $rootInfo;
302
-		}
303
-		if ($free >= 0) {
304
-			$total = $free + $used;
305
-		} else {
306
-			$total = $free; //either unknown or unlimited
307
-		}
308
-		if ($total > 0) {
309
-			if ($quota > 0 && $total > $quota) {
310
-				$total = $quota;
311
-			}
312
-			// prevent division by zero or error codes (negative values)
313
-			$relative = round(($used / $total) * 10000) / 100;
314
-		} else {
315
-			$relative = 0;
316
-		}
317
-
318
-		/*
35
+    private static $templateManager;
36
+    private static ?ICacheFactory $cacheFactory = null;
37
+    private static ?bool $quotaIncludeExternalStorage = null;
38
+
39
+    /**
40
+     * Recursive copying of folders
41
+     * @param string $src source folder
42
+     * @param string $dest target folder
43
+     * @return void
44
+     * @deprecated 32.0.0 - use \OCP\Files\Folder::copy
45
+     */
46
+    public static function copyr($src, $dest) {
47
+        if (!file_exists($src)) {
48
+            return;
49
+        }
50
+
51
+        if (is_dir($src)) {
52
+            if (!is_dir($dest)) {
53
+                mkdir($dest);
54
+            }
55
+            $files = scandir($src);
56
+            foreach ($files as $file) {
57
+                if ($file != '.' && $file != '..') {
58
+                    self::copyr("$src/$file", "$dest/$file");
59
+                }
60
+            }
61
+        } else {
62
+            $validator = \OCP\Server::get(FilenameValidator::class);
63
+            if (!$validator->isForbidden($src)) {
64
+                copy($src, $dest);
65
+            }
66
+        }
67
+    }
68
+
69
+    /**
70
+     * @deprecated 18.0.0
71
+     * @return \OC\Files\Type\TemplateManager
72
+     */
73
+    public static function getFileTemplateManager() {
74
+        if (!self::$templateManager) {
75
+            self::$templateManager = new \OC\Files\Type\TemplateManager();
76
+        }
77
+        return self::$templateManager;
78
+    }
79
+
80
+    /**
81
+     * detect if a given program is found in the search PATH
82
+     *
83
+     * @param string $name
84
+     * @param bool $path
85
+     * @internal param string $program name
86
+     * @internal param string $optional search path, defaults to $PATH
87
+     * @return bool true if executable program found in path
88
+     * @deprecated 32.0.0 use the \OCP\IBinaryFinder
89
+     */
90
+    public static function canExecute($name, $path = false) {
91
+        // path defaults to PATH from environment if not set
92
+        if ($path === false) {
93
+            $path = getenv('PATH');
94
+        }
95
+        // we look for an executable file of that name
96
+        $exts = [''];
97
+        $check_fn = 'is_executable';
98
+        // Default check will be done with $path directories :
99
+        $dirs = explode(PATH_SEPARATOR, (string)$path);
100
+        // WARNING : We have to check if open_basedir is enabled :
101
+        $obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
102
+        if ($obd != 'none') {
103
+            $obd_values = explode(PATH_SEPARATOR, $obd);
104
+            if (count($obd_values) > 0 and $obd_values[0]) {
105
+                // open_basedir is in effect !
106
+                // We need to check if the program is in one of these dirs :
107
+                $dirs = $obd_values;
108
+            }
109
+        }
110
+        foreach ($dirs as $dir) {
111
+            foreach ($exts as $ext) {
112
+                if ($check_fn("$dir/$name" . $ext)) {
113
+                    return true;
114
+                }
115
+            }
116
+        }
117
+        return false;
118
+    }
119
+
120
+    /**
121
+     * copy the contents of one stream to another
122
+     *
123
+     * @param resource $source
124
+     * @param resource $target
125
+     * @return array the number of bytes copied and result
126
+     * @deprecated 5.0.0 - Use \OCP\Files::streamCopy
127
+     */
128
+    public static function streamCopy($source, $target) {
129
+        return \OCP\Files::streamCopy($source, $target, true);
130
+    }
131
+
132
+    /**
133
+     * Adds a suffix to the name in case the file exists
134
+     *
135
+     * @param string $path
136
+     * @param string $filename
137
+     * @return string
138
+     */
139
+    public static function buildNotExistingFileName($path, $filename) {
140
+        $view = \OC\Files\Filesystem::getView();
141
+        return self::buildNotExistingFileNameForView($path, $filename, $view);
142
+    }
143
+
144
+    /**
145
+     * Adds a suffix to the name in case the file exists
146
+     *
147
+     * @param string $path
148
+     * @param string $filename
149
+     * @return string
150
+     */
151
+    public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
152
+        if ($path === '/') {
153
+            $path = '';
154
+        }
155
+        if ($pos = strrpos($filename, '.')) {
156
+            $name = substr($filename, 0, $pos);
157
+            $ext = substr($filename, $pos);
158
+        } else {
159
+            $name = $filename;
160
+            $ext = '';
161
+        }
162
+
163
+        $newpath = $path . '/' . $filename;
164
+        if ($view->file_exists($newpath)) {
165
+            if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
166
+                //Replace the last "(number)" with "(number+1)"
167
+                $last_match = count($matches[0]) - 1;
168
+                $counter = $matches[1][$last_match][0] + 1;
169
+                $offset = $matches[0][$last_match][1];
170
+                $match_length = strlen($matches[0][$last_match][0]);
171
+            } else {
172
+                $counter = 2;
173
+                $match_length = 0;
174
+                $offset = false;
175
+            }
176
+            do {
177
+                if ($offset) {
178
+                    //Replace the last "(number)" with "(number+1)"
179
+                    $newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
180
+                } else {
181
+                    $newname = $name . ' (' . $counter . ')';
182
+                }
183
+                $newpath = $path . '/' . $newname . $ext;
184
+                $counter++;
185
+            } while ($view->file_exists($newpath));
186
+        }
187
+
188
+        return $newpath;
189
+    }
190
+
191
+    /**
192
+     * Checks if a function is available
193
+     *
194
+     * @deprecated 25.0.0 use \OCP\Util::isFunctionEnabled instead
195
+     */
196
+    public static function is_function_enabled(string $function_name): bool {
197
+        return Util::isFunctionEnabled($function_name);
198
+    }
199
+
200
+    /**
201
+     * Try to find a program
202
+     * @deprecated 25.0.0 Use \OCP\IBinaryFinder directly
203
+     */
204
+    public static function findBinaryPath(string $program): ?string {
205
+        $result = Server::get(IBinaryFinder::class)->findBinaryPath($program);
206
+        return $result !== false ? $result : null;
207
+    }
208
+
209
+    /**
210
+     * Calculate the disc space for the given path
211
+     *
212
+     * BEWARE: this requires that Util::setupFS() was called
213
+     * already !
214
+     *
215
+     * @param string $path
216
+     * @param \OCP\Files\FileInfo $rootInfo (optional)
217
+     * @param bool $includeMountPoints whether to include mount points in the size calculation
218
+     * @param bool $useCache whether to use the cached quota values
219
+     * @psalm-suppress LessSpecificReturnStatement Legacy code outputs weird types - manually validated that they are correct
220
+     * @return StorageInfo
221
+     * @throws \OCP\Files\NotFoundException
222
+     */
223
+    public static function getStorageInfo($path, $rootInfo = null, $includeMountPoints = true, $useCache = true) {
224
+        if (!self::$cacheFactory) {
225
+            self::$cacheFactory = Server::get(ICacheFactory::class);
226
+        }
227
+        $memcache = self::$cacheFactory->createLocal('storage_info');
228
+
229
+        // return storage info without adding mount points
230
+        if (self::$quotaIncludeExternalStorage === null) {
231
+            self::$quotaIncludeExternalStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
232
+        }
233
+
234
+        $view = Filesystem::getView();
235
+        if (!$view) {
236
+            throw new \OCP\Files\NotFoundException();
237
+        }
238
+        $fullPath = Filesystem::normalizePath($view->getAbsolutePath($path));
239
+
240
+        $cacheKey = $fullPath . '::' . ($includeMountPoints ? 'include' : 'exclude');
241
+        if ($useCache) {
242
+            $cached = $memcache->get($cacheKey);
243
+            if ($cached) {
244
+                return $cached;
245
+            }
246
+        }
247
+
248
+        if (!$rootInfo) {
249
+            $rootInfo = \OC\Files\Filesystem::getFileInfo($path, self::$quotaIncludeExternalStorage ? 'ext' : false);
250
+        }
251
+        if (!$rootInfo instanceof \OCP\Files\FileInfo) {
252
+            throw new \OCP\Files\NotFoundException('The root directory of the user\'s files is missing');
253
+        }
254
+        $used = $rootInfo->getSize($includeMountPoints);
255
+        if ($used < 0) {
256
+            $used = 0.0;
257
+        }
258
+        /** @var int|float $quota */
259
+        $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
260
+        $mount = $rootInfo->getMountPoint();
261
+        $storage = $mount->getStorage();
262
+        $sourceStorage = $storage;
263
+        if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
264
+            self::$quotaIncludeExternalStorage = false;
265
+        }
266
+        if (self::$quotaIncludeExternalStorage) {
267
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
268
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
269
+            ) {
270
+                /** @var \OC\Files\Storage\Home $storage */
271
+                $user = $storage->getUser();
272
+            } else {
273
+                $user = \OC::$server->getUserSession()->getUser();
274
+            }
275
+            $quota = OC_Util::getUserQuota($user);
276
+            if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
277
+                // always get free space / total space from root + mount points
278
+                return self::getGlobalStorageInfo($quota, $user, $mount);
279
+            }
280
+        }
281
+
282
+        // TODO: need a better way to get total space from storage
283
+        if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
284
+            /** @var \OC\Files\Storage\Wrapper\Quota $storage */
285
+            $quota = $sourceStorage->getQuota();
286
+        }
287
+        try {
288
+            $free = $sourceStorage->free_space($rootInfo->getInternalPath());
289
+            if (is_bool($free)) {
290
+                $free = 0.0;
291
+            }
292
+        } catch (\Exception $e) {
293
+            if ($path === '') {
294
+                throw $e;
295
+            }
296
+            /** @var LoggerInterface $logger */
297
+            $logger = \OC::$server->get(LoggerInterface::class);
298
+            $logger->warning('Error while getting quota info, using root quota', ['exception' => $e]);
299
+            $rootInfo = self::getStorageInfo('');
300
+            $memcache->set($cacheKey, $rootInfo, 5 * 60);
301
+            return $rootInfo;
302
+        }
303
+        if ($free >= 0) {
304
+            $total = $free + $used;
305
+        } else {
306
+            $total = $free; //either unknown or unlimited
307
+        }
308
+        if ($total > 0) {
309
+            if ($quota > 0 && $total > $quota) {
310
+                $total = $quota;
311
+            }
312
+            // prevent division by zero or error codes (negative values)
313
+            $relative = round(($used / $total) * 10000) / 100;
314
+        } else {
315
+            $relative = 0;
316
+        }
317
+
318
+        /*
319 319
 		 * \OCA\Files_Sharing\External\Storage returns the cloud ID as the owner for the storage.
320 320
 		 * It is unnecessary to query the user manager for the display name, as it won't have this information.
321 321
 		 */
322
-		$isRemoteShare = $storage->instanceOfStorage(\OCA\Files_Sharing\External\Storage::class);
323
-
324
-		$ownerId = $storage->getOwner($path);
325
-		$ownerDisplayName = '';
326
-
327
-		if ($isRemoteShare === false && $ownerId !== false) {
328
-			$ownerDisplayName = \OC::$server->getUserManager()->getDisplayName($ownerId) ?? '';
329
-		}
330
-
331
-		if (substr_count($mount->getMountPoint(), '/') < 3) {
332
-			$mountPoint = '';
333
-		} else {
334
-			[,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
335
-		}
336
-
337
-		$info = [
338
-			'free' => $free,
339
-			'used' => $used,
340
-			'quota' => $quota,
341
-			'total' => $total,
342
-			'relative' => $relative,
343
-			'owner' => $ownerId,
344
-			'ownerDisplayName' => $ownerDisplayName,
345
-			'mountType' => $mount->getMountType(),
346
-			'mountPoint' => trim($mountPoint, '/'),
347
-		];
348
-
349
-		if ($isRemoteShare === false && $ownerId !== false && $path === '/') {
350
-			// If path is root, store this as last known quota usage for this user
351
-			\OCP\Server::get(\OCP\IConfig::class)->setUserValue($ownerId, 'files', 'lastSeenQuotaUsage', (string)$relative);
352
-		}
353
-
354
-		$memcache->set($cacheKey, $info, 5 * 60);
355
-
356
-		return $info;
357
-	}
358
-
359
-	/**
360
-	 * Get storage info including all mount points and quota
361
-	 *
362
-	 * @psalm-suppress LessSpecificReturnStatement Legacy code outputs weird types - manually validated that they are correct
363
-	 * @return StorageInfo
364
-	 */
365
-	private static function getGlobalStorageInfo(int|float $quota, IUser $user, IMountPoint $mount): array {
366
-		$rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
367
-		/** @var int|float $used */
368
-		$used = $rootInfo['size'];
369
-		if ($used < 0) {
370
-			$used = 0.0;
371
-		}
372
-
373
-		$total = $quota;
374
-		/** @var int|float $free */
375
-		$free = $quota - $used;
376
-
377
-		if ($total > 0) {
378
-			if ($quota > 0 && $total > $quota) {
379
-				$total = $quota;
380
-			}
381
-			// prevent division by zero or error codes (negative values)
382
-			$relative = round(($used / $total) * 10000) / 100;
383
-		} else {
384
-			$relative = 0.0;
385
-		}
386
-
387
-		if (substr_count($mount->getMountPoint(), '/') < 3) {
388
-			$mountPoint = '';
389
-		} else {
390
-			[,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
391
-		}
392
-
393
-		return [
394
-			'free' => $free,
395
-			'used' => $used,
396
-			'total' => $total,
397
-			'relative' => $relative,
398
-			'quota' => $quota,
399
-			'owner' => $user->getUID(),
400
-			'ownerDisplayName' => $user->getDisplayName(),
401
-			'mountType' => $mount->getMountType(),
402
-			'mountPoint' => trim($mountPoint, '/'),
403
-		];
404
-	}
405
-
406
-	public static function clearStorageInfo(string $absolutePath): void {
407
-		/** @var ICacheFactory $cacheFactory */
408
-		$cacheFactory = \OC::$server->get(ICacheFactory::class);
409
-		$memcache = $cacheFactory->createLocal('storage_info');
410
-		$cacheKeyPrefix = Filesystem::normalizePath($absolutePath) . '::';
411
-		$memcache->remove($cacheKeyPrefix . 'include');
412
-		$memcache->remove($cacheKeyPrefix . 'exclude');
413
-	}
414
-
415
-	/**
416
-	 * Returns whether the config file is set manually to read-only
417
-	 * @return bool
418
-	 * @deprecated 32.0.0 use the `config_is_read_only` system config directly
419
-	 */
420
-	public static function isReadOnlyConfigEnabled() {
421
-		return \OC::$server->getConfig()->getSystemValueBool('config_is_read_only', false);
422
-	}
322
+        $isRemoteShare = $storage->instanceOfStorage(\OCA\Files_Sharing\External\Storage::class);
323
+
324
+        $ownerId = $storage->getOwner($path);
325
+        $ownerDisplayName = '';
326
+
327
+        if ($isRemoteShare === false && $ownerId !== false) {
328
+            $ownerDisplayName = \OC::$server->getUserManager()->getDisplayName($ownerId) ?? '';
329
+        }
330
+
331
+        if (substr_count($mount->getMountPoint(), '/') < 3) {
332
+            $mountPoint = '';
333
+        } else {
334
+            [,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
335
+        }
336
+
337
+        $info = [
338
+            'free' => $free,
339
+            'used' => $used,
340
+            'quota' => $quota,
341
+            'total' => $total,
342
+            'relative' => $relative,
343
+            'owner' => $ownerId,
344
+            'ownerDisplayName' => $ownerDisplayName,
345
+            'mountType' => $mount->getMountType(),
346
+            'mountPoint' => trim($mountPoint, '/'),
347
+        ];
348
+
349
+        if ($isRemoteShare === false && $ownerId !== false && $path === '/') {
350
+            // If path is root, store this as last known quota usage for this user
351
+            \OCP\Server::get(\OCP\IConfig::class)->setUserValue($ownerId, 'files', 'lastSeenQuotaUsage', (string)$relative);
352
+        }
353
+
354
+        $memcache->set($cacheKey, $info, 5 * 60);
355
+
356
+        return $info;
357
+    }
358
+
359
+    /**
360
+     * Get storage info including all mount points and quota
361
+     *
362
+     * @psalm-suppress LessSpecificReturnStatement Legacy code outputs weird types - manually validated that they are correct
363
+     * @return StorageInfo
364
+     */
365
+    private static function getGlobalStorageInfo(int|float $quota, IUser $user, IMountPoint $mount): array {
366
+        $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
367
+        /** @var int|float $used */
368
+        $used = $rootInfo['size'];
369
+        if ($used < 0) {
370
+            $used = 0.0;
371
+        }
372
+
373
+        $total = $quota;
374
+        /** @var int|float $free */
375
+        $free = $quota - $used;
376
+
377
+        if ($total > 0) {
378
+            if ($quota > 0 && $total > $quota) {
379
+                $total = $quota;
380
+            }
381
+            // prevent division by zero or error codes (negative values)
382
+            $relative = round(($used / $total) * 10000) / 100;
383
+        } else {
384
+            $relative = 0.0;
385
+        }
386
+
387
+        if (substr_count($mount->getMountPoint(), '/') < 3) {
388
+            $mountPoint = '';
389
+        } else {
390
+            [,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
391
+        }
392
+
393
+        return [
394
+            'free' => $free,
395
+            'used' => $used,
396
+            'total' => $total,
397
+            'relative' => $relative,
398
+            'quota' => $quota,
399
+            'owner' => $user->getUID(),
400
+            'ownerDisplayName' => $user->getDisplayName(),
401
+            'mountType' => $mount->getMountType(),
402
+            'mountPoint' => trim($mountPoint, '/'),
403
+        ];
404
+    }
405
+
406
+    public static function clearStorageInfo(string $absolutePath): void {
407
+        /** @var ICacheFactory $cacheFactory */
408
+        $cacheFactory = \OC::$server->get(ICacheFactory::class);
409
+        $memcache = $cacheFactory->createLocal('storage_info');
410
+        $cacheKeyPrefix = Filesystem::normalizePath($absolutePath) . '::';
411
+        $memcache->remove($cacheKeyPrefix . 'include');
412
+        $memcache->remove($cacheKeyPrefix . 'exclude');
413
+    }
414
+
415
+    /**
416
+     * Returns whether the config file is set manually to read-only
417
+     * @return bool
418
+     * @deprecated 32.0.0 use the `config_is_read_only` system config directly
419
+     */
420
+    public static function isReadOnlyConfigEnabled() {
421
+        return \OC::$server->getConfig()->getSystemValueBool('config_is_read_only', false);
422
+    }
423 423
 }
Please login to merge, or discard this patch.
lib/private/legacy/OC_Util.php 2 patches
Indentation   +836 added lines, -836 removed lines patch added patch discarded remove patch
@@ -22,840 +22,840 @@
 block discarded – undo
22 22
  * @deprecated 32.0.0 Use \OCP\Util or any appropriate official API instead
23 23
  */
24 24
 class OC_Util {
25
-	public static $styles = [];
26
-	public static $headers = [];
27
-
28
-	/**
29
-	 * Setup the file system
30
-	 *
31
-	 * @param string|null $user
32
-	 * @return boolean
33
-	 * @description configure the initial filesystem based on the configuration
34
-	 * @suppress PhanDeprecatedFunction
35
-	 * @suppress PhanAccessMethodInternal
36
-	 */
37
-	public static function setupFS(?string $user = '') {
38
-		// If we are not forced to load a specific user we load the one that is logged in
39
-		if ($user === '') {
40
-			$userObject = \OC::$server->get(\OCP\IUserSession::class)->getUser();
41
-		} else {
42
-			$userObject = \OC::$server->get(\OCP\IUserManager::class)->get($user);
43
-		}
44
-
45
-		/** @var SetupManager $setupManager */
46
-		$setupManager = \OC::$server->get(SetupManager::class);
47
-
48
-		if ($userObject) {
49
-			$setupManager->setupForUser($userObject);
50
-		} else {
51
-			$setupManager->setupRoot();
52
-		}
53
-		return true;
54
-	}
55
-
56
-	/**
57
-	 * Check if a password is required for each public link
58
-	 *
59
-	 * @param bool $checkGroupMembership Check group membership exclusion
60
-	 * @return bool
61
-	 * @deprecated 32.0.0 use OCP\Share\IManager's shareApiLinkEnforcePassword directly
62
-	 */
63
-	public static function isPublicLinkPasswordRequired(bool $checkGroupMembership = true) {
64
-		/** @var IManager $shareManager */
65
-		$shareManager = \OC::$server->get(IManager::class);
66
-		return $shareManager->shareApiLinkEnforcePassword($checkGroupMembership);
67
-	}
68
-
69
-	/**
70
-	 * check if sharing is disabled for the current user
71
-	 * @param IConfig $config
72
-	 * @param IGroupManager $groupManager
73
-	 * @param IUser|null $user
74
-	 * @return bool
75
-	 * @deprecated 32.0.0 use OCP\Share\IManager's sharingDisabledForUser directly
76
-	 */
77
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
78
-		/** @var IManager $shareManager */
79
-		$shareManager = \OC::$server->get(IManager::class);
80
-		$userId = $user ? $user->getUID() : null;
81
-		return $shareManager->sharingDisabledForUser($userId);
82
-	}
83
-
84
-	/**
85
-	 * check if share API enforces a default expire date
86
-	 *
87
-	 * @return bool
88
-	 * @deprecated 32.0.0 use OCP\Share\IManager's shareApiLinkDefaultExpireDateEnforced directly
89
-	 */
90
-	public static function isDefaultExpireDateEnforced() {
91
-		/** @var IManager $shareManager */
92
-		$shareManager = \OC::$server->get(IManager::class);
93
-		return $shareManager->shareApiLinkDefaultExpireDateEnforced();
94
-	}
95
-
96
-	/**
97
-	 * Get the quota of a user
98
-	 *
99
-	 * @param IUser|null $user
100
-	 * @return int|\OCP\Files\FileInfo::SPACE_UNLIMITED|false|float Quota bytes
101
-	 * @deprecated 9.0.0 - Use \OCP\IUser::getQuota
102
-	 */
103
-	public static function getUserQuota(?IUser $user) {
104
-		if (is_null($user)) {
105
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
106
-		}
107
-		$userQuota = $user->getQuota();
108
-		if ($userQuota === 'none') {
109
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
110
-		}
111
-		return \OCP\Util::computerFileSize($userQuota);
112
-	}
113
-
114
-	/**
115
-	 * copies the skeleton to the users /files
116
-	 *
117
-	 * @param string $userId
118
-	 * @param \OCP\Files\Folder $userDirectory
119
-	 * @throws \OCP\Files\NotFoundException
120
-	 * @throws \OCP\Files\NotPermittedException
121
-	 * @suppress PhanDeprecatedFunction
122
-	 */
123
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
124
-		/** @var LoggerInterface $logger */
125
-		$logger = \OC::$server->get(LoggerInterface::class);
126
-
127
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValueString('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
128
-		$userLang = \OC::$server->get(IFactory::class)->findLanguage();
129
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
130
-
131
-		if (!file_exists($skeletonDirectory)) {
132
-			$dialectStart = strpos($userLang, '_');
133
-			if ($dialectStart !== false) {
134
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
135
-			}
136
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
137
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
138
-			}
139
-			if (!file_exists($skeletonDirectory)) {
140
-				$skeletonDirectory = '';
141
-			}
142
-		}
143
-
144
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
145
-
146
-		if ($instanceId === null) {
147
-			throw new \RuntimeException('no instance id!');
148
-		}
149
-		$appdata = 'appdata_' . $instanceId;
150
-		if ($userId === $appdata) {
151
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
152
-		}
153
-
154
-		if (!empty($skeletonDirectory)) {
155
-			$logger->debug('copying skeleton for ' . $userId . ' from ' . $skeletonDirectory . ' to ' . $userDirectory->getFullPath('/'), ['app' => 'files_skeleton']);
156
-			self::copyr($skeletonDirectory, $userDirectory);
157
-			// update the file cache
158
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
159
-
160
-			/** @var ITemplateManager $templateManager */
161
-			$templateManager = \OC::$server->get(ITemplateManager::class);
162
-			$templateManager->initializeTemplateDirectory(null, $userId);
163
-		}
164
-	}
165
-
166
-	/**
167
-	 * copies a directory recursively by using streams
168
-	 *
169
-	 * @param string $source
170
-	 * @param \OCP\Files\Folder $target
171
-	 * @return void
172
-	 */
173
-	public static function copyr($source, \OCP\Files\Folder $target) {
174
-		$logger = \OCP\Server::get(LoggerInterface::class);
175
-
176
-		// Verify if folder exists
177
-		$dir = opendir($source);
178
-		if ($dir === false) {
179
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
180
-			return;
181
-		}
182
-
183
-		// Copy the files
184
-		while (false !== ($file = readdir($dir))) {
185
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
186
-				if (is_dir($source . '/' . $file)) {
187
-					$child = $target->newFolder($file);
188
-					self::copyr($source . '/' . $file, $child);
189
-				} else {
190
-					$child = $target->newFile($file);
191
-					$sourceStream = fopen($source . '/' . $file, 'r');
192
-					if ($sourceStream === false) {
193
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
194
-						closedir($dir);
195
-						return;
196
-					}
197
-					$child->putContent($sourceStream);
198
-				}
199
-			}
200
-		}
201
-		closedir($dir);
202
-	}
203
-
204
-	/**
205
-	 * @deprecated 32.0.0 Call tearDown directly on SetupManager
206
-	 */
207
-	public static function tearDownFS(): void {
208
-		$setupManager = \OCP\Server::get(SetupManager::class);
209
-		$setupManager->tearDown();
210
-	}
211
-
212
-	/**
213
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
214
-	 *
215
-	 * @param string $application application to get the files from
216
-	 * @param string $directory directory within this application (css, js, vendor, etc)
217
-	 * @param ?string $file the file inside of the above folder
218
-	 */
219
-	private static function generatePath($application, $directory, $file): string {
220
-		if (is_null($file)) {
221
-			$file = $application;
222
-			$application = '';
223
-		}
224
-		if (!empty($application)) {
225
-			return "$application/$directory/$file";
226
-		} else {
227
-			return "$directory/$file";
228
-		}
229
-	}
230
-
231
-	/**
232
-	 * add a css file
233
-	 *
234
-	 * @param string $application application id
235
-	 * @param string|null $file filename
236
-	 * @param bool $prepend prepend the Style to the beginning of the list
237
-	 * @deprecated 32.0.0 Use \OCP\Util::addStyle
238
-	 */
239
-	public static function addStyle($application, $file = null, $prepend = false): void {
240
-		$path = OC_Util::generatePath($application, 'css', $file);
241
-		self::addExternalResource($application, $prepend, $path, 'style');
242
-	}
243
-
244
-	/**
245
-	 * add a css file from the vendor sub folder
246
-	 *
247
-	 * @param string $application application id
248
-	 * @param string|null $file filename
249
-	 * @param bool $prepend prepend the Style to the beginning of the list
250
-	 * @deprecated 32.0.0
251
-	 */
252
-	public static function addVendorStyle($application, $file = null, $prepend = false): void {
253
-		$path = OC_Util::generatePath($application, 'vendor', $file);
254
-		self::addExternalResource($application, $prepend, $path, 'style');
255
-	}
256
-
257
-	/**
258
-	 * add an external resource css/js file
259
-	 *
260
-	 * @param string $application application id
261
-	 * @param bool $prepend prepend the file to the beginning of the list
262
-	 * @param string $path
263
-	 * @param string $type (script or style)
264
-	 */
265
-	private static function addExternalResource($application, $prepend, $path, $type = 'script'): void {
266
-		if ($type === 'style') {
267
-			if (!in_array($path, self::$styles)) {
268
-				if ($prepend === true) {
269
-					array_unshift(self::$styles, $path);
270
-				} else {
271
-					self::$styles[] = $path;
272
-				}
273
-			}
274
-		}
275
-	}
276
-
277
-	/**
278
-	 * Add a custom element to the header
279
-	 * If $text is null then the element will be written as empty element.
280
-	 * So use "" to get a closing tag.
281
-	 * @param string $tag tag name of the element
282
-	 * @param array $attributes array of attributes for the element
283
-	 * @param string $text the text content for the element
284
-	 * @param bool $prepend prepend the header to the beginning of the list
285
-	 * @deprecated 32.0.0 Use \OCP\Util::addHeader instead
286
-	 */
287
-	public static function addHeader($tag, $attributes, $text = null, $prepend = false): void {
288
-		$header = [
289
-			'tag' => $tag,
290
-			'attributes' => $attributes,
291
-			'text' => $text
292
-		];
293
-		if ($prepend === true) {
294
-			array_unshift(self::$headers, $header);
295
-		} else {
296
-			self::$headers[] = $header;
297
-		}
298
-	}
299
-
300
-	/**
301
-	 * check if the current server configuration is suitable for ownCloud
302
-	 *
303
-	 * @return array arrays with error messages and hints
304
-	 */
305
-	public static function checkServer(\OC\SystemConfig $config) {
306
-		$l = \OC::$server->getL10N('lib');
307
-		$errors = [];
308
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
309
-
310
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
311
-			// this check needs to be done every time
312
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
313
-		}
314
-
315
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
316
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
317
-			return $errors;
318
-		}
319
-
320
-		$webServerRestart = false;
321
-		$setup = \OCP\Server::get(\OC\Setup::class);
322
-
323
-		$urlGenerator = \OC::$server->getURLGenerator();
324
-
325
-		$availableDatabases = $setup->getSupportedDatabases();
326
-		if (empty($availableDatabases)) {
327
-			$errors[] = [
328
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
329
-				'hint' => '' //TODO: sane hint
330
-			];
331
-			$webServerRestart = true;
332
-		}
333
-
334
-		// Check if config folder is writable.
335
-		if (!(bool)$config->getValue('config_is_read_only', false)) {
336
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
337
-				$errors[] = [
338
-					'error' => $l->t('Cannot write into "config" directory.'),
339
-					'hint' => $l->t('This can usually be fixed by giving the web server write access to the config directory. See %s',
340
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
341
-						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
342
-							[ $urlGenerator->linkToDocs('admin-config') ])
343
-				];
344
-			}
345
-		}
346
-
347
-		// Check if there is a writable install folder.
348
-		if ($config->getValue('appstoreenabled', true)) {
349
-			if (OC_App::getInstallPath() === null
350
-				|| !is_writable(OC_App::getInstallPath())
351
-				|| !is_readable(OC_App::getInstallPath())
352
-			) {
353
-				$errors[] = [
354
-					'error' => $l->t('Cannot write into "apps" directory.'),
355
-					'hint' => $l->t('This can usually be fixed by giving the web server write access to the apps directory'
356
-						. ' or disabling the App Store in the config file.')
357
-				];
358
-			}
359
-		}
360
-		// Create root dir.
361
-		if ($config->getValue('installed', false)) {
362
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
363
-				$success = @mkdir($CONFIG_DATADIRECTORY);
364
-				if ($success) {
365
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
366
-				} else {
367
-					$errors[] = [
368
-						'error' => $l->t('Cannot create "data" directory.'),
369
-						'hint' => $l->t('This can usually be fixed by giving the web server write access to the root directory. See %s',
370
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
371
-					];
372
-				}
373
-			} elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
374
-				// is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
375
-				$testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
376
-				$handle = fopen($testFile, 'w');
377
-				if (!$handle || fwrite($handle, 'Test write operation') === false) {
378
-					$permissionsHint = $l->t('Permissions can usually be fixed by giving the web server write access to the root directory. See %s.',
379
-						[$urlGenerator->linkToDocs('admin-dir_permissions')]);
380
-					$errors[] = [
381
-						'error' => $l->t('Your data directory is not writable.'),
382
-						'hint' => $permissionsHint
383
-					];
384
-				} else {
385
-					fclose($handle);
386
-					unlink($testFile);
387
-				}
388
-			} else {
389
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
390
-			}
391
-		}
392
-
393
-		if (!OC_Util::isSetLocaleWorking()) {
394
-			$errors[] = [
395
-				'error' => $l->t('Setting locale to %s failed.',
396
-					['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
397
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
398
-				'hint' => $l->t('Please install one of these locales on your system and restart your web server.')
399
-			];
400
-		}
401
-
402
-		// Contains the dependencies that should be checked against
403
-		// classes = class_exists
404
-		// functions = function_exists
405
-		// defined = defined
406
-		// ini = ini_get
407
-		// If the dependency is not found the missing module name is shown to the EndUser
408
-		// When adding new checks always verify that they pass on CI as well
409
-		$dependencies = [
410
-			'classes' => [
411
-				'ZipArchive' => 'zip',
412
-				'DOMDocument' => 'dom',
413
-				'XMLWriter' => 'XMLWriter',
414
-				'XMLReader' => 'XMLReader',
415
-			],
416
-			'functions' => [
417
-				'xml_parser_create' => 'libxml',
418
-				'mb_strcut' => 'mbstring',
419
-				'ctype_digit' => 'ctype',
420
-				'json_encode' => 'JSON',
421
-				'gd_info' => 'GD',
422
-				'gzencode' => 'zlib',
423
-				'simplexml_load_string' => 'SimpleXML',
424
-				'hash' => 'HASH Message Digest Framework',
425
-				'curl_init' => 'cURL',
426
-				'openssl_verify' => 'OpenSSL',
427
-			],
428
-			'defined' => [
429
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
430
-			],
431
-			'ini' => [
432
-				'default_charset' => 'UTF-8',
433
-			],
434
-		];
435
-		$missingDependencies = [];
436
-		$invalidIniSettings = [];
437
-
438
-		$iniWrapper = \OC::$server->get(IniGetWrapper::class);
439
-		foreach ($dependencies['classes'] as $class => $module) {
440
-			if (!class_exists($class)) {
441
-				$missingDependencies[] = $module;
442
-			}
443
-		}
444
-		foreach ($dependencies['functions'] as $function => $module) {
445
-			if (!function_exists($function)) {
446
-				$missingDependencies[] = $module;
447
-			}
448
-		}
449
-		foreach ($dependencies['defined'] as $defined => $module) {
450
-			if (!defined($defined)) {
451
-				$missingDependencies[] = $module;
452
-			}
453
-		}
454
-		foreach ($dependencies['ini'] as $setting => $expected) {
455
-			if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
456
-				$invalidIniSettings[] = [$setting, $expected];
457
-			}
458
-		}
459
-
460
-		foreach ($missingDependencies as $missingDependency) {
461
-			$errors[] = [
462
-				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
463
-				'hint' => $l->t('Please ask your server administrator to install the module.'),
464
-			];
465
-			$webServerRestart = true;
466
-		}
467
-		foreach ($invalidIniSettings as $setting) {
468
-			$errors[] = [
469
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
470
-				'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
471
-			];
472
-			$webServerRestart = true;
473
-		}
474
-
475
-		/**
476
-		 * The mbstring.func_overload check can only be performed if the mbstring
477
-		 * module is installed as it will return null if the checking setting is
478
-		 * not available and thus a check on the boolean value fails.
479
-		 *
480
-		 * TODO: Should probably be implemented in the above generic dependency
481
-		 *       check somehow in the long-term.
482
-		 */
483
-		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
484
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
485
-			$errors[] = [
486
-				'error' => $l->t('<code>mbstring.func_overload</code> is set to <code>%s</code> instead of the expected value <code>0</code>.', [$iniWrapper->getString('mbstring.func_overload')]),
487
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini.')
488
-			];
489
-		}
490
-
491
-		if (!self::isAnnotationsWorking()) {
492
-			$errors[] = [
493
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
494
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
495
-			];
496
-		}
497
-
498
-		if (!\OC::$CLI && $webServerRestart) {
499
-			$errors[] = [
500
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
501
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
502
-			];
503
-		}
504
-
505
-		foreach (['secret', 'instanceid', 'passwordsalt'] as $requiredConfig) {
506
-			if ($config->getValue($requiredConfig, '') === '' && !\OC::$CLI && $config->getValue('installed', false)) {
507
-				$errors[] = [
508
-					'error' => $l->t('The required %s config variable is not configured in the config.php file.', [$requiredConfig]),
509
-					'hint' => $l->t('Please ask your server administrator to check the Nextcloud configuration.')
510
-				];
511
-			}
512
-		}
513
-
514
-		// Cache the result of this function
515
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
516
-
517
-		return $errors;
518
-	}
519
-
520
-	/**
521
-	 * Check for correct file permissions of data directory
522
-	 *
523
-	 * @param string $dataDirectory
524
-	 * @return array arrays with error messages and hints
525
-	 * @internal
526
-	 */
527
-	public static function checkDataDirectoryPermissions($dataDirectory) {
528
-		if (!\OC::$server->getConfig()->getSystemValueBool('check_data_directory_permissions', true)) {
529
-			return  [];
530
-		}
531
-
532
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
533
-		if (substr($perms, -1) !== '0') {
534
-			chmod($dataDirectory, 0770);
535
-			clearstatcache();
536
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
537
-			if ($perms[2] !== '0') {
538
-				$l = \OC::$server->getL10N('lib');
539
-				return [[
540
-					'error' => $l->t('Your data directory is readable by other people.'),
541
-					'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other people.'),
542
-				]];
543
-			}
544
-		}
545
-		return [];
546
-	}
547
-
548
-	/**
549
-	 * Check that the data directory exists and is valid by
550
-	 * checking the existence of the ".ncdata" file.
551
-	 *
552
-	 * @param string $dataDirectory data directory path
553
-	 * @return array errors found
554
-	 * @internal
555
-	 */
556
-	public static function checkDataDirectoryValidity($dataDirectory) {
557
-		$l = \OC::$server->getL10N('lib');
558
-		$errors = [];
559
-		if ($dataDirectory[0] !== '/') {
560
-			$errors[] = [
561
-				'error' => $l->t('Your data directory must be an absolute path.'),
562
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration.')
563
-			];
564
-		}
565
-
566
-		if (!file_exists($dataDirectory . '/.ncdata')) {
567
-			$errors[] = [
568
-				'error' => $l->t('Your data directory is invalid.'),
569
-				'hint' => $l->t('Ensure there is a file called "%1$s" in the root of the data directory. It should have the content: "%2$s"', ['.ncdata', '# Nextcloud data directory']),
570
-			];
571
-		}
572
-		return $errors;
573
-	}
574
-
575
-	/**
576
-	 * Check if the user is logged in, redirects to home if not. With
577
-	 * redirect URL parameter to the request URI.
578
-	 *
579
-	 * @deprecated 32.0.0
580
-	 */
581
-	public static function checkLoggedIn(): void {
582
-		// Check if we are a user
583
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
584
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
585
-				'core.login.showLoginForm',
586
-				[
587
-					'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
588
-				]
589
-			)
590
-			);
591
-			exit();
592
-		}
593
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
594
-		if (\OC::$server->get(TwoFactorAuthManager::class)->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
595
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
596
-			exit();
597
-		}
598
-	}
599
-
600
-	/**
601
-	 * Check if the user is a admin, redirects to home if not
602
-	 *
603
-	 * @deprecated 32.0.0
604
-	 */
605
-	public static function checkAdminUser(): void {
606
-		self::checkLoggedIn();
607
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
608
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
609
-			exit();
610
-		}
611
-	}
612
-
613
-	/**
614
-	 * Returns the URL of the default page
615
-	 * based on the system configuration and
616
-	 * the apps visible for the current user
617
-	 *
618
-	 * @return string URL
619
-	 * @deprecated 32.0.0 use IURLGenerator's linkToDefaultPageUrl directly
620
-	 */
621
-	public static function getDefaultPageUrl() {
622
-		/** @var IURLGenerator $urlGenerator */
623
-		$urlGenerator = \OC::$server->get(IURLGenerator::class);
624
-		return $urlGenerator->linkToDefaultPageUrl();
625
-	}
626
-
627
-	/**
628
-	 * Redirect to the user default page
629
-	 *
630
-	 * @deprecated 32.0.0
631
-	 */
632
-	public static function redirectToDefaultPage(): void {
633
-		$location = self::getDefaultPageUrl();
634
-		header('Location: ' . $location);
635
-		exit();
636
-	}
637
-
638
-	/**
639
-	 * get an id unique for this instance
640
-	 *
641
-	 * @return string
642
-	 */
643
-	public static function getInstanceId(): string {
644
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
645
-		if (is_null($id)) {
646
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
647
-			$id = 'oc' . \OC::$server->get(ISecureRandom::class)->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
648
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
649
-		}
650
-		return $id;
651
-	}
652
-
653
-	/**
654
-	 * Public function to sanitize HTML
655
-	 *
656
-	 * This function is used to sanitize HTML and should be applied on any
657
-	 * string or array of strings before displaying it on a web page.
658
-	 *
659
-	 * @param string|string[] $value
660
-	 * @return ($value is array ? string[] : string)
661
-	 * @deprecated 32.0.0 use \OCP\Util::sanitizeHTML instead
662
-	 */
663
-	public static function sanitizeHTML($value) {
664
-		if (is_array($value)) {
665
-			$value = array_map(function ($value) {
666
-				return self::sanitizeHTML($value);
667
-			}, $value);
668
-		} else {
669
-			// Specify encoding for PHP<5.4
670
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
671
-		}
672
-		return $value;
673
-	}
674
-
675
-	/**
676
-	 * Public function to encode url parameters
677
-	 *
678
-	 * This function is used to encode path to file before output.
679
-	 * Encoding is done according to RFC 3986 with one exception:
680
-	 * Character '/' is preserved as is.
681
-	 *
682
-	 * @param string $component part of URI to encode
683
-	 * @return string
684
-	 * @deprecated 32.0.0 use \OCP\Util::encodePath instead
685
-	 */
686
-	public static function encodePath($component) {
687
-		$encoded = rawurlencode($component);
688
-		$encoded = str_replace('%2F', '/', $encoded);
689
-		return $encoded;
690
-	}
691
-
692
-	/**
693
-	 * Check if current locale is non-UTF8
694
-	 *
695
-	 * @return bool
696
-	 */
697
-	private static function isNonUTF8Locale() {
698
-		if (function_exists('escapeshellcmd')) {
699
-			return escapeshellcmd('§') === '';
700
-		} elseif (function_exists('escapeshellarg')) {
701
-			return escapeshellarg('§') === '\'\'';
702
-		} else {
703
-			return preg_match('/utf-?8/i', setlocale(LC_CTYPE, 0)) === 0;
704
-		}
705
-	}
706
-
707
-	/**
708
-	 * Check if the setlocale call does not work. This can happen if the right
709
-	 * local packages are not available on the server.
710
-	 *
711
-	 * @internal
712
-	 */
713
-	public static function isSetLocaleWorking(): bool {
714
-		if (self::isNonUTF8Locale()) {
715
-			// Borrowed from \Patchwork\Utf8\Bootup::initLocale
716
-			setlocale(LC_ALL, 'C.UTF-8', 'C');
717
-			setlocale(LC_CTYPE, 'en_US.UTF-8', 'fr_FR.UTF-8', 'es_ES.UTF-8', 'de_DE.UTF-8', 'ru_RU.UTF-8', 'pt_BR.UTF-8', 'it_IT.UTF-8', 'ja_JP.UTF-8', 'zh_CN.UTF-8', '0');
718
-
719
-			// Check again
720
-			if (self::isNonUTF8Locale()) {
721
-				return false;
722
-			}
723
-		}
724
-
725
-		return true;
726
-	}
727
-
728
-	/**
729
-	 * Check if it's possible to get the inline annotations
730
-	 *
731
-	 * @internal
732
-	 */
733
-	public static function isAnnotationsWorking(): bool {
734
-		if (PHP_VERSION_ID >= 80300) {
735
-			/** @psalm-suppress UndefinedMethod */
736
-			$reflection = \ReflectionMethod::createFromMethodName(__METHOD__);
737
-		} else {
738
-			$reflection = new \ReflectionMethod(__METHOD__);
739
-		}
740
-		$docs = $reflection->getDocComment();
741
-
742
-		return (is_string($docs) && strlen($docs) > 50);
743
-	}
744
-
745
-	/**
746
-	 * Check if the PHP module fileinfo is loaded.
747
-	 *
748
-	 * @internal
749
-	 */
750
-	public static function fileInfoLoaded(): bool {
751
-		return function_exists('finfo_open');
752
-	}
753
-
754
-	/**
755
-	 * clear all levels of output buffering
756
-	 *
757
-	 * @return void
758
-	 */
759
-	public static function obEnd() {
760
-		while (ob_get_level()) {
761
-			ob_end_clean();
762
-		}
763
-	}
764
-
765
-	/**
766
-	 * Checks whether the server is running on Mac OS X
767
-	 *
768
-	 * @return bool true if running on Mac OS X, false otherwise
769
-	 */
770
-	public static function runningOnMac() {
771
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
772
-	}
773
-
774
-	/**
775
-	 * Handles the case that there may not be a theme, then check if a "default"
776
-	 * theme exists and take that one
777
-	 *
778
-	 * @return string the theme
779
-	 */
780
-	public static function getTheme() {
781
-		$theme = \OC::$server->getSystemConfig()->getValue('theme', '');
782
-
783
-		if ($theme === '') {
784
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
785
-				$theme = 'default';
786
-			}
787
-		}
788
-
789
-		return $theme;
790
-	}
791
-
792
-	/**
793
-	 * Normalize a unicode string
794
-	 *
795
-	 * @param string $value a not normalized string
796
-	 * @return string The normalized string or the input if the normalization failed
797
-	 */
798
-	public static function normalizeUnicode(string $value): string {
799
-		if (Normalizer::isNormalized($value)) {
800
-			return $value;
801
-		}
802
-
803
-		$normalizedValue = Normalizer::normalize($value);
804
-		if ($normalizedValue === false) {
805
-			\OCP\Server::get(LoggerInterface::class)->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
806
-			return $value;
807
-		}
808
-
809
-		return $normalizedValue;
810
-	}
811
-
812
-	/**
813
-	 * Check whether the instance needs to perform an upgrade,
814
-	 * either when the core version is higher or any app requires
815
-	 * an upgrade.
816
-	 *
817
-	 * @param \OC\SystemConfig $config
818
-	 * @return bool whether the core or any app needs an upgrade
819
-	 * @throws \OCP\HintException When the upgrade from the given version is not allowed
820
-	 * @deprecated 32.0.0 Use \OCP\Util::needUpgrade instead
821
-	 */
822
-	public static function needUpgrade(\OC\SystemConfig $config) {
823
-		if ($config->getValue('installed', false)) {
824
-			$installedVersion = $config->getValue('version', '0.0.0');
825
-			$currentVersion = implode('.', \OCP\Util::getVersion());
826
-			$versionDiff = version_compare($currentVersion, $installedVersion);
827
-			if ($versionDiff > 0) {
828
-				return true;
829
-			} elseif ($config->getValue('debug', false) && $versionDiff < 0) {
830
-				// downgrade with debug
831
-				$installedMajor = explode('.', $installedVersion);
832
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
833
-				$currentMajor = explode('.', $currentVersion);
834
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
835
-				if ($installedMajor === $currentMajor) {
836
-					// Same major, allow downgrade for developers
837
-					return true;
838
-				} else {
839
-					// downgrade attempt, throw exception
840
-					throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
841
-				}
842
-			} elseif ($versionDiff < 0) {
843
-				// downgrade attempt, throw exception
844
-				throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
845
-			}
846
-
847
-			// also check for upgrades for apps (independently from the user)
848
-			$apps = \OC_App::getEnabledApps(false, true);
849
-			$shouldUpgrade = false;
850
-			foreach ($apps as $app) {
851
-				if (\OC_App::shouldUpgrade($app)) {
852
-					$shouldUpgrade = true;
853
-					break;
854
-				}
855
-			}
856
-			return $shouldUpgrade;
857
-		} else {
858
-			return false;
859
-		}
860
-	}
25
+    public static $styles = [];
26
+    public static $headers = [];
27
+
28
+    /**
29
+     * Setup the file system
30
+     *
31
+     * @param string|null $user
32
+     * @return boolean
33
+     * @description configure the initial filesystem based on the configuration
34
+     * @suppress PhanDeprecatedFunction
35
+     * @suppress PhanAccessMethodInternal
36
+     */
37
+    public static function setupFS(?string $user = '') {
38
+        // If we are not forced to load a specific user we load the one that is logged in
39
+        if ($user === '') {
40
+            $userObject = \OC::$server->get(\OCP\IUserSession::class)->getUser();
41
+        } else {
42
+            $userObject = \OC::$server->get(\OCP\IUserManager::class)->get($user);
43
+        }
44
+
45
+        /** @var SetupManager $setupManager */
46
+        $setupManager = \OC::$server->get(SetupManager::class);
47
+
48
+        if ($userObject) {
49
+            $setupManager->setupForUser($userObject);
50
+        } else {
51
+            $setupManager->setupRoot();
52
+        }
53
+        return true;
54
+    }
55
+
56
+    /**
57
+     * Check if a password is required for each public link
58
+     *
59
+     * @param bool $checkGroupMembership Check group membership exclusion
60
+     * @return bool
61
+     * @deprecated 32.0.0 use OCP\Share\IManager's shareApiLinkEnforcePassword directly
62
+     */
63
+    public static function isPublicLinkPasswordRequired(bool $checkGroupMembership = true) {
64
+        /** @var IManager $shareManager */
65
+        $shareManager = \OC::$server->get(IManager::class);
66
+        return $shareManager->shareApiLinkEnforcePassword($checkGroupMembership);
67
+    }
68
+
69
+    /**
70
+     * check if sharing is disabled for the current user
71
+     * @param IConfig $config
72
+     * @param IGroupManager $groupManager
73
+     * @param IUser|null $user
74
+     * @return bool
75
+     * @deprecated 32.0.0 use OCP\Share\IManager's sharingDisabledForUser directly
76
+     */
77
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
78
+        /** @var IManager $shareManager */
79
+        $shareManager = \OC::$server->get(IManager::class);
80
+        $userId = $user ? $user->getUID() : null;
81
+        return $shareManager->sharingDisabledForUser($userId);
82
+    }
83
+
84
+    /**
85
+     * check if share API enforces a default expire date
86
+     *
87
+     * @return bool
88
+     * @deprecated 32.0.0 use OCP\Share\IManager's shareApiLinkDefaultExpireDateEnforced directly
89
+     */
90
+    public static function isDefaultExpireDateEnforced() {
91
+        /** @var IManager $shareManager */
92
+        $shareManager = \OC::$server->get(IManager::class);
93
+        return $shareManager->shareApiLinkDefaultExpireDateEnforced();
94
+    }
95
+
96
+    /**
97
+     * Get the quota of a user
98
+     *
99
+     * @param IUser|null $user
100
+     * @return int|\OCP\Files\FileInfo::SPACE_UNLIMITED|false|float Quota bytes
101
+     * @deprecated 9.0.0 - Use \OCP\IUser::getQuota
102
+     */
103
+    public static function getUserQuota(?IUser $user) {
104
+        if (is_null($user)) {
105
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
106
+        }
107
+        $userQuota = $user->getQuota();
108
+        if ($userQuota === 'none') {
109
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
110
+        }
111
+        return \OCP\Util::computerFileSize($userQuota);
112
+    }
113
+
114
+    /**
115
+     * copies the skeleton to the users /files
116
+     *
117
+     * @param string $userId
118
+     * @param \OCP\Files\Folder $userDirectory
119
+     * @throws \OCP\Files\NotFoundException
120
+     * @throws \OCP\Files\NotPermittedException
121
+     * @suppress PhanDeprecatedFunction
122
+     */
123
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
124
+        /** @var LoggerInterface $logger */
125
+        $logger = \OC::$server->get(LoggerInterface::class);
126
+
127
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValueString('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
128
+        $userLang = \OC::$server->get(IFactory::class)->findLanguage();
129
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
130
+
131
+        if (!file_exists($skeletonDirectory)) {
132
+            $dialectStart = strpos($userLang, '_');
133
+            if ($dialectStart !== false) {
134
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
135
+            }
136
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
137
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
138
+            }
139
+            if (!file_exists($skeletonDirectory)) {
140
+                $skeletonDirectory = '';
141
+            }
142
+        }
143
+
144
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
145
+
146
+        if ($instanceId === null) {
147
+            throw new \RuntimeException('no instance id!');
148
+        }
149
+        $appdata = 'appdata_' . $instanceId;
150
+        if ($userId === $appdata) {
151
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
152
+        }
153
+
154
+        if (!empty($skeletonDirectory)) {
155
+            $logger->debug('copying skeleton for ' . $userId . ' from ' . $skeletonDirectory . ' to ' . $userDirectory->getFullPath('/'), ['app' => 'files_skeleton']);
156
+            self::copyr($skeletonDirectory, $userDirectory);
157
+            // update the file cache
158
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
159
+
160
+            /** @var ITemplateManager $templateManager */
161
+            $templateManager = \OC::$server->get(ITemplateManager::class);
162
+            $templateManager->initializeTemplateDirectory(null, $userId);
163
+        }
164
+    }
165
+
166
+    /**
167
+     * copies a directory recursively by using streams
168
+     *
169
+     * @param string $source
170
+     * @param \OCP\Files\Folder $target
171
+     * @return void
172
+     */
173
+    public static function copyr($source, \OCP\Files\Folder $target) {
174
+        $logger = \OCP\Server::get(LoggerInterface::class);
175
+
176
+        // Verify if folder exists
177
+        $dir = opendir($source);
178
+        if ($dir === false) {
179
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
180
+            return;
181
+        }
182
+
183
+        // Copy the files
184
+        while (false !== ($file = readdir($dir))) {
185
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
186
+                if (is_dir($source . '/' . $file)) {
187
+                    $child = $target->newFolder($file);
188
+                    self::copyr($source . '/' . $file, $child);
189
+                } else {
190
+                    $child = $target->newFile($file);
191
+                    $sourceStream = fopen($source . '/' . $file, 'r');
192
+                    if ($sourceStream === false) {
193
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
194
+                        closedir($dir);
195
+                        return;
196
+                    }
197
+                    $child->putContent($sourceStream);
198
+                }
199
+            }
200
+        }
201
+        closedir($dir);
202
+    }
203
+
204
+    /**
205
+     * @deprecated 32.0.0 Call tearDown directly on SetupManager
206
+     */
207
+    public static function tearDownFS(): void {
208
+        $setupManager = \OCP\Server::get(SetupManager::class);
209
+        $setupManager->tearDown();
210
+    }
211
+
212
+    /**
213
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
214
+     *
215
+     * @param string $application application to get the files from
216
+     * @param string $directory directory within this application (css, js, vendor, etc)
217
+     * @param ?string $file the file inside of the above folder
218
+     */
219
+    private static function generatePath($application, $directory, $file): string {
220
+        if (is_null($file)) {
221
+            $file = $application;
222
+            $application = '';
223
+        }
224
+        if (!empty($application)) {
225
+            return "$application/$directory/$file";
226
+        } else {
227
+            return "$directory/$file";
228
+        }
229
+    }
230
+
231
+    /**
232
+     * add a css file
233
+     *
234
+     * @param string $application application id
235
+     * @param string|null $file filename
236
+     * @param bool $prepend prepend the Style to the beginning of the list
237
+     * @deprecated 32.0.0 Use \OCP\Util::addStyle
238
+     */
239
+    public static function addStyle($application, $file = null, $prepend = false): void {
240
+        $path = OC_Util::generatePath($application, 'css', $file);
241
+        self::addExternalResource($application, $prepend, $path, 'style');
242
+    }
243
+
244
+    /**
245
+     * add a css file from the vendor sub folder
246
+     *
247
+     * @param string $application application id
248
+     * @param string|null $file filename
249
+     * @param bool $prepend prepend the Style to the beginning of the list
250
+     * @deprecated 32.0.0
251
+     */
252
+    public static function addVendorStyle($application, $file = null, $prepend = false): void {
253
+        $path = OC_Util::generatePath($application, 'vendor', $file);
254
+        self::addExternalResource($application, $prepend, $path, 'style');
255
+    }
256
+
257
+    /**
258
+     * add an external resource css/js file
259
+     *
260
+     * @param string $application application id
261
+     * @param bool $prepend prepend the file to the beginning of the list
262
+     * @param string $path
263
+     * @param string $type (script or style)
264
+     */
265
+    private static function addExternalResource($application, $prepend, $path, $type = 'script'): void {
266
+        if ($type === 'style') {
267
+            if (!in_array($path, self::$styles)) {
268
+                if ($prepend === true) {
269
+                    array_unshift(self::$styles, $path);
270
+                } else {
271
+                    self::$styles[] = $path;
272
+                }
273
+            }
274
+        }
275
+    }
276
+
277
+    /**
278
+     * Add a custom element to the header
279
+     * If $text is null then the element will be written as empty element.
280
+     * So use "" to get a closing tag.
281
+     * @param string $tag tag name of the element
282
+     * @param array $attributes array of attributes for the element
283
+     * @param string $text the text content for the element
284
+     * @param bool $prepend prepend the header to the beginning of the list
285
+     * @deprecated 32.0.0 Use \OCP\Util::addHeader instead
286
+     */
287
+    public static function addHeader($tag, $attributes, $text = null, $prepend = false): void {
288
+        $header = [
289
+            'tag' => $tag,
290
+            'attributes' => $attributes,
291
+            'text' => $text
292
+        ];
293
+        if ($prepend === true) {
294
+            array_unshift(self::$headers, $header);
295
+        } else {
296
+            self::$headers[] = $header;
297
+        }
298
+    }
299
+
300
+    /**
301
+     * check if the current server configuration is suitable for ownCloud
302
+     *
303
+     * @return array arrays with error messages and hints
304
+     */
305
+    public static function checkServer(\OC\SystemConfig $config) {
306
+        $l = \OC::$server->getL10N('lib');
307
+        $errors = [];
308
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
309
+
310
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
311
+            // this check needs to be done every time
312
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
313
+        }
314
+
315
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
316
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
317
+            return $errors;
318
+        }
319
+
320
+        $webServerRestart = false;
321
+        $setup = \OCP\Server::get(\OC\Setup::class);
322
+
323
+        $urlGenerator = \OC::$server->getURLGenerator();
324
+
325
+        $availableDatabases = $setup->getSupportedDatabases();
326
+        if (empty($availableDatabases)) {
327
+            $errors[] = [
328
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
329
+                'hint' => '' //TODO: sane hint
330
+            ];
331
+            $webServerRestart = true;
332
+        }
333
+
334
+        // Check if config folder is writable.
335
+        if (!(bool)$config->getValue('config_is_read_only', false)) {
336
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
337
+                $errors[] = [
338
+                    'error' => $l->t('Cannot write into "config" directory.'),
339
+                    'hint' => $l->t('This can usually be fixed by giving the web server write access to the config directory. See %s',
340
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
341
+                        . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
342
+                            [ $urlGenerator->linkToDocs('admin-config') ])
343
+                ];
344
+            }
345
+        }
346
+
347
+        // Check if there is a writable install folder.
348
+        if ($config->getValue('appstoreenabled', true)) {
349
+            if (OC_App::getInstallPath() === null
350
+                || !is_writable(OC_App::getInstallPath())
351
+                || !is_readable(OC_App::getInstallPath())
352
+            ) {
353
+                $errors[] = [
354
+                    'error' => $l->t('Cannot write into "apps" directory.'),
355
+                    'hint' => $l->t('This can usually be fixed by giving the web server write access to the apps directory'
356
+                        . ' or disabling the App Store in the config file.')
357
+                ];
358
+            }
359
+        }
360
+        // Create root dir.
361
+        if ($config->getValue('installed', false)) {
362
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
363
+                $success = @mkdir($CONFIG_DATADIRECTORY);
364
+                if ($success) {
365
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
366
+                } else {
367
+                    $errors[] = [
368
+                        'error' => $l->t('Cannot create "data" directory.'),
369
+                        'hint' => $l->t('This can usually be fixed by giving the web server write access to the root directory. See %s',
370
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
371
+                    ];
372
+                }
373
+            } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
374
+                // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
375
+                $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
376
+                $handle = fopen($testFile, 'w');
377
+                if (!$handle || fwrite($handle, 'Test write operation') === false) {
378
+                    $permissionsHint = $l->t('Permissions can usually be fixed by giving the web server write access to the root directory. See %s.',
379
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')]);
380
+                    $errors[] = [
381
+                        'error' => $l->t('Your data directory is not writable.'),
382
+                        'hint' => $permissionsHint
383
+                    ];
384
+                } else {
385
+                    fclose($handle);
386
+                    unlink($testFile);
387
+                }
388
+            } else {
389
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
390
+            }
391
+        }
392
+
393
+        if (!OC_Util::isSetLocaleWorking()) {
394
+            $errors[] = [
395
+                'error' => $l->t('Setting locale to %s failed.',
396
+                    ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
397
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
398
+                'hint' => $l->t('Please install one of these locales on your system and restart your web server.')
399
+            ];
400
+        }
401
+
402
+        // Contains the dependencies that should be checked against
403
+        // classes = class_exists
404
+        // functions = function_exists
405
+        // defined = defined
406
+        // ini = ini_get
407
+        // If the dependency is not found the missing module name is shown to the EndUser
408
+        // When adding new checks always verify that they pass on CI as well
409
+        $dependencies = [
410
+            'classes' => [
411
+                'ZipArchive' => 'zip',
412
+                'DOMDocument' => 'dom',
413
+                'XMLWriter' => 'XMLWriter',
414
+                'XMLReader' => 'XMLReader',
415
+            ],
416
+            'functions' => [
417
+                'xml_parser_create' => 'libxml',
418
+                'mb_strcut' => 'mbstring',
419
+                'ctype_digit' => 'ctype',
420
+                'json_encode' => 'JSON',
421
+                'gd_info' => 'GD',
422
+                'gzencode' => 'zlib',
423
+                'simplexml_load_string' => 'SimpleXML',
424
+                'hash' => 'HASH Message Digest Framework',
425
+                'curl_init' => 'cURL',
426
+                'openssl_verify' => 'OpenSSL',
427
+            ],
428
+            'defined' => [
429
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
430
+            ],
431
+            'ini' => [
432
+                'default_charset' => 'UTF-8',
433
+            ],
434
+        ];
435
+        $missingDependencies = [];
436
+        $invalidIniSettings = [];
437
+
438
+        $iniWrapper = \OC::$server->get(IniGetWrapper::class);
439
+        foreach ($dependencies['classes'] as $class => $module) {
440
+            if (!class_exists($class)) {
441
+                $missingDependencies[] = $module;
442
+            }
443
+        }
444
+        foreach ($dependencies['functions'] as $function => $module) {
445
+            if (!function_exists($function)) {
446
+                $missingDependencies[] = $module;
447
+            }
448
+        }
449
+        foreach ($dependencies['defined'] as $defined => $module) {
450
+            if (!defined($defined)) {
451
+                $missingDependencies[] = $module;
452
+            }
453
+        }
454
+        foreach ($dependencies['ini'] as $setting => $expected) {
455
+            if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
456
+                $invalidIniSettings[] = [$setting, $expected];
457
+            }
458
+        }
459
+
460
+        foreach ($missingDependencies as $missingDependency) {
461
+            $errors[] = [
462
+                'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
463
+                'hint' => $l->t('Please ask your server administrator to install the module.'),
464
+            ];
465
+            $webServerRestart = true;
466
+        }
467
+        foreach ($invalidIniSettings as $setting) {
468
+            $errors[] = [
469
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
470
+                'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
471
+            ];
472
+            $webServerRestart = true;
473
+        }
474
+
475
+        /**
476
+         * The mbstring.func_overload check can only be performed if the mbstring
477
+         * module is installed as it will return null if the checking setting is
478
+         * not available and thus a check on the boolean value fails.
479
+         *
480
+         * TODO: Should probably be implemented in the above generic dependency
481
+         *       check somehow in the long-term.
482
+         */
483
+        if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
484
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
485
+            $errors[] = [
486
+                'error' => $l->t('<code>mbstring.func_overload</code> is set to <code>%s</code> instead of the expected value <code>0</code>.', [$iniWrapper->getString('mbstring.func_overload')]),
487
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini.')
488
+            ];
489
+        }
490
+
491
+        if (!self::isAnnotationsWorking()) {
492
+            $errors[] = [
493
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
494
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
495
+            ];
496
+        }
497
+
498
+        if (!\OC::$CLI && $webServerRestart) {
499
+            $errors[] = [
500
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
501
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
502
+            ];
503
+        }
504
+
505
+        foreach (['secret', 'instanceid', 'passwordsalt'] as $requiredConfig) {
506
+            if ($config->getValue($requiredConfig, '') === '' && !\OC::$CLI && $config->getValue('installed', false)) {
507
+                $errors[] = [
508
+                    'error' => $l->t('The required %s config variable is not configured in the config.php file.', [$requiredConfig]),
509
+                    'hint' => $l->t('Please ask your server administrator to check the Nextcloud configuration.')
510
+                ];
511
+            }
512
+        }
513
+
514
+        // Cache the result of this function
515
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
516
+
517
+        return $errors;
518
+    }
519
+
520
+    /**
521
+     * Check for correct file permissions of data directory
522
+     *
523
+     * @param string $dataDirectory
524
+     * @return array arrays with error messages and hints
525
+     * @internal
526
+     */
527
+    public static function checkDataDirectoryPermissions($dataDirectory) {
528
+        if (!\OC::$server->getConfig()->getSystemValueBool('check_data_directory_permissions', true)) {
529
+            return  [];
530
+        }
531
+
532
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
533
+        if (substr($perms, -1) !== '0') {
534
+            chmod($dataDirectory, 0770);
535
+            clearstatcache();
536
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
537
+            if ($perms[2] !== '0') {
538
+                $l = \OC::$server->getL10N('lib');
539
+                return [[
540
+                    'error' => $l->t('Your data directory is readable by other people.'),
541
+                    'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other people.'),
542
+                ]];
543
+            }
544
+        }
545
+        return [];
546
+    }
547
+
548
+    /**
549
+     * Check that the data directory exists and is valid by
550
+     * checking the existence of the ".ncdata" file.
551
+     *
552
+     * @param string $dataDirectory data directory path
553
+     * @return array errors found
554
+     * @internal
555
+     */
556
+    public static function checkDataDirectoryValidity($dataDirectory) {
557
+        $l = \OC::$server->getL10N('lib');
558
+        $errors = [];
559
+        if ($dataDirectory[0] !== '/') {
560
+            $errors[] = [
561
+                'error' => $l->t('Your data directory must be an absolute path.'),
562
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration.')
563
+            ];
564
+        }
565
+
566
+        if (!file_exists($dataDirectory . '/.ncdata')) {
567
+            $errors[] = [
568
+                'error' => $l->t('Your data directory is invalid.'),
569
+                'hint' => $l->t('Ensure there is a file called "%1$s" in the root of the data directory. It should have the content: "%2$s"', ['.ncdata', '# Nextcloud data directory']),
570
+            ];
571
+        }
572
+        return $errors;
573
+    }
574
+
575
+    /**
576
+     * Check if the user is logged in, redirects to home if not. With
577
+     * redirect URL parameter to the request URI.
578
+     *
579
+     * @deprecated 32.0.0
580
+     */
581
+    public static function checkLoggedIn(): void {
582
+        // Check if we are a user
583
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
584
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
585
+                'core.login.showLoginForm',
586
+                [
587
+                    'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
588
+                ]
589
+            )
590
+            );
591
+            exit();
592
+        }
593
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
594
+        if (\OC::$server->get(TwoFactorAuthManager::class)->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
595
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
596
+            exit();
597
+        }
598
+    }
599
+
600
+    /**
601
+     * Check if the user is a admin, redirects to home if not
602
+     *
603
+     * @deprecated 32.0.0
604
+     */
605
+    public static function checkAdminUser(): void {
606
+        self::checkLoggedIn();
607
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
608
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
609
+            exit();
610
+        }
611
+    }
612
+
613
+    /**
614
+     * Returns the URL of the default page
615
+     * based on the system configuration and
616
+     * the apps visible for the current user
617
+     *
618
+     * @return string URL
619
+     * @deprecated 32.0.0 use IURLGenerator's linkToDefaultPageUrl directly
620
+     */
621
+    public static function getDefaultPageUrl() {
622
+        /** @var IURLGenerator $urlGenerator */
623
+        $urlGenerator = \OC::$server->get(IURLGenerator::class);
624
+        return $urlGenerator->linkToDefaultPageUrl();
625
+    }
626
+
627
+    /**
628
+     * Redirect to the user default page
629
+     *
630
+     * @deprecated 32.0.0
631
+     */
632
+    public static function redirectToDefaultPage(): void {
633
+        $location = self::getDefaultPageUrl();
634
+        header('Location: ' . $location);
635
+        exit();
636
+    }
637
+
638
+    /**
639
+     * get an id unique for this instance
640
+     *
641
+     * @return string
642
+     */
643
+    public static function getInstanceId(): string {
644
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
645
+        if (is_null($id)) {
646
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
647
+            $id = 'oc' . \OC::$server->get(ISecureRandom::class)->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
648
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
649
+        }
650
+        return $id;
651
+    }
652
+
653
+    /**
654
+     * Public function to sanitize HTML
655
+     *
656
+     * This function is used to sanitize HTML and should be applied on any
657
+     * string or array of strings before displaying it on a web page.
658
+     *
659
+     * @param string|string[] $value
660
+     * @return ($value is array ? string[] : string)
661
+     * @deprecated 32.0.0 use \OCP\Util::sanitizeHTML instead
662
+     */
663
+    public static function sanitizeHTML($value) {
664
+        if (is_array($value)) {
665
+            $value = array_map(function ($value) {
666
+                return self::sanitizeHTML($value);
667
+            }, $value);
668
+        } else {
669
+            // Specify encoding for PHP<5.4
670
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
671
+        }
672
+        return $value;
673
+    }
674
+
675
+    /**
676
+     * Public function to encode url parameters
677
+     *
678
+     * This function is used to encode path to file before output.
679
+     * Encoding is done according to RFC 3986 with one exception:
680
+     * Character '/' is preserved as is.
681
+     *
682
+     * @param string $component part of URI to encode
683
+     * @return string
684
+     * @deprecated 32.0.0 use \OCP\Util::encodePath instead
685
+     */
686
+    public static function encodePath($component) {
687
+        $encoded = rawurlencode($component);
688
+        $encoded = str_replace('%2F', '/', $encoded);
689
+        return $encoded;
690
+    }
691
+
692
+    /**
693
+     * Check if current locale is non-UTF8
694
+     *
695
+     * @return bool
696
+     */
697
+    private static function isNonUTF8Locale() {
698
+        if (function_exists('escapeshellcmd')) {
699
+            return escapeshellcmd('§') === '';
700
+        } elseif (function_exists('escapeshellarg')) {
701
+            return escapeshellarg('§') === '\'\'';
702
+        } else {
703
+            return preg_match('/utf-?8/i', setlocale(LC_CTYPE, 0)) === 0;
704
+        }
705
+    }
706
+
707
+    /**
708
+     * Check if the setlocale call does not work. This can happen if the right
709
+     * local packages are not available on the server.
710
+     *
711
+     * @internal
712
+     */
713
+    public static function isSetLocaleWorking(): bool {
714
+        if (self::isNonUTF8Locale()) {
715
+            // Borrowed from \Patchwork\Utf8\Bootup::initLocale
716
+            setlocale(LC_ALL, 'C.UTF-8', 'C');
717
+            setlocale(LC_CTYPE, 'en_US.UTF-8', 'fr_FR.UTF-8', 'es_ES.UTF-8', 'de_DE.UTF-8', 'ru_RU.UTF-8', 'pt_BR.UTF-8', 'it_IT.UTF-8', 'ja_JP.UTF-8', 'zh_CN.UTF-8', '0');
718
+
719
+            // Check again
720
+            if (self::isNonUTF8Locale()) {
721
+                return false;
722
+            }
723
+        }
724
+
725
+        return true;
726
+    }
727
+
728
+    /**
729
+     * Check if it's possible to get the inline annotations
730
+     *
731
+     * @internal
732
+     */
733
+    public static function isAnnotationsWorking(): bool {
734
+        if (PHP_VERSION_ID >= 80300) {
735
+            /** @psalm-suppress UndefinedMethod */
736
+            $reflection = \ReflectionMethod::createFromMethodName(__METHOD__);
737
+        } else {
738
+            $reflection = new \ReflectionMethod(__METHOD__);
739
+        }
740
+        $docs = $reflection->getDocComment();
741
+
742
+        return (is_string($docs) && strlen($docs) > 50);
743
+    }
744
+
745
+    /**
746
+     * Check if the PHP module fileinfo is loaded.
747
+     *
748
+     * @internal
749
+     */
750
+    public static function fileInfoLoaded(): bool {
751
+        return function_exists('finfo_open');
752
+    }
753
+
754
+    /**
755
+     * clear all levels of output buffering
756
+     *
757
+     * @return void
758
+     */
759
+    public static function obEnd() {
760
+        while (ob_get_level()) {
761
+            ob_end_clean();
762
+        }
763
+    }
764
+
765
+    /**
766
+     * Checks whether the server is running on Mac OS X
767
+     *
768
+     * @return bool true if running on Mac OS X, false otherwise
769
+     */
770
+    public static function runningOnMac() {
771
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
772
+    }
773
+
774
+    /**
775
+     * Handles the case that there may not be a theme, then check if a "default"
776
+     * theme exists and take that one
777
+     *
778
+     * @return string the theme
779
+     */
780
+    public static function getTheme() {
781
+        $theme = \OC::$server->getSystemConfig()->getValue('theme', '');
782
+
783
+        if ($theme === '') {
784
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
785
+                $theme = 'default';
786
+            }
787
+        }
788
+
789
+        return $theme;
790
+    }
791
+
792
+    /**
793
+     * Normalize a unicode string
794
+     *
795
+     * @param string $value a not normalized string
796
+     * @return string The normalized string or the input if the normalization failed
797
+     */
798
+    public static function normalizeUnicode(string $value): string {
799
+        if (Normalizer::isNormalized($value)) {
800
+            return $value;
801
+        }
802
+
803
+        $normalizedValue = Normalizer::normalize($value);
804
+        if ($normalizedValue === false) {
805
+            \OCP\Server::get(LoggerInterface::class)->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
806
+            return $value;
807
+        }
808
+
809
+        return $normalizedValue;
810
+    }
811
+
812
+    /**
813
+     * Check whether the instance needs to perform an upgrade,
814
+     * either when the core version is higher or any app requires
815
+     * an upgrade.
816
+     *
817
+     * @param \OC\SystemConfig $config
818
+     * @return bool whether the core or any app needs an upgrade
819
+     * @throws \OCP\HintException When the upgrade from the given version is not allowed
820
+     * @deprecated 32.0.0 Use \OCP\Util::needUpgrade instead
821
+     */
822
+    public static function needUpgrade(\OC\SystemConfig $config) {
823
+        if ($config->getValue('installed', false)) {
824
+            $installedVersion = $config->getValue('version', '0.0.0');
825
+            $currentVersion = implode('.', \OCP\Util::getVersion());
826
+            $versionDiff = version_compare($currentVersion, $installedVersion);
827
+            if ($versionDiff > 0) {
828
+                return true;
829
+            } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
830
+                // downgrade with debug
831
+                $installedMajor = explode('.', $installedVersion);
832
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
833
+                $currentMajor = explode('.', $currentVersion);
834
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
835
+                if ($installedMajor === $currentMajor) {
836
+                    // Same major, allow downgrade for developers
837
+                    return true;
838
+                } else {
839
+                    // downgrade attempt, throw exception
840
+                    throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
841
+                }
842
+            } elseif ($versionDiff < 0) {
843
+                // downgrade attempt, throw exception
844
+                throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
845
+            }
846
+
847
+            // also check for upgrades for apps (independently from the user)
848
+            $apps = \OC_App::getEnabledApps(false, true);
849
+            $shouldUpgrade = false;
850
+            foreach ($apps as $app) {
851
+                if (\OC_App::shouldUpgrade($app)) {
852
+                    $shouldUpgrade = true;
853
+                    break;
854
+                }
855
+            }
856
+            return $shouldUpgrade;
857
+        } else {
858
+            return false;
859
+        }
860
+    }
861 861
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
 		/** @var LoggerInterface $logger */
125 125
 		$logger = \OC::$server->get(LoggerInterface::class);
126 126
 
127
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValueString('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
127
+		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValueString('skeletondirectory', \OC::$SERVERROOT.'/core/skeleton');
128 128
 		$userLang = \OC::$server->get(IFactory::class)->findLanguage();
129 129
 		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
130 130
 
@@ -146,13 +146,13 @@  discard block
 block discarded – undo
146 146
 		if ($instanceId === null) {
147 147
 			throw new \RuntimeException('no instance id!');
148 148
 		}
149
-		$appdata = 'appdata_' . $instanceId;
149
+		$appdata = 'appdata_'.$instanceId;
150 150
 		if ($userId === $appdata) {
151
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
151
+			throw new \RuntimeException('username is reserved name: '.$appdata);
152 152
 		}
153 153
 
154 154
 		if (!empty($skeletonDirectory)) {
155
-			$logger->debug('copying skeleton for ' . $userId . ' from ' . $skeletonDirectory . ' to ' . $userDirectory->getFullPath('/'), ['app' => 'files_skeleton']);
155
+			$logger->debug('copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'), ['app' => 'files_skeleton']);
156 156
 			self::copyr($skeletonDirectory, $userDirectory);
157 157
 			// update the file cache
158 158
 			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
@@ -183,14 +183,14 @@  discard block
 block discarded – undo
183 183
 		// Copy the files
184 184
 		while (false !== ($file = readdir($dir))) {
185 185
 			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
186
-				if (is_dir($source . '/' . $file)) {
186
+				if (is_dir($source.'/'.$file)) {
187 187
 					$child = $target->newFolder($file);
188
-					self::copyr($source . '/' . $file, $child);
188
+					self::copyr($source.'/'.$file, $child);
189 189
 				} else {
190 190
 					$child = $target->newFile($file);
191
-					$sourceStream = fopen($source . '/' . $file, 'r');
191
+					$sourceStream = fopen($source.'/'.$file, 'r');
192 192
 					if ($sourceStream === false) {
193
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
193
+						$logger->error(sprintf('Could not fopen "%s"', $source.'/'.$file), ['app' => 'core']);
194 194
 						closedir($dir);
195 195
 						return;
196 196
 					}
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
 	public static function checkServer(\OC\SystemConfig $config) {
306 306
 		$l = \OC::$server->getL10N('lib');
307 307
 		$errors = [];
308
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
308
+		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT.'/data');
309 309
 
310 310
 		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
311 311
 			// this check needs to be done every time
@@ -332,14 +332,14 @@  discard block
 block discarded – undo
332 332
 		}
333 333
 
334 334
 		// Check if config folder is writable.
335
-		if (!(bool)$config->getValue('config_is_read_only', false)) {
335
+		if (!(bool) $config->getValue('config_is_read_only', false)) {
336 336
 			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
337 337
 				$errors[] = [
338 338
 					'error' => $l->t('Cannot write into "config" directory.'),
339 339
 					'hint' => $l->t('This can usually be fixed by giving the web server write access to the config directory. See %s',
340
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
340
+						[$urlGenerator->linkToDocs('admin-dir_permissions')]).'. '
341 341
 						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
342
-							[ $urlGenerator->linkToDocs('admin-config') ])
342
+							[$urlGenerator->linkToDocs('admin-config')])
343 343
 				];
344 344
 			}
345 345
 		}
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
 			];
564 564
 		}
565 565
 
566
-		if (!file_exists($dataDirectory . '/.ncdata')) {
566
+		if (!file_exists($dataDirectory.'/.ncdata')) {
567 567
 			$errors[] = [
568 568
 				'error' => $l->t('Your data directory is invalid.'),
569 569
 				'hint' => $l->t('Ensure there is a file called "%1$s" in the root of the data directory. It should have the content: "%2$s"', ['.ncdata', '# Nextcloud data directory']),
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
 	public static function checkLoggedIn(): void {
582 582
 		// Check if we are a user
583 583
 		if (!\OC::$server->getUserSession()->isLoggedIn()) {
584
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
584
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute(
585 585
 				'core.login.showLoginForm',
586 586
 				[
587 587
 					'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
 		}
593 593
 		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
594 594
 		if (\OC::$server->get(TwoFactorAuthManager::class)->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
595
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
595
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
596 596
 			exit();
597 597
 		}
598 598
 	}
@@ -605,7 +605,7 @@  discard block
 block discarded – undo
605 605
 	public static function checkAdminUser(): void {
606 606
 		self::checkLoggedIn();
607 607
 		if (!OC_User::isAdminUser(OC_User::getUser())) {
608
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
608
+			header('Location: '.\OCP\Util::linkToAbsolute('', 'index.php'));
609 609
 			exit();
610 610
 		}
611 611
 	}
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
 	 */
632 632
 	public static function redirectToDefaultPage(): void {
633 633
 		$location = self::getDefaultPageUrl();
634
-		header('Location: ' . $location);
634
+		header('Location: '.$location);
635 635
 		exit();
636 636
 	}
637 637
 
@@ -644,7 +644,7 @@  discard block
 block discarded – undo
644 644
 		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
645 645
 		if (is_null($id)) {
646 646
 			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
647
-			$id = 'oc' . \OC::$server->get(ISecureRandom::class)->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
647
+			$id = 'oc'.\OC::$server->get(ISecureRandom::class)->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
648 648
 			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
649 649
 		}
650 650
 		return $id;
@@ -662,12 +662,12 @@  discard block
 block discarded – undo
662 662
 	 */
663 663
 	public static function sanitizeHTML($value) {
664 664
 		if (is_array($value)) {
665
-			$value = array_map(function ($value) {
665
+			$value = array_map(function($value) {
666 666
 				return self::sanitizeHTML($value);
667 667
 			}, $value);
668 668
 		} else {
669 669
 			// Specify encoding for PHP<5.4
670
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
670
+			$value = htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
671 671
 		}
672 672
 		return $value;
673 673
 	}
@@ -781,7 +781,7 @@  discard block
 block discarded – undo
781 781
 		$theme = \OC::$server->getSystemConfig()->getValue('theme', '');
782 782
 
783 783
 		if ($theme === '') {
784
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
784
+			if (is_dir(OC::$SERVERROOT.'/themes/default')) {
785 785
 				$theme = 'default';
786 786
 			}
787 787
 		}
@@ -802,7 +802,7 @@  discard block
 block discarded – undo
802 802
 
803 803
 		$normalizedValue = Normalizer::normalize($value);
804 804
 		if ($normalizedValue === false) {
805
-			\OCP\Server::get(LoggerInterface::class)->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
805
+			\OCP\Server::get(LoggerInterface::class)->warning('normalizing failed for "'.$value.'"', ['app' => 'core']);
806 806
 			return $value;
807 807
 		}
808 808
 
@@ -829,19 +829,19 @@  discard block
 block discarded – undo
829 829
 			} elseif ($config->getValue('debug', false) && $versionDiff < 0) {
830 830
 				// downgrade with debug
831 831
 				$installedMajor = explode('.', $installedVersion);
832
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
832
+				$installedMajor = $installedMajor[0].'.'.$installedMajor[1];
833 833
 				$currentMajor = explode('.', $currentVersion);
834
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
834
+				$currentMajor = $currentMajor[0].'.'.$currentMajor[1];
835 835
 				if ($installedMajor === $currentMajor) {
836 836
 					// Same major, allow downgrade for developers
837 837
 					return true;
838 838
 				} else {
839 839
 					// downgrade attempt, throw exception
840
-					throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
840
+					throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
841 841
 				}
842 842
 			} elseif ($versionDiff < 0) {
843 843
 				// downgrade attempt, throw exception
844
-				throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
844
+				throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
845 845
 			}
846 846
 
847 847
 			// also check for upgrades for apps (independently from the user)
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +1150 added lines, -1150 removed lines patch added patch discarded remove patch
@@ -39,1156 +39,1156 @@
 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
-			// index.php routes are handled in the middleware
555
-			// and cron.php does not need any authentication at all
556
-			if ($processingScript === 'index.php'
557
-				|| $processingScript === 'cron.php') {
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
-		if (defined('PHPUNIT_RUN')) {
605
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
606
-		}
607
-		spl_autoload_register([self::$loader, 'load']);
608
-		$loaderEnd = microtime(true);
609
-
610
-		self::$CLI = (php_sapi_name() == 'cli');
611
-
612
-		// Add default composer PSR-4 autoloader, ensure apcu to be disabled
613
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
614
-		self::$composerAutoloader->setApcuPrefix(null);
615
-
616
-
617
-		try {
618
-			self::initPaths();
619
-			// setup 3rdparty autoloader
620
-			$vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php';
621
-			if (!file_exists($vendorAutoLoad)) {
622
-				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".');
623
-			}
624
-			require_once $vendorAutoLoad;
625
-		} catch (\RuntimeException $e) {
626
-			if (!self::$CLI) {
627
-				http_response_code(503);
628
-			}
629
-			// we can't use the template error page here, because this needs the
630
-			// DI container which isn't available yet
631
-			print($e->getMessage());
632
-			exit();
633
-		}
634
-
635
-		// setup the basic server
636
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
637
-		self::$server->boot();
638
-
639
-		try {
640
-			$profiler = new BuiltInProfiler(
641
-				Server::get(IConfig::class),
642
-				Server::get(IRequest::class),
643
-			);
644
-			$profiler->start();
645
-		} catch (\Throwable $e) {
646
-			logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']);
647
-		}
648
-
649
-		if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) {
650
-			\OC\Core\Listener\BeforeMessageLoggedEventListener::setup();
651
-		}
652
-
653
-		$eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
654
-		$eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
655
-		$eventLogger->start('boot', 'Initialize');
656
-
657
-		// Override php.ini and log everything if we're troubleshooting
658
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
659
-			error_reporting(E_ALL);
660
-		}
661
-
662
-		$systemConfig = Server::get(\OC\SystemConfig::class);
663
-		self::registerAutoloaderCache($systemConfig);
664
-
665
-		// initialize intl fallback if necessary
666
-		OC_Util::isSetLocaleWorking();
667
-
668
-		$config = Server::get(IConfig::class);
669
-		if (!defined('PHPUNIT_RUN')) {
670
-			$errorHandler = new OC\Log\ErrorHandler(
671
-				\OCP\Server::get(\Psr\Log\LoggerInterface::class),
672
-			);
673
-			$exceptionHandler = [$errorHandler, 'onException'];
674
-			if ($config->getSystemValueBool('debug', false)) {
675
-				set_error_handler([$errorHandler, 'onAll'], E_ALL);
676
-				if (\OC::$CLI) {
677
-					$exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage'];
678
-				}
679
-			} else {
680
-				set_error_handler([$errorHandler, 'onError']);
681
-			}
682
-			register_shutdown_function([$errorHandler, 'onShutdown']);
683
-			set_exception_handler($exceptionHandler);
684
-		}
685
-
686
-		/** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
687
-		$bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
688
-		$bootstrapCoordinator->runInitialRegistration();
689
-
690
-		$eventLogger->start('init_session', 'Initialize session');
691
-
692
-		// Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users
693
-		// see https://github.com/nextcloud/server/pull/2619
694
-		if (!function_exists('simplexml_load_file')) {
695
-			throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.');
696
-		}
697
-
698
-		$appManager = Server::get(\OCP\App\IAppManager::class);
699
-		if ($systemConfig->getValue('installed', false)) {
700
-			$appManager->loadApps(['session']);
701
-		}
702
-		if (!self::$CLI) {
703
-			self::initSession();
704
-		}
705
-		$eventLogger->end('init_session');
706
-		self::checkConfig();
707
-		self::checkInstalled($systemConfig);
708
-
709
-		OC_Response::addSecurityHeaders();
710
-
711
-		self::performSameSiteCookieProtection($config);
712
-
713
-		if (!defined('OC_CONSOLE')) {
714
-			$eventLogger->start('check_server', 'Run a few configuration checks');
715
-			$errors = OC_Util::checkServer($systemConfig);
716
-			if (count($errors) > 0) {
717
-				if (!self::$CLI) {
718
-					http_response_code(503);
719
-					Util::addStyle('guest');
720
-					try {
721
-						Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]);
722
-						exit;
723
-					} catch (\Exception $e) {
724
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
725
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
726
-					}
727
-				}
728
-
729
-				// Convert l10n string into regular string for usage in database
730
-				$staticErrors = [];
731
-				foreach ($errors as $error) {
732
-					echo $error['error'] . "\n";
733
-					echo $error['hint'] . "\n\n";
734
-					$staticErrors[] = [
735
-						'error' => (string)$error['error'],
736
-						'hint' => (string)$error['hint'],
737
-					];
738
-				}
739
-
740
-				try {
741
-					$config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
742
-				} catch (\Exception $e) {
743
-					echo('Writing to database failed');
744
-				}
745
-				exit(1);
746
-			} elseif (self::$CLI && $config->getSystemValueBool('installed', false)) {
747
-				$config->deleteAppValue('core', 'cronErrors');
748
-			}
749
-			$eventLogger->end('check_server');
750
-		}
751
-
752
-		// User and Groups
753
-		if (!$systemConfig->getValue('installed', false)) {
754
-			self::$server->getSession()->set('user_id', '');
755
-		}
756
-
757
-		$eventLogger->start('setup_backends', 'Setup group and user backends');
758
-		Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database());
759
-		Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
760
-
761
-		// Subscribe to the hook
762
-		\OCP\Util::connectHook(
763
-			'\OCA\Files_Sharing\API\Server2Server',
764
-			'preLoginNameUsedAsUserName',
765
-			'\OC\User\Database',
766
-			'preLoginNameUsedAsUserName'
767
-		);
768
-
769
-		//setup extra user backends
770
-		if (!\OCP\Util::needUpgrade()) {
771
-			OC_User::setupBackends();
772
-		} else {
773
-			// Run upgrades in incognito mode
774
-			OC_User::setIncognitoMode(true);
775
-		}
776
-		$eventLogger->end('setup_backends');
777
-
778
-		self::registerCleanupHooks($systemConfig);
779
-		self::registerShareHooks($systemConfig);
780
-		self::registerEncryptionWrapperAndHooks();
781
-		self::registerAccountHooks();
782
-		self::registerResourceCollectionHooks();
783
-		self::registerFileReferenceEventListener();
784
-		self::registerRenderReferenceEventListener();
785
-		self::registerAppRestrictionsHooks();
786
-
787
-		// Make sure that the application class is not loaded before the database is setup
788
-		if ($systemConfig->getValue('installed', false)) {
789
-			$appManager->loadApp('settings');
790
-			/* Build core application to make sure that listeners are registered */
791
-			Server::get(\OC\Core\Application::class);
792
-		}
793
-
794
-		//make sure temporary files are cleaned up
795
-		$tmpManager = Server::get(\OCP\ITempManager::class);
796
-		register_shutdown_function([$tmpManager, 'clean']);
797
-		$lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
798
-		register_shutdown_function([$lockProvider, 'releaseAll']);
799
-
800
-		// Check whether the sample configuration has been copied
801
-		if ($systemConfig->getValue('copied_sample_config', false)) {
802
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
803
-			Server::get(ITemplateManager::class)->printErrorPage(
804
-				$l->t('Sample configuration detected'),
805
-				$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'),
806
-				503
807
-			);
808
-			return;
809
-		}
810
-
811
-		$request = Server::get(IRequest::class);
812
-		$host = $request->getInsecureServerHost();
813
-		/**
814
-		 * if the host passed in headers isn't trusted
815
-		 * FIXME: Should not be in here at all :see_no_evil:
816
-		 */
817
-		if (!OC::$CLI
818
-			&& !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
819
-			&& $config->getSystemValueBool('installed', false)
820
-		) {
821
-			// Allow access to CSS resources
822
-			$isScssRequest = false;
823
-			if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
824
-				$isScssRequest = true;
825
-			}
826
-
827
-			if (substr($request->getRequestUri(), -11) === '/status.php') {
828
-				http_response_code(400);
829
-				header('Content-Type: application/json');
830
-				echo '{"error": "Trusted domain error.", "code": 15}';
831
-				exit();
832
-			}
833
-
834
-			if (!$isScssRequest) {
835
-				http_response_code(400);
836
-				Server::get(LoggerInterface::class)->info(
837
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
838
-					[
839
-						'app' => 'core',
840
-						'remoteAddress' => $request->getRemoteAddress(),
841
-						'host' => $host,
842
-					]
843
-				);
844
-
845
-				$tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest');
846
-				$tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
847
-				$tmpl->printPage();
848
-
849
-				exit();
850
-			}
851
-		}
852
-		$eventLogger->end('boot');
853
-		$eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
854
-		$eventLogger->start('runtime', 'Runtime');
855
-		$eventLogger->start('request', 'Full request after boot');
856
-		register_shutdown_function(function () use ($eventLogger) {
857
-			$eventLogger->end('request');
858
-		});
859
-
860
-		register_shutdown_function(function () {
861
-			$memoryPeak = memory_get_peak_usage();
862
-			$logLevel = match (true) {
863
-				$memoryPeak > 500_000_000 => ILogger::FATAL,
864
-				$memoryPeak > 400_000_000 => ILogger::ERROR,
865
-				$memoryPeak > 300_000_000 => ILogger::WARN,
866
-				default => null,
867
-			};
868
-			if ($logLevel !== null) {
869
-				$message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak);
870
-				$logger = Server::get(LoggerInterface::class);
871
-				$logger->log($logLevel, $message, ['app' => 'core']);
872
-			}
873
-		});
874
-	}
875
-
876
-	/**
877
-	 * register hooks for the cleanup of cache and bruteforce protection
878
-	 */
879
-	public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
880
-		//don't try to do this before we are properly setup
881
-		if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
882
-			// NOTE: This will be replaced to use OCP
883
-			$userSession = Server::get(\OC\User\Session::class);
884
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
885
-				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
886
-					// reset brute force delay for this IP address and username
887
-					$uid = $userSession->getUser()->getUID();
888
-					$request = Server::get(IRequest::class);
889
-					$throttler = Server::get(IThrottler::class);
890
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
891
-				}
892
-
893
-				try {
894
-					$cache = new \OC\Cache\File();
895
-					$cache->gc();
896
-				} catch (\OC\ServerNotAvailableException $e) {
897
-					// not a GC exception, pass it on
898
-					throw $e;
899
-				} catch (\OC\ForbiddenException $e) {
900
-					// filesystem blocked for this request, ignore
901
-				} catch (\Exception $e) {
902
-					// a GC exception should not prevent users from using OC,
903
-					// so log the exception
904
-					Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
905
-						'app' => 'core',
906
-						'exception' => $e,
907
-					]);
908
-				}
909
-			});
910
-		}
911
-	}
912
-
913
-	private static function registerEncryptionWrapperAndHooks(): void {
914
-		/** @var \OC\Encryption\Manager */
915
-		$manager = Server::get(\OCP\Encryption\IManager::class);
916
-		Server::get(IEventDispatcher::class)->addListener(
917
-			BeforeFileSystemSetupEvent::class,
918
-			$manager->setupStorage(...),
919
-		);
920
-
921
-		$enabled = $manager->isEnabled();
922
-		if ($enabled) {
923
-			\OC\Encryption\EncryptionEventListener::register(Server::get(IEventDispatcher::class));
924
-		}
925
-	}
926
-
927
-	private static function registerAccountHooks(): void {
928
-		/** @var IEventDispatcher $dispatcher */
929
-		$dispatcher = Server::get(IEventDispatcher::class);
930
-		$dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
931
-	}
932
-
933
-	private static function registerAppRestrictionsHooks(): void {
934
-		/** @var \OC\Group\Manager $groupManager */
935
-		$groupManager = Server::get(\OCP\IGroupManager::class);
936
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
937
-			$appManager = Server::get(\OCP\App\IAppManager::class);
938
-			$apps = $appManager->getEnabledAppsForGroup($group);
939
-			foreach ($apps as $appId) {
940
-				$restrictions = $appManager->getAppRestriction($appId);
941
-				if (empty($restrictions)) {
942
-					continue;
943
-				}
944
-				$key = array_search($group->getGID(), $restrictions);
945
-				unset($restrictions[$key]);
946
-				$restrictions = array_values($restrictions);
947
-				if (empty($restrictions)) {
948
-					$appManager->disableApp($appId);
949
-				} else {
950
-					$appManager->enableAppForGroups($appId, $restrictions);
951
-				}
952
-			}
953
-		});
954
-	}
955
-
956
-	private static function registerResourceCollectionHooks(): void {
957
-		\OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class));
958
-	}
959
-
960
-	private static function registerFileReferenceEventListener(): void {
961
-		\OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
962
-	}
963
-
964
-	private static function registerRenderReferenceEventListener() {
965
-		\OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
966
-	}
967
-
968
-	/**
969
-	 * register hooks for sharing
970
-	 */
971
-	public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
972
-		if ($systemConfig->getValue('installed')) {
973
-
974
-			$dispatcher = Server::get(IEventDispatcher::class);
975
-			$dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class);
976
-			$dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class);
977
-			$dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class);
978
-		}
979
-	}
980
-
981
-	protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
982
-		// The class loader takes an optional low-latency cache, which MUST be
983
-		// namespaced. The instanceid is used for namespacing, but might be
984
-		// unavailable at this point. Furthermore, it might not be possible to
985
-		// generate an instanceid via \OC_Util::getInstanceId() because the
986
-		// config file may not be writable. As such, we only register a class
987
-		// loader cache if instanceid is available without trying to create one.
988
-		$instanceId = $systemConfig->getValue('instanceid', null);
989
-		if ($instanceId) {
990
-			try {
991
-				$memcacheFactory = Server::get(\OCP\ICacheFactory::class);
992
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
993
-			} catch (\Exception $ex) {
994
-			}
995
-		}
996
-	}
997
-
998
-	/**
999
-	 * Handle the request
1000
-	 */
1001
-	public static function handleRequest(): void {
1002
-		Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
1003
-		$systemConfig = Server::get(\OC\SystemConfig::class);
1004
-
1005
-		// Check if Nextcloud is installed or in maintenance (update) mode
1006
-		if (!$systemConfig->getValue('installed', false)) {
1007
-			\OC::$server->getSession()->clear();
1008
-			$controller = Server::get(\OC\Core\Controller\SetupController::class);
1009
-			$controller->run($_POST);
1010
-			exit();
1011
-		}
1012
-
1013
-		$request = Server::get(IRequest::class);
1014
-		$requestPath = $request->getRawPathInfo();
1015
-		if ($requestPath === '/heartbeat') {
1016
-			return;
1017
-		}
1018
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
1019
-			self::checkMaintenanceMode($systemConfig);
1020
-
1021
-			if (\OCP\Util::needUpgrade()) {
1022
-				if (function_exists('opcache_reset')) {
1023
-					opcache_reset();
1024
-				}
1025
-				if (!((bool)$systemConfig->getValue('maintenance', false))) {
1026
-					self::printUpgradePage($systemConfig);
1027
-					exit();
1028
-				}
1029
-			}
1030
-		}
1031
-
1032
-		$appManager = Server::get(\OCP\App\IAppManager::class);
1033
-
1034
-		// Always load authentication apps
1035
-		$appManager->loadApps(['authentication']);
1036
-		$appManager->loadApps(['extended_authentication']);
1037
-
1038
-		// Load minimum set of apps
1039
-		if (!\OCP\Util::needUpgrade()
1040
-			&& !((bool)$systemConfig->getValue('maintenance', false))) {
1041
-			// For logged-in users: Load everything
1042
-			if (Server::get(IUserSession::class)->isLoggedIn()) {
1043
-				$appManager->loadApps();
1044
-			} else {
1045
-				// For guests: Load only filesystem and logging
1046
-				$appManager->loadApps(['filesystem', 'logging']);
1047
-
1048
-				// Don't try to login when a client is trying to get a OAuth token.
1049
-				// OAuth needs to support basic auth too, so the login is not valid
1050
-				// inside Nextcloud and the Login exception would ruin it.
1051
-				if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1052
-					self::handleLogin($request);
1053
-				}
1054
-			}
1055
-		}
1056
-
1057
-		if (!self::$CLI) {
1058
-			try {
1059
-				if (!\OCP\Util::needUpgrade()) {
1060
-					$appManager->loadApps(['filesystem', 'logging']);
1061
-					$appManager->loadApps();
1062
-				}
1063
-				Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1064
-				return;
1065
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1066
-				//header('HTTP/1.0 404 Not Found');
1067
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1068
-				http_response_code(405);
1069
-				return;
1070
-			}
1071
-		}
1072
-
1073
-		// Handle WebDAV
1074
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1075
-			// not allowed any more to prevent people
1076
-			// mounting this root directly.
1077
-			// Users need to mount remote.php/webdav instead.
1078
-			http_response_code(405);
1079
-			return;
1080
-		}
1081
-
1082
-		// Handle requests for JSON or XML
1083
-		$acceptHeader = $request->getHeader('Accept');
1084
-		if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1085
-			http_response_code(404);
1086
-			return;
1087
-		}
1088
-
1089
-		// Handle resources that can't be found
1090
-		// This prevents browsers from redirecting to the default page and then
1091
-		// attempting to parse HTML as CSS and similar.
1092
-		$destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1093
-		if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1094
-			http_response_code(404);
1095
-			return;
1096
-		}
1097
-
1098
-		// Redirect to the default app or login only as an entry point
1099
-		if ($requestPath === '') {
1100
-			// Someone is logged in
1101
-			if (Server::get(IUserSession::class)->isLoggedIn()) {
1102
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1103
-			} else {
1104
-				// Not handled and not logged in
1105
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1106
-			}
1107
-			return;
1108
-		}
1109
-
1110
-		try {
1111
-			Server::get(\OC\Route\Router::class)->match('/error/404');
1112
-		} catch (\Exception $e) {
1113
-			if (!$e instanceof MethodNotAllowedException) {
1114
-				logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1115
-			}
1116
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
1117
-			Server::get(ITemplateManager::class)->printErrorPage(
1118
-				'404',
1119
-				$l->t('The page could not be found on the server.'),
1120
-				404
1121
-			);
1122
-		}
1123
-	}
1124
-
1125
-	/**
1126
-	 * Check login: apache auth, auth token, basic auth
1127
-	 */
1128
-	public static function handleLogin(OCP\IRequest $request): bool {
1129
-		if ($request->getHeader('X-Nextcloud-Federation')) {
1130
-			return false;
1131
-		}
1132
-		$userSession = Server::get(\OC\User\Session::class);
1133
-		if (OC_User::handleApacheAuth()) {
1134
-			return true;
1135
-		}
1136
-		if (self::tryAppAPILogin($request)) {
1137
-			return true;
1138
-		}
1139
-		if ($userSession->tryTokenLogin($request)) {
1140
-			return true;
1141
-		}
1142
-		if (isset($_COOKIE['nc_username'])
1143
-			&& isset($_COOKIE['nc_token'])
1144
-			&& isset($_COOKIE['nc_session_id'])
1145
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1146
-			return true;
1147
-		}
1148
-		if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) {
1149
-			return true;
1150
-		}
1151
-		return false;
1152
-	}
1153
-
1154
-	protected static function handleAuthHeaders(): void {
1155
-		//copy http auth headers for apache+php-fcgid work around
1156
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1157
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1158
-		}
1159
-
1160
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1161
-		$vars = [
1162
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1163
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1164
-		];
1165
-		foreach ($vars as $var) {
1166
-			if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1167
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1168
-				if (count($credentials) === 2) {
1169
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1170
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1171
-					break;
1172
-				}
1173
-			}
1174
-		}
1175
-	}
1176
-
1177
-	protected static function tryAppAPILogin(OCP\IRequest $request): bool {
1178
-		if (!$request->getHeader('AUTHORIZATION-APP-API')) {
1179
-			return false;
1180
-		}
1181
-		$appManager = Server::get(OCP\App\IAppManager::class);
1182
-		if (!$appManager->isEnabledForAnyone('app_api')) {
1183
-			return false;
1184
-		}
1185
-		try {
1186
-			$appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class);
1187
-			return $appAPIService->validateExAppRequestToNC($request);
1188
-		} catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) {
1189
-			return false;
1190
-		}
1191
-	}
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
+            // index.php routes are handled in the middleware
555
+            // and cron.php does not need any authentication at all
556
+            if ($processingScript === 'index.php'
557
+                || $processingScript === 'cron.php') {
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
+        if (defined('PHPUNIT_RUN')) {
605
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
606
+        }
607
+        spl_autoload_register([self::$loader, 'load']);
608
+        $loaderEnd = microtime(true);
609
+
610
+        self::$CLI = (php_sapi_name() == 'cli');
611
+
612
+        // Add default composer PSR-4 autoloader, ensure apcu to be disabled
613
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
614
+        self::$composerAutoloader->setApcuPrefix(null);
615
+
616
+
617
+        try {
618
+            self::initPaths();
619
+            // setup 3rdparty autoloader
620
+            $vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php';
621
+            if (!file_exists($vendorAutoLoad)) {
622
+                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".');
623
+            }
624
+            require_once $vendorAutoLoad;
625
+        } catch (\RuntimeException $e) {
626
+            if (!self::$CLI) {
627
+                http_response_code(503);
628
+            }
629
+            // we can't use the template error page here, because this needs the
630
+            // DI container which isn't available yet
631
+            print($e->getMessage());
632
+            exit();
633
+        }
634
+
635
+        // setup the basic server
636
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
637
+        self::$server->boot();
638
+
639
+        try {
640
+            $profiler = new BuiltInProfiler(
641
+                Server::get(IConfig::class),
642
+                Server::get(IRequest::class),
643
+            );
644
+            $profiler->start();
645
+        } catch (\Throwable $e) {
646
+            logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']);
647
+        }
648
+
649
+        if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) {
650
+            \OC\Core\Listener\BeforeMessageLoggedEventListener::setup();
651
+        }
652
+
653
+        $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
654
+        $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
655
+        $eventLogger->start('boot', 'Initialize');
656
+
657
+        // Override php.ini and log everything if we're troubleshooting
658
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
659
+            error_reporting(E_ALL);
660
+        }
661
+
662
+        $systemConfig = Server::get(\OC\SystemConfig::class);
663
+        self::registerAutoloaderCache($systemConfig);
664
+
665
+        // initialize intl fallback if necessary
666
+        OC_Util::isSetLocaleWorking();
667
+
668
+        $config = Server::get(IConfig::class);
669
+        if (!defined('PHPUNIT_RUN')) {
670
+            $errorHandler = new OC\Log\ErrorHandler(
671
+                \OCP\Server::get(\Psr\Log\LoggerInterface::class),
672
+            );
673
+            $exceptionHandler = [$errorHandler, 'onException'];
674
+            if ($config->getSystemValueBool('debug', false)) {
675
+                set_error_handler([$errorHandler, 'onAll'], E_ALL);
676
+                if (\OC::$CLI) {
677
+                    $exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage'];
678
+                }
679
+            } else {
680
+                set_error_handler([$errorHandler, 'onError']);
681
+            }
682
+            register_shutdown_function([$errorHandler, 'onShutdown']);
683
+            set_exception_handler($exceptionHandler);
684
+        }
685
+
686
+        /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
687
+        $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
688
+        $bootstrapCoordinator->runInitialRegistration();
689
+
690
+        $eventLogger->start('init_session', 'Initialize session');
691
+
692
+        // Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users
693
+        // see https://github.com/nextcloud/server/pull/2619
694
+        if (!function_exists('simplexml_load_file')) {
695
+            throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.');
696
+        }
697
+
698
+        $appManager = Server::get(\OCP\App\IAppManager::class);
699
+        if ($systemConfig->getValue('installed', false)) {
700
+            $appManager->loadApps(['session']);
701
+        }
702
+        if (!self::$CLI) {
703
+            self::initSession();
704
+        }
705
+        $eventLogger->end('init_session');
706
+        self::checkConfig();
707
+        self::checkInstalled($systemConfig);
708
+
709
+        OC_Response::addSecurityHeaders();
710
+
711
+        self::performSameSiteCookieProtection($config);
712
+
713
+        if (!defined('OC_CONSOLE')) {
714
+            $eventLogger->start('check_server', 'Run a few configuration checks');
715
+            $errors = OC_Util::checkServer($systemConfig);
716
+            if (count($errors) > 0) {
717
+                if (!self::$CLI) {
718
+                    http_response_code(503);
719
+                    Util::addStyle('guest');
720
+                    try {
721
+                        Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]);
722
+                        exit;
723
+                    } catch (\Exception $e) {
724
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
725
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
726
+                    }
727
+                }
728
+
729
+                // Convert l10n string into regular string for usage in database
730
+                $staticErrors = [];
731
+                foreach ($errors as $error) {
732
+                    echo $error['error'] . "\n";
733
+                    echo $error['hint'] . "\n\n";
734
+                    $staticErrors[] = [
735
+                        'error' => (string)$error['error'],
736
+                        'hint' => (string)$error['hint'],
737
+                    ];
738
+                }
739
+
740
+                try {
741
+                    $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
742
+                } catch (\Exception $e) {
743
+                    echo('Writing to database failed');
744
+                }
745
+                exit(1);
746
+            } elseif (self::$CLI && $config->getSystemValueBool('installed', false)) {
747
+                $config->deleteAppValue('core', 'cronErrors');
748
+            }
749
+            $eventLogger->end('check_server');
750
+        }
751
+
752
+        // User and Groups
753
+        if (!$systemConfig->getValue('installed', false)) {
754
+            self::$server->getSession()->set('user_id', '');
755
+        }
756
+
757
+        $eventLogger->start('setup_backends', 'Setup group and user backends');
758
+        Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database());
759
+        Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
760
+
761
+        // Subscribe to the hook
762
+        \OCP\Util::connectHook(
763
+            '\OCA\Files_Sharing\API\Server2Server',
764
+            'preLoginNameUsedAsUserName',
765
+            '\OC\User\Database',
766
+            'preLoginNameUsedAsUserName'
767
+        );
768
+
769
+        //setup extra user backends
770
+        if (!\OCP\Util::needUpgrade()) {
771
+            OC_User::setupBackends();
772
+        } else {
773
+            // Run upgrades in incognito mode
774
+            OC_User::setIncognitoMode(true);
775
+        }
776
+        $eventLogger->end('setup_backends');
777
+
778
+        self::registerCleanupHooks($systemConfig);
779
+        self::registerShareHooks($systemConfig);
780
+        self::registerEncryptionWrapperAndHooks();
781
+        self::registerAccountHooks();
782
+        self::registerResourceCollectionHooks();
783
+        self::registerFileReferenceEventListener();
784
+        self::registerRenderReferenceEventListener();
785
+        self::registerAppRestrictionsHooks();
786
+
787
+        // Make sure that the application class is not loaded before the database is setup
788
+        if ($systemConfig->getValue('installed', false)) {
789
+            $appManager->loadApp('settings');
790
+            /* Build core application to make sure that listeners are registered */
791
+            Server::get(\OC\Core\Application::class);
792
+        }
793
+
794
+        //make sure temporary files are cleaned up
795
+        $tmpManager = Server::get(\OCP\ITempManager::class);
796
+        register_shutdown_function([$tmpManager, 'clean']);
797
+        $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
798
+        register_shutdown_function([$lockProvider, 'releaseAll']);
799
+
800
+        // Check whether the sample configuration has been copied
801
+        if ($systemConfig->getValue('copied_sample_config', false)) {
802
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
803
+            Server::get(ITemplateManager::class)->printErrorPage(
804
+                $l->t('Sample configuration detected'),
805
+                $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'),
806
+                503
807
+            );
808
+            return;
809
+        }
810
+
811
+        $request = Server::get(IRequest::class);
812
+        $host = $request->getInsecureServerHost();
813
+        /**
814
+         * if the host passed in headers isn't trusted
815
+         * FIXME: Should not be in here at all :see_no_evil:
816
+         */
817
+        if (!OC::$CLI
818
+            && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
819
+            && $config->getSystemValueBool('installed', false)
820
+        ) {
821
+            // Allow access to CSS resources
822
+            $isScssRequest = false;
823
+            if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
824
+                $isScssRequest = true;
825
+            }
826
+
827
+            if (substr($request->getRequestUri(), -11) === '/status.php') {
828
+                http_response_code(400);
829
+                header('Content-Type: application/json');
830
+                echo '{"error": "Trusted domain error.", "code": 15}';
831
+                exit();
832
+            }
833
+
834
+            if (!$isScssRequest) {
835
+                http_response_code(400);
836
+                Server::get(LoggerInterface::class)->info(
837
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
838
+                    [
839
+                        'app' => 'core',
840
+                        'remoteAddress' => $request->getRemoteAddress(),
841
+                        'host' => $host,
842
+                    ]
843
+                );
844
+
845
+                $tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest');
846
+                $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
847
+                $tmpl->printPage();
848
+
849
+                exit();
850
+            }
851
+        }
852
+        $eventLogger->end('boot');
853
+        $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
854
+        $eventLogger->start('runtime', 'Runtime');
855
+        $eventLogger->start('request', 'Full request after boot');
856
+        register_shutdown_function(function () use ($eventLogger) {
857
+            $eventLogger->end('request');
858
+        });
859
+
860
+        register_shutdown_function(function () {
861
+            $memoryPeak = memory_get_peak_usage();
862
+            $logLevel = match (true) {
863
+                $memoryPeak > 500_000_000 => ILogger::FATAL,
864
+                $memoryPeak > 400_000_000 => ILogger::ERROR,
865
+                $memoryPeak > 300_000_000 => ILogger::WARN,
866
+                default => null,
867
+            };
868
+            if ($logLevel !== null) {
869
+                $message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak);
870
+                $logger = Server::get(LoggerInterface::class);
871
+                $logger->log($logLevel, $message, ['app' => 'core']);
872
+            }
873
+        });
874
+    }
875
+
876
+    /**
877
+     * register hooks for the cleanup of cache and bruteforce protection
878
+     */
879
+    public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
880
+        //don't try to do this before we are properly setup
881
+        if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
882
+            // NOTE: This will be replaced to use OCP
883
+            $userSession = Server::get(\OC\User\Session::class);
884
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
885
+                if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
886
+                    // reset brute force delay for this IP address and username
887
+                    $uid = $userSession->getUser()->getUID();
888
+                    $request = Server::get(IRequest::class);
889
+                    $throttler = Server::get(IThrottler::class);
890
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
891
+                }
892
+
893
+                try {
894
+                    $cache = new \OC\Cache\File();
895
+                    $cache->gc();
896
+                } catch (\OC\ServerNotAvailableException $e) {
897
+                    // not a GC exception, pass it on
898
+                    throw $e;
899
+                } catch (\OC\ForbiddenException $e) {
900
+                    // filesystem blocked for this request, ignore
901
+                } catch (\Exception $e) {
902
+                    // a GC exception should not prevent users from using OC,
903
+                    // so log the exception
904
+                    Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
905
+                        'app' => 'core',
906
+                        'exception' => $e,
907
+                    ]);
908
+                }
909
+            });
910
+        }
911
+    }
912
+
913
+    private static function registerEncryptionWrapperAndHooks(): void {
914
+        /** @var \OC\Encryption\Manager */
915
+        $manager = Server::get(\OCP\Encryption\IManager::class);
916
+        Server::get(IEventDispatcher::class)->addListener(
917
+            BeforeFileSystemSetupEvent::class,
918
+            $manager->setupStorage(...),
919
+        );
920
+
921
+        $enabled = $manager->isEnabled();
922
+        if ($enabled) {
923
+            \OC\Encryption\EncryptionEventListener::register(Server::get(IEventDispatcher::class));
924
+        }
925
+    }
926
+
927
+    private static function registerAccountHooks(): void {
928
+        /** @var IEventDispatcher $dispatcher */
929
+        $dispatcher = Server::get(IEventDispatcher::class);
930
+        $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
931
+    }
932
+
933
+    private static function registerAppRestrictionsHooks(): void {
934
+        /** @var \OC\Group\Manager $groupManager */
935
+        $groupManager = Server::get(\OCP\IGroupManager::class);
936
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
937
+            $appManager = Server::get(\OCP\App\IAppManager::class);
938
+            $apps = $appManager->getEnabledAppsForGroup($group);
939
+            foreach ($apps as $appId) {
940
+                $restrictions = $appManager->getAppRestriction($appId);
941
+                if (empty($restrictions)) {
942
+                    continue;
943
+                }
944
+                $key = array_search($group->getGID(), $restrictions);
945
+                unset($restrictions[$key]);
946
+                $restrictions = array_values($restrictions);
947
+                if (empty($restrictions)) {
948
+                    $appManager->disableApp($appId);
949
+                } else {
950
+                    $appManager->enableAppForGroups($appId, $restrictions);
951
+                }
952
+            }
953
+        });
954
+    }
955
+
956
+    private static function registerResourceCollectionHooks(): void {
957
+        \OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class));
958
+    }
959
+
960
+    private static function registerFileReferenceEventListener(): void {
961
+        \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
962
+    }
963
+
964
+    private static function registerRenderReferenceEventListener() {
965
+        \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
966
+    }
967
+
968
+    /**
969
+     * register hooks for sharing
970
+     */
971
+    public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
972
+        if ($systemConfig->getValue('installed')) {
973
+
974
+            $dispatcher = Server::get(IEventDispatcher::class);
975
+            $dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class);
976
+            $dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class);
977
+            $dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class);
978
+        }
979
+    }
980
+
981
+    protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
982
+        // The class loader takes an optional low-latency cache, which MUST be
983
+        // namespaced. The instanceid is used for namespacing, but might be
984
+        // unavailable at this point. Furthermore, it might not be possible to
985
+        // generate an instanceid via \OC_Util::getInstanceId() because the
986
+        // config file may not be writable. As such, we only register a class
987
+        // loader cache if instanceid is available without trying to create one.
988
+        $instanceId = $systemConfig->getValue('instanceid', null);
989
+        if ($instanceId) {
990
+            try {
991
+                $memcacheFactory = Server::get(\OCP\ICacheFactory::class);
992
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
993
+            } catch (\Exception $ex) {
994
+            }
995
+        }
996
+    }
997
+
998
+    /**
999
+     * Handle the request
1000
+     */
1001
+    public static function handleRequest(): void {
1002
+        Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
1003
+        $systemConfig = Server::get(\OC\SystemConfig::class);
1004
+
1005
+        // Check if Nextcloud is installed or in maintenance (update) mode
1006
+        if (!$systemConfig->getValue('installed', false)) {
1007
+            \OC::$server->getSession()->clear();
1008
+            $controller = Server::get(\OC\Core\Controller\SetupController::class);
1009
+            $controller->run($_POST);
1010
+            exit();
1011
+        }
1012
+
1013
+        $request = Server::get(IRequest::class);
1014
+        $requestPath = $request->getRawPathInfo();
1015
+        if ($requestPath === '/heartbeat') {
1016
+            return;
1017
+        }
1018
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
1019
+            self::checkMaintenanceMode($systemConfig);
1020
+
1021
+            if (\OCP\Util::needUpgrade()) {
1022
+                if (function_exists('opcache_reset')) {
1023
+                    opcache_reset();
1024
+                }
1025
+                if (!((bool)$systemConfig->getValue('maintenance', false))) {
1026
+                    self::printUpgradePage($systemConfig);
1027
+                    exit();
1028
+                }
1029
+            }
1030
+        }
1031
+
1032
+        $appManager = Server::get(\OCP\App\IAppManager::class);
1033
+
1034
+        // Always load authentication apps
1035
+        $appManager->loadApps(['authentication']);
1036
+        $appManager->loadApps(['extended_authentication']);
1037
+
1038
+        // Load minimum set of apps
1039
+        if (!\OCP\Util::needUpgrade()
1040
+            && !((bool)$systemConfig->getValue('maintenance', false))) {
1041
+            // For logged-in users: Load everything
1042
+            if (Server::get(IUserSession::class)->isLoggedIn()) {
1043
+                $appManager->loadApps();
1044
+            } else {
1045
+                // For guests: Load only filesystem and logging
1046
+                $appManager->loadApps(['filesystem', 'logging']);
1047
+
1048
+                // Don't try to login when a client is trying to get a OAuth token.
1049
+                // OAuth needs to support basic auth too, so the login is not valid
1050
+                // inside Nextcloud and the Login exception would ruin it.
1051
+                if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1052
+                    self::handleLogin($request);
1053
+                }
1054
+            }
1055
+        }
1056
+
1057
+        if (!self::$CLI) {
1058
+            try {
1059
+                if (!\OCP\Util::needUpgrade()) {
1060
+                    $appManager->loadApps(['filesystem', 'logging']);
1061
+                    $appManager->loadApps();
1062
+                }
1063
+                Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1064
+                return;
1065
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1066
+                //header('HTTP/1.0 404 Not Found');
1067
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1068
+                http_response_code(405);
1069
+                return;
1070
+            }
1071
+        }
1072
+
1073
+        // Handle WebDAV
1074
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1075
+            // not allowed any more to prevent people
1076
+            // mounting this root directly.
1077
+            // Users need to mount remote.php/webdav instead.
1078
+            http_response_code(405);
1079
+            return;
1080
+        }
1081
+
1082
+        // Handle requests for JSON or XML
1083
+        $acceptHeader = $request->getHeader('Accept');
1084
+        if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1085
+            http_response_code(404);
1086
+            return;
1087
+        }
1088
+
1089
+        // Handle resources that can't be found
1090
+        // This prevents browsers from redirecting to the default page and then
1091
+        // attempting to parse HTML as CSS and similar.
1092
+        $destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1093
+        if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1094
+            http_response_code(404);
1095
+            return;
1096
+        }
1097
+
1098
+        // Redirect to the default app or login only as an entry point
1099
+        if ($requestPath === '') {
1100
+            // Someone is logged in
1101
+            if (Server::get(IUserSession::class)->isLoggedIn()) {
1102
+                header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1103
+            } else {
1104
+                // Not handled and not logged in
1105
+                header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1106
+            }
1107
+            return;
1108
+        }
1109
+
1110
+        try {
1111
+            Server::get(\OC\Route\Router::class)->match('/error/404');
1112
+        } catch (\Exception $e) {
1113
+            if (!$e instanceof MethodNotAllowedException) {
1114
+                logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1115
+            }
1116
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
1117
+            Server::get(ITemplateManager::class)->printErrorPage(
1118
+                '404',
1119
+                $l->t('The page could not be found on the server.'),
1120
+                404
1121
+            );
1122
+        }
1123
+    }
1124
+
1125
+    /**
1126
+     * Check login: apache auth, auth token, basic auth
1127
+     */
1128
+    public static function handleLogin(OCP\IRequest $request): bool {
1129
+        if ($request->getHeader('X-Nextcloud-Federation')) {
1130
+            return false;
1131
+        }
1132
+        $userSession = Server::get(\OC\User\Session::class);
1133
+        if (OC_User::handleApacheAuth()) {
1134
+            return true;
1135
+        }
1136
+        if (self::tryAppAPILogin($request)) {
1137
+            return true;
1138
+        }
1139
+        if ($userSession->tryTokenLogin($request)) {
1140
+            return true;
1141
+        }
1142
+        if (isset($_COOKIE['nc_username'])
1143
+            && isset($_COOKIE['nc_token'])
1144
+            && isset($_COOKIE['nc_session_id'])
1145
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1146
+            return true;
1147
+        }
1148
+        if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) {
1149
+            return true;
1150
+        }
1151
+        return false;
1152
+    }
1153
+
1154
+    protected static function handleAuthHeaders(): void {
1155
+        //copy http auth headers for apache+php-fcgid work around
1156
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1157
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1158
+        }
1159
+
1160
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1161
+        $vars = [
1162
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1163
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1164
+        ];
1165
+        foreach ($vars as $var) {
1166
+            if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1167
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1168
+                if (count($credentials) === 2) {
1169
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1170
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1171
+                    break;
1172
+                }
1173
+            }
1174
+        }
1175
+    }
1176
+
1177
+    protected static function tryAppAPILogin(OCP\IRequest $request): bool {
1178
+        if (!$request->getHeader('AUTHORIZATION-APP-API')) {
1179
+            return false;
1180
+        }
1181
+        $appManager = Server::get(OCP\App\IAppManager::class);
1182
+        if (!$appManager->isEnabledForAnyone('app_api')) {
1183
+            return false;
1184
+        }
1185
+        try {
1186
+            $appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class);
1187
+            return $appAPIService->validateExAppRequestToNC($request);
1188
+        } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) {
1189
+            return false;
1190
+        }
1191
+    }
1192 1192
 }
1193 1193
 
1194 1194
 OC::init();
Please login to merge, or discard this patch.