Passed
Push — master ( 741e5e...d13f2d )
by Roeland
61:14 queued 47:07
created
lib/private/legacy/OC_Util.php 1 patch
Indentation   +1411 added lines, -1411 removed lines patch added patch discarded remove patch
@@ -73,1420 +73,1420 @@
 block discarded – undo
73 73
 use OCP\IUserSession;
74 74
 
75 75
 class OC_Util {
76
-	public static $scripts = [];
77
-	public static $styles = [];
78
-	public static $headers = [];
79
-	private static $rootMounted = false;
80
-	private static $fsSetup = false;
81
-
82
-	/** @var array Local cache of version.php */
83
-	private static $versionCache = null;
84
-
85
-	protected static function getAppManager() {
86
-		return \OC::$server->getAppManager();
87
-	}
88
-
89
-	private static function initLocalStorageRootFS() {
90
-		// mount local file backend as root
91
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
92
-		//first set up the local "root" storage
93
-		\OC\Files\Filesystem::initMountManager();
94
-		if (!self::$rootMounted) {
95
-			\OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
96
-			self::$rootMounted = true;
97
-		}
98
-	}
99
-
100
-	/**
101
-	 * mounting an object storage as the root fs will in essence remove the
102
-	 * necessity of a data folder being present.
103
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
104
-	 *
105
-	 * @param array $config containing 'class' and optional 'arguments'
106
-	 * @suppress PhanDeprecatedFunction
107
-	 */
108
-	private static function initObjectStoreRootFS($config) {
109
-		// check misconfiguration
110
-		if (empty($config['class'])) {
111
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
112
-		}
113
-		if (!isset($config['arguments'])) {
114
-			$config['arguments'] = [];
115
-		}
116
-
117
-		// instantiate object store implementation
118
-		$name = $config['class'];
119
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
120
-			$segments = explode('\\', $name);
121
-			OC_App::loadApp(strtolower($segments[1]));
122
-		}
123
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
124
-		// mount with plain / root object store implementation
125
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
126
-
127
-		// mount object storage as root
128
-		\OC\Files\Filesystem::initMountManager();
129
-		if (!self::$rootMounted) {
130
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
131
-			self::$rootMounted = true;
132
-		}
133
-	}
134
-
135
-	/**
136
-	 * mounting an object storage as the root fs will in essence remove the
137
-	 * necessity of a data folder being present.
138
-	 *
139
-	 * @param array $config containing 'class' and optional 'arguments'
140
-	 * @suppress PhanDeprecatedFunction
141
-	 */
142
-	private static function initObjectStoreMultibucketRootFS($config) {
143
-		// check misconfiguration
144
-		if (empty($config['class'])) {
145
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
146
-		}
147
-		if (!isset($config['arguments'])) {
148
-			$config['arguments'] = [];
149
-		}
150
-
151
-		// instantiate object store implementation
152
-		$name = $config['class'];
153
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
154
-			$segments = explode('\\', $name);
155
-			OC_App::loadApp(strtolower($segments[1]));
156
-		}
157
-
158
-		if (!isset($config['arguments']['bucket'])) {
159
-			$config['arguments']['bucket'] = '';
160
-		}
161
-		// put the root FS always in first bucket for multibucket configuration
162
-		$config['arguments']['bucket'] .= '0';
163
-
164
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
165
-		// mount with plain / root object store implementation
166
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
167
-
168
-		// mount object storage as root
169
-		\OC\Files\Filesystem::initMountManager();
170
-		if (!self::$rootMounted) {
171
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
172
-			self::$rootMounted = true;
173
-		}
174
-	}
175
-
176
-	/**
177
-	 * Can be set up
178
-	 *
179
-	 * @param string $user
180
-	 * @return boolean
181
-	 * @description configure the initial filesystem based on the configuration
182
-	 * @suppress PhanDeprecatedFunction
183
-	 * @suppress PhanAccessMethodInternal
184
-	 */
185
-	public static function setupFS($user = '') {
186
-		//setting up the filesystem twice can only lead to trouble
187
-		if (self::$fsSetup) {
188
-			return false;
189
-		}
190
-
191
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
192
-
193
-		// If we are not forced to load a specific user we load the one that is logged in
194
-		if ($user === null) {
195
-			$user = '';
196
-		} elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
197
-			$user = OC_User::getUser();
198
-		}
199
-
200
-		// load all filesystem apps before, so no setup-hook gets lost
201
-		OC_App::loadApps(['filesystem']);
202
-
203
-		// the filesystem will finish when $user is not empty,
204
-		// mark fs setup here to avoid doing the setup from loading
205
-		// OC_Filesystem
206
-		if ($user != '') {
207
-			self::$fsSetup = true;
208
-		}
209
-
210
-		\OC\Files\Filesystem::initMountManager();
211
-
212
-		$prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
213
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
214
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
215
-				/** @var \OC\Files\Storage\Common $storage */
216
-				$storage->setMountOptions($mount->getOptions());
217
-			}
218
-			return $storage;
219
-		});
220
-
221
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
222
-			if (!$mount->getOption('enable_sharing', true)) {
223
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
224
-					'storage' => $storage,
225
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
226
-				]);
227
-			}
228
-			return $storage;
229
-		});
230
-
231
-		// install storage availability wrapper, before most other wrappers
232
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
233
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
234
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
235
-			}
236
-			return $storage;
237
-		});
238
-
239
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
240
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
241
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
242
-			}
243
-			return $storage;
244
-		});
245
-
246
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
247
-			// set up quota for home storages, even for other users
248
-			// which can happen when using sharing
249
-
250
-			/**
251
-			 * @var \OC\Files\Storage\Storage $storage
252
-			 */
253
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
254
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
255
-			) {
256
-				/** @var \OC\Files\Storage\Home $storage */
257
-				if (is_object($storage->getUser())) {
258
-					$quota = OC_Util::getUserQuota($storage->getUser());
259
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
260
-						return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
261
-					}
262
-				}
263
-			}
264
-
265
-			return $storage;
266
-		});
267
-
268
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
269
-			/*
76
+    public static $scripts = [];
77
+    public static $styles = [];
78
+    public static $headers = [];
79
+    private static $rootMounted = false;
80
+    private static $fsSetup = false;
81
+
82
+    /** @var array Local cache of version.php */
83
+    private static $versionCache = null;
84
+
85
+    protected static function getAppManager() {
86
+        return \OC::$server->getAppManager();
87
+    }
88
+
89
+    private static function initLocalStorageRootFS() {
90
+        // mount local file backend as root
91
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
92
+        //first set up the local "root" storage
93
+        \OC\Files\Filesystem::initMountManager();
94
+        if (!self::$rootMounted) {
95
+            \OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
96
+            self::$rootMounted = true;
97
+        }
98
+    }
99
+
100
+    /**
101
+     * mounting an object storage as the root fs will in essence remove the
102
+     * necessity of a data folder being present.
103
+     * TODO make home storage aware of this and use the object storage instead of local disk access
104
+     *
105
+     * @param array $config containing 'class' and optional 'arguments'
106
+     * @suppress PhanDeprecatedFunction
107
+     */
108
+    private static function initObjectStoreRootFS($config) {
109
+        // check misconfiguration
110
+        if (empty($config['class'])) {
111
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
112
+        }
113
+        if (!isset($config['arguments'])) {
114
+            $config['arguments'] = [];
115
+        }
116
+
117
+        // instantiate object store implementation
118
+        $name = $config['class'];
119
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
120
+            $segments = explode('\\', $name);
121
+            OC_App::loadApp(strtolower($segments[1]));
122
+        }
123
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
124
+        // mount with plain / root object store implementation
125
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
126
+
127
+        // mount object storage as root
128
+        \OC\Files\Filesystem::initMountManager();
129
+        if (!self::$rootMounted) {
130
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
131
+            self::$rootMounted = true;
132
+        }
133
+    }
134
+
135
+    /**
136
+     * mounting an object storage as the root fs will in essence remove the
137
+     * necessity of a data folder being present.
138
+     *
139
+     * @param array $config containing 'class' and optional 'arguments'
140
+     * @suppress PhanDeprecatedFunction
141
+     */
142
+    private static function initObjectStoreMultibucketRootFS($config) {
143
+        // check misconfiguration
144
+        if (empty($config['class'])) {
145
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
146
+        }
147
+        if (!isset($config['arguments'])) {
148
+            $config['arguments'] = [];
149
+        }
150
+
151
+        // instantiate object store implementation
152
+        $name = $config['class'];
153
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
154
+            $segments = explode('\\', $name);
155
+            OC_App::loadApp(strtolower($segments[1]));
156
+        }
157
+
158
+        if (!isset($config['arguments']['bucket'])) {
159
+            $config['arguments']['bucket'] = '';
160
+        }
161
+        // put the root FS always in first bucket for multibucket configuration
162
+        $config['arguments']['bucket'] .= '0';
163
+
164
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
165
+        // mount with plain / root object store implementation
166
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
167
+
168
+        // mount object storage as root
169
+        \OC\Files\Filesystem::initMountManager();
170
+        if (!self::$rootMounted) {
171
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
172
+            self::$rootMounted = true;
173
+        }
174
+    }
175
+
176
+    /**
177
+     * Can be set up
178
+     *
179
+     * @param string $user
180
+     * @return boolean
181
+     * @description configure the initial filesystem based on the configuration
182
+     * @suppress PhanDeprecatedFunction
183
+     * @suppress PhanAccessMethodInternal
184
+     */
185
+    public static function setupFS($user = '') {
186
+        //setting up the filesystem twice can only lead to trouble
187
+        if (self::$fsSetup) {
188
+            return false;
189
+        }
190
+
191
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
192
+
193
+        // If we are not forced to load a specific user we load the one that is logged in
194
+        if ($user === null) {
195
+            $user = '';
196
+        } elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
197
+            $user = OC_User::getUser();
198
+        }
199
+
200
+        // load all filesystem apps before, so no setup-hook gets lost
201
+        OC_App::loadApps(['filesystem']);
202
+
203
+        // the filesystem will finish when $user is not empty,
204
+        // mark fs setup here to avoid doing the setup from loading
205
+        // OC_Filesystem
206
+        if ($user != '') {
207
+            self::$fsSetup = true;
208
+        }
209
+
210
+        \OC\Files\Filesystem::initMountManager();
211
+
212
+        $prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
213
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
214
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
215
+                /** @var \OC\Files\Storage\Common $storage */
216
+                $storage->setMountOptions($mount->getOptions());
217
+            }
218
+            return $storage;
219
+        });
220
+
221
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
222
+            if (!$mount->getOption('enable_sharing', true)) {
223
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
224
+                    'storage' => $storage,
225
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
226
+                ]);
227
+            }
228
+            return $storage;
229
+        });
230
+
231
+        // install storage availability wrapper, before most other wrappers
232
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
233
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
234
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
235
+            }
236
+            return $storage;
237
+        });
238
+
239
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
240
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
241
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
242
+            }
243
+            return $storage;
244
+        });
245
+
246
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
247
+            // set up quota for home storages, even for other users
248
+            // which can happen when using sharing
249
+
250
+            /**
251
+             * @var \OC\Files\Storage\Storage $storage
252
+             */
253
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
254
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
255
+            ) {
256
+                /** @var \OC\Files\Storage\Home $storage */
257
+                if (is_object($storage->getUser())) {
258
+                    $quota = OC_Util::getUserQuota($storage->getUser());
259
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
260
+                        return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
261
+                    }
262
+                }
263
+            }
264
+
265
+            return $storage;
266
+        });
267
+
268
+        \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
269
+            /*
270 270
 			 * Do not allow any operations that modify the storage
271 271
 			 */
272
-			if ($mount->getOption('readonly', false)) {
273
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
274
-					'storage' => $storage,
275
-					'mask' => \OCP\Constants::PERMISSION_ALL & ~(
276
-						\OCP\Constants::PERMISSION_UPDATE |
277
-						\OCP\Constants::PERMISSION_CREATE |
278
-						\OCP\Constants::PERMISSION_DELETE
279
-					),
280
-				]);
281
-			}
282
-			return $storage;
283
-		});
284
-
285
-		OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
286
-
287
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
288
-
289
-		//check if we are using an object storage
290
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
291
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
292
-
293
-		// use the same order as in ObjectHomeMountProvider
294
-		if (isset($objectStoreMultibucket)) {
295
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
296
-		} elseif (isset($objectStore)) {
297
-			self::initObjectStoreRootFS($objectStore);
298
-		} else {
299
-			self::initLocalStorageRootFS();
300
-		}
301
-
302
-		/** @var \OCP\Files\Config\IMountProviderCollection $mountProviderCollection */
303
-		$mountProviderCollection = \OC::$server->query(\OCP\Files\Config\IMountProviderCollection::class);
304
-		$rootMountProviders = $mountProviderCollection->getRootMounts();
305
-
306
-		/** @var \OC\Files\Mount\Manager $mountManager */
307
-		$mountManager = \OC\Files\Filesystem::getMountManager();
308
-		foreach ($rootMountProviders as $rootMountProvider) {
309
-			$mountManager->addMount($rootMountProvider);
310
-		}
311
-
312
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
313
-			\OC::$server->getEventLogger()->end('setup_fs');
314
-			return false;
315
-		}
316
-
317
-		//if we aren't logged in, there is no use to set up the filesystem
318
-		if ($user != "") {
319
-			$userDir = '/' . $user . '/files';
320
-
321
-			//jail the user into his "home" directory
322
-			\OC\Files\Filesystem::init($user, $userDir);
323
-
324
-			OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
325
-		}
326
-		\OC::$server->getEventLogger()->end('setup_fs');
327
-		return true;
328
-	}
329
-
330
-	/**
331
-	 * check if a password is required for each public link
332
-	 *
333
-	 * @return boolean
334
-	 * @suppress PhanDeprecatedFunction
335
-	 */
336
-	public static function isPublicLinkPasswordRequired() {
337
-		$enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
338
-		return $enforcePassword === 'yes';
339
-	}
340
-
341
-	/**
342
-	 * check if sharing is disabled for the current user
343
-	 * @param IConfig $config
344
-	 * @param IGroupManager $groupManager
345
-	 * @param IUser|null $user
346
-	 * @return bool
347
-	 */
348
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
349
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
350
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
351
-			$excludedGroups = json_decode($groupsList);
352
-			if (is_null($excludedGroups)) {
353
-				$excludedGroups = explode(',', $groupsList);
354
-				$newValue = json_encode($excludedGroups);
355
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
356
-			}
357
-			$usersGroups = $groupManager->getUserGroupIds($user);
358
-			if (!empty($usersGroups)) {
359
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
360
-				// if the user is only in groups which are disabled for sharing then
361
-				// sharing is also disabled for the user
362
-				if (empty($remainingGroups)) {
363
-					return true;
364
-				}
365
-			}
366
-		}
367
-		return false;
368
-	}
369
-
370
-	/**
371
-	 * check if share API enforces a default expire date
372
-	 *
373
-	 * @return boolean
374
-	 * @suppress PhanDeprecatedFunction
375
-	 */
376
-	public static function isDefaultExpireDateEnforced() {
377
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
378
-		$enforceDefaultExpireDate = false;
379
-		if ($isDefaultExpireDateEnabled === 'yes') {
380
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
381
-			$enforceDefaultExpireDate = $value === 'yes';
382
-		}
383
-
384
-		return $enforceDefaultExpireDate;
385
-	}
386
-
387
-	/**
388
-	 * Get the quota of a user
389
-	 *
390
-	 * @param IUser|null $user
391
-	 * @return float Quota bytes
392
-	 */
393
-	public static function getUserQuota(?IUser $user) {
394
-		if (is_null($user)) {
395
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
396
-		}
397
-		$userQuota = $user->getQuota();
398
-		if ($userQuota === 'none') {
399
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
400
-		}
401
-		return OC_Helper::computerFileSize($userQuota);
402
-	}
403
-
404
-	/**
405
-	 * copies the skeleton to the users /files
406
-	 *
407
-	 * @param string $userId
408
-	 * @param \OCP\Files\Folder $userDirectory
409
-	 * @throws \OCP\Files\NotFoundException
410
-	 * @throws \OCP\Files\NotPermittedException
411
-	 * @suppress PhanDeprecatedFunction
412
-	 */
413
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
414
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
415
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
416
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
417
-
418
-		if (!file_exists($skeletonDirectory)) {
419
-			$dialectStart = strpos($userLang, '_');
420
-			if ($dialectStart !== false) {
421
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
422
-			}
423
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
424
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
425
-			}
426
-			if (!file_exists($skeletonDirectory)) {
427
-				$skeletonDirectory = '';
428
-			}
429
-		}
430
-
431
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
432
-
433
-		if ($instanceId === null) {
434
-			throw new \RuntimeException('no instance id!');
435
-		}
436
-		$appdata = 'appdata_' . $instanceId;
437
-		if ($userId === $appdata) {
438
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
439
-		}
440
-
441
-		if (!empty($skeletonDirectory)) {
442
-			\OCP\Util::writeLog(
443
-				'files_skeleton',
444
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
445
-				ILogger::DEBUG
446
-			);
447
-			self::copyr($skeletonDirectory, $userDirectory);
448
-			// update the file cache
449
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
450
-		}
451
-	}
452
-
453
-	/**
454
-	 * copies a directory recursively by using streams
455
-	 *
456
-	 * @param string $source
457
-	 * @param \OCP\Files\Folder $target
458
-	 * @return void
459
-	 */
460
-	public static function copyr($source, \OCP\Files\Folder $target) {
461
-		$logger = \OC::$server->getLogger();
462
-
463
-		// Verify if folder exists
464
-		$dir = opendir($source);
465
-		if ($dir === false) {
466
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
467
-			return;
468
-		}
469
-
470
-		// Copy the files
471
-		while (false !== ($file = readdir($dir))) {
472
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
473
-				if (is_dir($source . '/' . $file)) {
474
-					$child = $target->newFolder($file);
475
-					self::copyr($source . '/' . $file, $child);
476
-				} else {
477
-					$child = $target->newFile($file);
478
-					$sourceStream = fopen($source . '/' . $file, 'r');
479
-					if ($sourceStream === false) {
480
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
481
-						closedir($dir);
482
-						return;
483
-					}
484
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
485
-				}
486
-			}
487
-		}
488
-		closedir($dir);
489
-	}
490
-
491
-	/**
492
-	 * @return void
493
-	 * @suppress PhanUndeclaredMethod
494
-	 */
495
-	public static function tearDownFS() {
496
-		\OC\Files\Filesystem::tearDown();
497
-		\OC::$server->getRootFolder()->clearCache();
498
-		self::$fsSetup = false;
499
-		self::$rootMounted = false;
500
-	}
501
-
502
-	/**
503
-	 * get the current installed version of ownCloud
504
-	 *
505
-	 * @return array
506
-	 */
507
-	public static function getVersion() {
508
-		OC_Util::loadVersion();
509
-		return self::$versionCache['OC_Version'];
510
-	}
511
-
512
-	/**
513
-	 * get the current installed version string of ownCloud
514
-	 *
515
-	 * @return string
516
-	 */
517
-	public static function getVersionString() {
518
-		OC_Util::loadVersion();
519
-		return self::$versionCache['OC_VersionString'];
520
-	}
521
-
522
-	/**
523
-	 * @deprecated the value is of no use anymore
524
-	 * @return string
525
-	 */
526
-	public static function getEditionString() {
527
-		return '';
528
-	}
529
-
530
-	/**
531
-	 * @description get the update channel of the current installed of ownCloud.
532
-	 * @return string
533
-	 */
534
-	public static function getChannel() {
535
-		OC_Util::loadVersion();
536
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
537
-	}
538
-
539
-	/**
540
-	 * @description get the build number of the current installed of ownCloud.
541
-	 * @return string
542
-	 */
543
-	public static function getBuild() {
544
-		OC_Util::loadVersion();
545
-		return self::$versionCache['OC_Build'];
546
-	}
547
-
548
-	/**
549
-	 * @description load the version.php into the session as cache
550
-	 * @suppress PhanUndeclaredVariable
551
-	 */
552
-	private static function loadVersion() {
553
-		if (self::$versionCache !== null) {
554
-			return;
555
-		}
556
-
557
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
558
-		require OC::$SERVERROOT . '/version.php';
559
-		/** @var int $timestamp */
560
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
561
-		/** @var string $OC_Version */
562
-		self::$versionCache['OC_Version'] = $OC_Version;
563
-		/** @var string $OC_VersionString */
564
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
565
-		/** @var string $OC_Build */
566
-		self::$versionCache['OC_Build'] = $OC_Build;
567
-
568
-		/** @var string $OC_Channel */
569
-		self::$versionCache['OC_Channel'] = $OC_Channel;
570
-	}
571
-
572
-	/**
573
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
574
-	 *
575
-	 * @param string $application application to get the files from
576
-	 * @param string $directory directory within this application (css, js, vendor, etc)
577
-	 * @param string $file the file inside of the above folder
578
-	 * @return string the path
579
-	 */
580
-	private static function generatePath($application, $directory, $file) {
581
-		if (is_null($file)) {
582
-			$file = $application;
583
-			$application = "";
584
-		}
585
-		if (!empty($application)) {
586
-			return "$application/$directory/$file";
587
-		} else {
588
-			return "$directory/$file";
589
-		}
590
-	}
591
-
592
-	/**
593
-	 * add a javascript file
594
-	 *
595
-	 * @param string $application application id
596
-	 * @param string|null $file filename
597
-	 * @param bool $prepend prepend the Script to the beginning of the list
598
-	 * @return void
599
-	 */
600
-	public static function addScript($application, $file = null, $prepend = false) {
601
-		$path = OC_Util::generatePath($application, 'js', $file);
602
-
603
-		// core js files need separate handling
604
-		if ($application !== 'core' && $file !== null) {
605
-			self::addTranslations($application);
606
-		}
607
-		self::addExternalResource($application, $prepend, $path, "script");
608
-	}
609
-
610
-	/**
611
-	 * add a javascript file from the vendor sub folder
612
-	 *
613
-	 * @param string $application application id
614
-	 * @param string|null $file filename
615
-	 * @param bool $prepend prepend the Script to the beginning of the list
616
-	 * @return void
617
-	 */
618
-	public static function addVendorScript($application, $file = null, $prepend = false) {
619
-		$path = OC_Util::generatePath($application, 'vendor', $file);
620
-		self::addExternalResource($application, $prepend, $path, "script");
621
-	}
622
-
623
-	/**
624
-	 * add a translation JS file
625
-	 *
626
-	 * @param string $application application id
627
-	 * @param string|null $languageCode language code, defaults to the current language
628
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
629
-	 */
630
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
631
-		if (is_null($languageCode)) {
632
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
633
-		}
634
-		if (!empty($application)) {
635
-			$path = "$application/l10n/$languageCode";
636
-		} else {
637
-			$path = "l10n/$languageCode";
638
-		}
639
-		self::addExternalResource($application, $prepend, $path, "script");
640
-	}
641
-
642
-	/**
643
-	 * add a css file
644
-	 *
645
-	 * @param string $application application id
646
-	 * @param string|null $file filename
647
-	 * @param bool $prepend prepend the Style to the beginning of the list
648
-	 * @return void
649
-	 */
650
-	public static function addStyle($application, $file = null, $prepend = false) {
651
-		$path = OC_Util::generatePath($application, 'css', $file);
652
-		self::addExternalResource($application, $prepend, $path, "style");
653
-	}
654
-
655
-	/**
656
-	 * add a css file from the vendor sub folder
657
-	 *
658
-	 * @param string $application application id
659
-	 * @param string|null $file filename
660
-	 * @param bool $prepend prepend the Style to the beginning of the list
661
-	 * @return void
662
-	 */
663
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
664
-		$path = OC_Util::generatePath($application, 'vendor', $file);
665
-		self::addExternalResource($application, $prepend, $path, "style");
666
-	}
667
-
668
-	/**
669
-	 * add an external resource css/js file
670
-	 *
671
-	 * @param string $application application id
672
-	 * @param bool $prepend prepend the file to the beginning of the list
673
-	 * @param string $path
674
-	 * @param string $type (script or style)
675
-	 * @return void
676
-	 */
677
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
678
-		if ($type === "style") {
679
-			if (!in_array($path, self::$styles)) {
680
-				if ($prepend === true) {
681
-					array_unshift(self::$styles, $path);
682
-				} else {
683
-					self::$styles[] = $path;
684
-				}
685
-			}
686
-		} elseif ($type === "script") {
687
-			if (!in_array($path, self::$scripts)) {
688
-				if ($prepend === true) {
689
-					array_unshift(self::$scripts, $path);
690
-				} else {
691
-					self::$scripts [] = $path;
692
-				}
693
-			}
694
-		}
695
-	}
696
-
697
-	/**
698
-	 * Add a custom element to the header
699
-	 * If $text is null then the element will be written as empty element.
700
-	 * So use "" to get a closing tag.
701
-	 * @param string $tag tag name of the element
702
-	 * @param array $attributes array of attributes for the element
703
-	 * @param string $text the text content for the element
704
-	 * @param bool $prepend prepend the header to the beginning of the list
705
-	 */
706
-	public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
707
-		$header = [
708
-			'tag' => $tag,
709
-			'attributes' => $attributes,
710
-			'text' => $text
711
-		];
712
-		if ($prepend === true) {
713
-			array_unshift(self::$headers, $header);
714
-		} else {
715
-			self::$headers[] = $header;
716
-		}
717
-	}
718
-
719
-	/**
720
-	 * check if the current server configuration is suitable for ownCloud
721
-	 *
722
-	 * @param \OC\SystemConfig $config
723
-	 * @return array arrays with error messages and hints
724
-	 */
725
-	public static function checkServer(\OC\SystemConfig $config) {
726
-		$l = \OC::$server->getL10N('lib');
727
-		$errors = [];
728
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
729
-
730
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
731
-			// this check needs to be done every time
732
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
733
-		}
734
-
735
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
736
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
737
-			return $errors;
738
-		}
739
-
740
-		$webServerRestart = false;
741
-		$setup = new \OC\Setup(
742
-			$config,
743
-			\OC::$server->get(IniGetWrapper::class),
744
-			\OC::$server->getL10N('lib'),
745
-			\OC::$server->query(\OCP\Defaults::class),
746
-			\OC::$server->getLogger(),
747
-			\OC::$server->getSecureRandom(),
748
-			\OC::$server->query(\OC\Installer::class)
749
-		);
750
-
751
-		$urlGenerator = \OC::$server->getURLGenerator();
752
-
753
-		$availableDatabases = $setup->getSupportedDatabases();
754
-		if (empty($availableDatabases)) {
755
-			$errors[] = [
756
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
757
-				'hint' => '' //TODO: sane hint
758
-			];
759
-			$webServerRestart = true;
760
-		}
761
-
762
-		// Check if config folder is writable.
763
-		if (!OC_Helper::isReadOnlyConfigEnabled()) {
764
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
765
-				$errors[] = [
766
-					'error' => $l->t('Cannot write into "config" directory'),
767
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
768
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
769
-						. $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',
770
-						[ $urlGenerator->linkToDocs('admin-config') ])
771
-				];
772
-			}
773
-		}
774
-
775
-		// Check if there is a writable install folder.
776
-		if ($config->getValue('appstoreenabled', true)) {
777
-			if (OC_App::getInstallPath() === null
778
-				|| !is_writable(OC_App::getInstallPath())
779
-				|| !is_readable(OC_App::getInstallPath())
780
-			) {
781
-				$errors[] = [
782
-					'error' => $l->t('Cannot write into "apps" directory'),
783
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
784
-						. ' or disabling the appstore in the config file.')
785
-				];
786
-			}
787
-		}
788
-		// Create root dir.
789
-		if ($config->getValue('installed', false)) {
790
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
791
-				$success = @mkdir($CONFIG_DATADIRECTORY);
792
-				if ($success) {
793
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
794
-				} else {
795
-					$errors[] = [
796
-						'error' => $l->t('Cannot create "data" directory'),
797
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
798
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
799
-					];
800
-				}
801
-			} elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
802
-				// is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
803
-				$testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
804
-				$handle = fopen($testFile, 'w');
805
-				if (!$handle || fwrite($handle, 'Test write operation') === false) {
806
-					$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
807
-						[$urlGenerator->linkToDocs('admin-dir_permissions')]);
808
-					$errors[] = [
809
-						'error' => 'Your data directory is not writable',
810
-						'hint' => $permissionsHint
811
-					];
812
-				} else {
813
-					fclose($handle);
814
-					unlink($testFile);
815
-				}
816
-			} else {
817
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
818
-			}
819
-		}
820
-
821
-		if (!OC_Util::isSetLocaleWorking()) {
822
-			$errors[] = [
823
-				'error' => $l->t('Setting locale to %s failed',
824
-					['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
825
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
826
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
827
-			];
828
-		}
829
-
830
-		// Contains the dependencies that should be checked against
831
-		// classes = class_exists
832
-		// functions = function_exists
833
-		// defined = defined
834
-		// ini = ini_get
835
-		// If the dependency is not found the missing module name is shown to the EndUser
836
-		// When adding new checks always verify that they pass on Travis as well
837
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
838
-		$dependencies = [
839
-			'classes' => [
840
-				'ZipArchive' => 'zip',
841
-				'DOMDocument' => 'dom',
842
-				'XMLWriter' => 'XMLWriter',
843
-				'XMLReader' => 'XMLReader',
844
-			],
845
-			'functions' => [
846
-				'xml_parser_create' => 'libxml',
847
-				'mb_strcut' => 'mbstring',
848
-				'ctype_digit' => 'ctype',
849
-				'json_encode' => 'JSON',
850
-				'gd_info' => 'GD',
851
-				'gzencode' => 'zlib',
852
-				'iconv' => 'iconv',
853
-				'simplexml_load_string' => 'SimpleXML',
854
-				'hash' => 'HASH Message Digest Framework',
855
-				'curl_init' => 'cURL',
856
-				'openssl_verify' => 'OpenSSL',
857
-			],
858
-			'defined' => [
859
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
860
-			],
861
-			'ini' => [
862
-				'default_charset' => 'UTF-8',
863
-			],
864
-		];
865
-		$missingDependencies = [];
866
-		$invalidIniSettings = [];
867
-
868
-		$iniWrapper = \OC::$server->get(IniGetWrapper::class);
869
-		foreach ($dependencies['classes'] as $class => $module) {
870
-			if (!class_exists($class)) {
871
-				$missingDependencies[] = $module;
872
-			}
873
-		}
874
-		foreach ($dependencies['functions'] as $function => $module) {
875
-			if (!function_exists($function)) {
876
-				$missingDependencies[] = $module;
877
-			}
878
-		}
879
-		foreach ($dependencies['defined'] as $defined => $module) {
880
-			if (!defined($defined)) {
881
-				$missingDependencies[] = $module;
882
-			}
883
-		}
884
-		foreach ($dependencies['ini'] as $setting => $expected) {
885
-			if (is_bool($expected)) {
886
-				if ($iniWrapper->getBool($setting) !== $expected) {
887
-					$invalidIniSettings[] = [$setting, $expected];
888
-				}
889
-			}
890
-			if (is_int($expected)) {
891
-				if ($iniWrapper->getNumeric($setting) !== $expected) {
892
-					$invalidIniSettings[] = [$setting, $expected];
893
-				}
894
-			}
895
-			if (is_string($expected)) {
896
-				if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
897
-					$invalidIniSettings[] = [$setting, $expected];
898
-				}
899
-			}
900
-		}
901
-
902
-		foreach ($missingDependencies as $missingDependency) {
903
-			$errors[] = [
904
-				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
905
-				'hint' => $l->t('Please ask your server administrator to install the module.'),
906
-			];
907
-			$webServerRestart = true;
908
-		}
909
-		foreach ($invalidIniSettings as $setting) {
910
-			if (is_bool($setting[1])) {
911
-				$setting[1] = $setting[1] ? 'on' : 'off';
912
-			}
913
-			$errors[] = [
914
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
915
-				'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
916
-			];
917
-			$webServerRestart = true;
918
-		}
919
-
920
-		/**
921
-		 * The mbstring.func_overload check can only be performed if the mbstring
922
-		 * module is installed as it will return null if the checking setting is
923
-		 * not available and thus a check on the boolean value fails.
924
-		 *
925
-		 * TODO: Should probably be implemented in the above generic dependency
926
-		 *       check somehow in the long-term.
927
-		 */
928
-		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
929
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
930
-			$errors[] = [
931
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
932
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
933
-			];
934
-		}
935
-
936
-		if (function_exists('xml_parser_create') &&
937
-			LIBXML_LOADED_VERSION < 20700) {
938
-			$version = LIBXML_LOADED_VERSION;
939
-			$major = floor($version / 10000);
940
-			$version -= ($major * 10000);
941
-			$minor = floor($version / 100);
942
-			$version -= ($minor * 100);
943
-			$patch = $version;
944
-			$errors[] = [
945
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
946
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
947
-			];
948
-		}
949
-
950
-		if (!self::isAnnotationsWorking()) {
951
-			$errors[] = [
952
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
953
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
954
-			];
955
-		}
956
-
957
-		if (!\OC::$CLI && $webServerRestart) {
958
-			$errors[] = [
959
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
960
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
961
-			];
962
-		}
963
-
964
-		$errors = array_merge($errors, self::checkDatabaseVersion());
965
-
966
-		// Cache the result of this function
967
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
968
-
969
-		return $errors;
970
-	}
971
-
972
-	/**
973
-	 * Check the database version
974
-	 *
975
-	 * @return array errors array
976
-	 */
977
-	public static function checkDatabaseVersion() {
978
-		$l = \OC::$server->getL10N('lib');
979
-		$errors = [];
980
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
981
-		if ($dbType === 'pgsql') {
982
-			// check PostgreSQL version
983
-			try {
984
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
985
-				$data = $result->fetchRow();
986
-				$result->closeCursor();
987
-				if (isset($data['server_version'])) {
988
-					$version = $data['server_version'];
989
-					if (version_compare($version, '9.0.0', '<')) {
990
-						$errors[] = [
991
-							'error' => $l->t('PostgreSQL >= 9 required'),
992
-							'hint' => $l->t('Please upgrade your database version')
993
-						];
994
-					}
995
-				}
996
-			} catch (\Doctrine\DBAL\DBALException $e) {
997
-				$logger = \OC::$server->getLogger();
998
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
999
-				$logger->logException($e);
1000
-			}
1001
-		}
1002
-		return $errors;
1003
-	}
1004
-
1005
-	/**
1006
-	 * Check for correct file permissions of data directory
1007
-	 *
1008
-	 * @param string $dataDirectory
1009
-	 * @return array arrays with error messages and hints
1010
-	 */
1011
-	public static function checkDataDirectoryPermissions($dataDirectory) {
1012
-		if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1013
-			return  [];
1014
-		}
1015
-
1016
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1017
-		if (substr($perms, -1) !== '0') {
1018
-			chmod($dataDirectory, 0770);
1019
-			clearstatcache();
1020
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1021
-			if ($perms[2] !== '0') {
1022
-				$l = \OC::$server->getL10N('lib');
1023
-				return [[
1024
-					'error' => $l->t('Your data directory is readable by other users'),
1025
-					'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1026
-				]];
1027
-			}
1028
-		}
1029
-		return [];
1030
-	}
1031
-
1032
-	/**
1033
-	 * Check that the data directory exists and is valid by
1034
-	 * checking the existence of the ".ocdata" file.
1035
-	 *
1036
-	 * @param string $dataDirectory data directory path
1037
-	 * @return array errors found
1038
-	 */
1039
-	public static function checkDataDirectoryValidity($dataDirectory) {
1040
-		$l = \OC::$server->getL10N('lib');
1041
-		$errors = [];
1042
-		if ($dataDirectory[0] !== '/') {
1043
-			$errors[] = [
1044
-				'error' => $l->t('Your data directory must be an absolute path'),
1045
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1046
-			];
1047
-		}
1048
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1049
-			$errors[] = [
1050
-				'error' => $l->t('Your data directory is invalid'),
1051
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1052
-					' in the root of the data directory.')
1053
-			];
1054
-		}
1055
-		return $errors;
1056
-	}
1057
-
1058
-	/**
1059
-	 * Check if the user is logged in, redirects to home if not. With
1060
-	 * redirect URL parameter to the request URI.
1061
-	 *
1062
-	 * @return void
1063
-	 */
1064
-	public static function checkLoggedIn() {
1065
-		// Check if we are a user
1066
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1067
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1068
-						'core.login.showLoginForm',
1069
-						[
1070
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1071
-						]
1072
-					)
1073
-			);
1074
-			exit();
1075
-		}
1076
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1077
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1078
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1079
-			exit();
1080
-		}
1081
-	}
1082
-
1083
-	/**
1084
-	 * Check if the user is a admin, redirects to home if not
1085
-	 *
1086
-	 * @return void
1087
-	 */
1088
-	public static function checkAdminUser() {
1089
-		OC_Util::checkLoggedIn();
1090
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1091
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1092
-			exit();
1093
-		}
1094
-	}
1095
-
1096
-	/**
1097
-	 * Returns the URL of the default page
1098
-	 * based on the system configuration and
1099
-	 * the apps visible for the current user
1100
-	 *
1101
-	 * @return string URL
1102
-	 * @suppress PhanDeprecatedFunction
1103
-	 */
1104
-	public static function getDefaultPageUrl() {
1105
-		/** @var IConfig $config */
1106
-		$config = \OC::$server->get(IConfig::class);
1107
-		$urlGenerator = \OC::$server->getURLGenerator();
1108
-		// Deny the redirect if the URL contains a @
1109
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1110
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1111
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1112
-		} else {
1113
-			$defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1114
-			if ($defaultPage) {
1115
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1116
-			} else {
1117
-				$appId = 'files';
1118
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'dashboard,files'));
1119
-
1120
-				/** @var IUserSession $userSession */
1121
-				$userSession = \OC::$server->get(IUserSession::class);
1122
-				$user = $userSession->getUser();
1123
-				if ($user) {
1124
-					$userDefaultApps = explode(',', $config->getUserValue($user->getUID(), 'core', 'defaultapp'));
1125
-					$defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
1126
-				}
1127
-
1128
-				// find the first app that is enabled for the current user
1129
-				foreach ($defaultApps as $defaultApp) {
1130
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1131
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1132
-						$appId = $defaultApp;
1133
-						break;
1134
-					}
1135
-				}
1136
-
1137
-				if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1138
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1139
-				} else {
1140
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1141
-				}
1142
-			}
1143
-		}
1144
-		return $location;
1145
-	}
1146
-
1147
-	/**
1148
-	 * Redirect to the user default page
1149
-	 *
1150
-	 * @return void
1151
-	 */
1152
-	public static function redirectToDefaultPage() {
1153
-		$location = self::getDefaultPageUrl();
1154
-		header('Location: ' . $location);
1155
-		exit();
1156
-	}
1157
-
1158
-	/**
1159
-	 * get an id unique for this instance
1160
-	 *
1161
-	 * @return string
1162
-	 */
1163
-	public static function getInstanceId() {
1164
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1165
-		if (is_null($id)) {
1166
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1167
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1168
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1169
-		}
1170
-		return $id;
1171
-	}
1172
-
1173
-	/**
1174
-	 * Public function to sanitize HTML
1175
-	 *
1176
-	 * This function is used to sanitize HTML and should be applied on any
1177
-	 * string or array of strings before displaying it on a web page.
1178
-	 *
1179
-	 * @param string|array $value
1180
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1181
-	 */
1182
-	public static function sanitizeHTML($value) {
1183
-		if (is_array($value)) {
1184
-			$value = array_map(function ($value) {
1185
-				return self::sanitizeHTML($value);
1186
-			}, $value);
1187
-		} else {
1188
-			// Specify encoding for PHP<5.4
1189
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1190
-		}
1191
-		return $value;
1192
-	}
1193
-
1194
-	/**
1195
-	 * Public function to encode url parameters
1196
-	 *
1197
-	 * This function is used to encode path to file before output.
1198
-	 * Encoding is done according to RFC 3986 with one exception:
1199
-	 * Character '/' is preserved as is.
1200
-	 *
1201
-	 * @param string $component part of URI to encode
1202
-	 * @return string
1203
-	 */
1204
-	public static function encodePath($component) {
1205
-		$encoded = rawurlencode($component);
1206
-		$encoded = str_replace('%2F', '/', $encoded);
1207
-		return $encoded;
1208
-	}
1209
-
1210
-
1211
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1212
-		// php dev server does not support htaccess
1213
-		if (php_sapi_name() === 'cli-server') {
1214
-			return false;
1215
-		}
1216
-
1217
-		// testdata
1218
-		$fileName = '/htaccesstest.txt';
1219
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1220
-
1221
-		// creating a test file
1222
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1223
-
1224
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1225
-			return false;
1226
-		}
1227
-
1228
-		$fp = @fopen($testFile, 'w');
1229
-		if (!$fp) {
1230
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1231
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1232
-		}
1233
-		fwrite($fp, $testContent);
1234
-		fclose($fp);
1235
-
1236
-		return $testContent;
1237
-	}
1238
-
1239
-	/**
1240
-	 * Check if the .htaccess file is working
1241
-	 * @param \OCP\IConfig $config
1242
-	 * @return bool
1243
-	 * @throws Exception
1244
-	 * @throws \OC\HintException If the test file can't get written.
1245
-	 */
1246
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1247
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1248
-			return true;
1249
-		}
1250
-
1251
-		$testContent = $this->createHtaccessTestFile($config);
1252
-		if ($testContent === false) {
1253
-			return false;
1254
-		}
1255
-
1256
-		$fileName = '/htaccesstest.txt';
1257
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1258
-
1259
-		// accessing the file via http
1260
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1261
-		try {
1262
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1263
-		} catch (\Exception $e) {
1264
-			$content = false;
1265
-		}
1266
-
1267
-		if (strpos($url, 'https:') === 0) {
1268
-			$url = 'http:' . substr($url, 6);
1269
-		} else {
1270
-			$url = 'https:' . substr($url, 5);
1271
-		}
1272
-
1273
-		try {
1274
-			$fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1275
-		} catch (\Exception $e) {
1276
-			$fallbackContent = false;
1277
-		}
1278
-
1279
-		// cleanup
1280
-		@unlink($testFile);
1281
-
1282
-		/*
272
+            if ($mount->getOption('readonly', false)) {
273
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
274
+                    'storage' => $storage,
275
+                    'mask' => \OCP\Constants::PERMISSION_ALL & ~(
276
+                        \OCP\Constants::PERMISSION_UPDATE |
277
+                        \OCP\Constants::PERMISSION_CREATE |
278
+                        \OCP\Constants::PERMISSION_DELETE
279
+                    ),
280
+                ]);
281
+            }
282
+            return $storage;
283
+        });
284
+
285
+        OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
286
+
287
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
288
+
289
+        //check if we are using an object storage
290
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
291
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
292
+
293
+        // use the same order as in ObjectHomeMountProvider
294
+        if (isset($objectStoreMultibucket)) {
295
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
296
+        } elseif (isset($objectStore)) {
297
+            self::initObjectStoreRootFS($objectStore);
298
+        } else {
299
+            self::initLocalStorageRootFS();
300
+        }
301
+
302
+        /** @var \OCP\Files\Config\IMountProviderCollection $mountProviderCollection */
303
+        $mountProviderCollection = \OC::$server->query(\OCP\Files\Config\IMountProviderCollection::class);
304
+        $rootMountProviders = $mountProviderCollection->getRootMounts();
305
+
306
+        /** @var \OC\Files\Mount\Manager $mountManager */
307
+        $mountManager = \OC\Files\Filesystem::getMountManager();
308
+        foreach ($rootMountProviders as $rootMountProvider) {
309
+            $mountManager->addMount($rootMountProvider);
310
+        }
311
+
312
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
313
+            \OC::$server->getEventLogger()->end('setup_fs');
314
+            return false;
315
+        }
316
+
317
+        //if we aren't logged in, there is no use to set up the filesystem
318
+        if ($user != "") {
319
+            $userDir = '/' . $user . '/files';
320
+
321
+            //jail the user into his "home" directory
322
+            \OC\Files\Filesystem::init($user, $userDir);
323
+
324
+            OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
325
+        }
326
+        \OC::$server->getEventLogger()->end('setup_fs');
327
+        return true;
328
+    }
329
+
330
+    /**
331
+     * check if a password is required for each public link
332
+     *
333
+     * @return boolean
334
+     * @suppress PhanDeprecatedFunction
335
+     */
336
+    public static function isPublicLinkPasswordRequired() {
337
+        $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
338
+        return $enforcePassword === 'yes';
339
+    }
340
+
341
+    /**
342
+     * check if sharing is disabled for the current user
343
+     * @param IConfig $config
344
+     * @param IGroupManager $groupManager
345
+     * @param IUser|null $user
346
+     * @return bool
347
+     */
348
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
349
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
350
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
351
+            $excludedGroups = json_decode($groupsList);
352
+            if (is_null($excludedGroups)) {
353
+                $excludedGroups = explode(',', $groupsList);
354
+                $newValue = json_encode($excludedGroups);
355
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
356
+            }
357
+            $usersGroups = $groupManager->getUserGroupIds($user);
358
+            if (!empty($usersGroups)) {
359
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
360
+                // if the user is only in groups which are disabled for sharing then
361
+                // sharing is also disabled for the user
362
+                if (empty($remainingGroups)) {
363
+                    return true;
364
+                }
365
+            }
366
+        }
367
+        return false;
368
+    }
369
+
370
+    /**
371
+     * check if share API enforces a default expire date
372
+     *
373
+     * @return boolean
374
+     * @suppress PhanDeprecatedFunction
375
+     */
376
+    public static function isDefaultExpireDateEnforced() {
377
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
378
+        $enforceDefaultExpireDate = false;
379
+        if ($isDefaultExpireDateEnabled === 'yes') {
380
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
381
+            $enforceDefaultExpireDate = $value === 'yes';
382
+        }
383
+
384
+        return $enforceDefaultExpireDate;
385
+    }
386
+
387
+    /**
388
+     * Get the quota of a user
389
+     *
390
+     * @param IUser|null $user
391
+     * @return float Quota bytes
392
+     */
393
+    public static function getUserQuota(?IUser $user) {
394
+        if (is_null($user)) {
395
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
396
+        }
397
+        $userQuota = $user->getQuota();
398
+        if ($userQuota === 'none') {
399
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
400
+        }
401
+        return OC_Helper::computerFileSize($userQuota);
402
+    }
403
+
404
+    /**
405
+     * copies the skeleton to the users /files
406
+     *
407
+     * @param string $userId
408
+     * @param \OCP\Files\Folder $userDirectory
409
+     * @throws \OCP\Files\NotFoundException
410
+     * @throws \OCP\Files\NotPermittedException
411
+     * @suppress PhanDeprecatedFunction
412
+     */
413
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
414
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
415
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
416
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
417
+
418
+        if (!file_exists($skeletonDirectory)) {
419
+            $dialectStart = strpos($userLang, '_');
420
+            if ($dialectStart !== false) {
421
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
422
+            }
423
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
424
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
425
+            }
426
+            if (!file_exists($skeletonDirectory)) {
427
+                $skeletonDirectory = '';
428
+            }
429
+        }
430
+
431
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
432
+
433
+        if ($instanceId === null) {
434
+            throw new \RuntimeException('no instance id!');
435
+        }
436
+        $appdata = 'appdata_' . $instanceId;
437
+        if ($userId === $appdata) {
438
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
439
+        }
440
+
441
+        if (!empty($skeletonDirectory)) {
442
+            \OCP\Util::writeLog(
443
+                'files_skeleton',
444
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
445
+                ILogger::DEBUG
446
+            );
447
+            self::copyr($skeletonDirectory, $userDirectory);
448
+            // update the file cache
449
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
450
+        }
451
+    }
452
+
453
+    /**
454
+     * copies a directory recursively by using streams
455
+     *
456
+     * @param string $source
457
+     * @param \OCP\Files\Folder $target
458
+     * @return void
459
+     */
460
+    public static function copyr($source, \OCP\Files\Folder $target) {
461
+        $logger = \OC::$server->getLogger();
462
+
463
+        // Verify if folder exists
464
+        $dir = opendir($source);
465
+        if ($dir === false) {
466
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
467
+            return;
468
+        }
469
+
470
+        // Copy the files
471
+        while (false !== ($file = readdir($dir))) {
472
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
473
+                if (is_dir($source . '/' . $file)) {
474
+                    $child = $target->newFolder($file);
475
+                    self::copyr($source . '/' . $file, $child);
476
+                } else {
477
+                    $child = $target->newFile($file);
478
+                    $sourceStream = fopen($source . '/' . $file, 'r');
479
+                    if ($sourceStream === false) {
480
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
481
+                        closedir($dir);
482
+                        return;
483
+                    }
484
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
485
+                }
486
+            }
487
+        }
488
+        closedir($dir);
489
+    }
490
+
491
+    /**
492
+     * @return void
493
+     * @suppress PhanUndeclaredMethod
494
+     */
495
+    public static function tearDownFS() {
496
+        \OC\Files\Filesystem::tearDown();
497
+        \OC::$server->getRootFolder()->clearCache();
498
+        self::$fsSetup = false;
499
+        self::$rootMounted = false;
500
+    }
501
+
502
+    /**
503
+     * get the current installed version of ownCloud
504
+     *
505
+     * @return array
506
+     */
507
+    public static function getVersion() {
508
+        OC_Util::loadVersion();
509
+        return self::$versionCache['OC_Version'];
510
+    }
511
+
512
+    /**
513
+     * get the current installed version string of ownCloud
514
+     *
515
+     * @return string
516
+     */
517
+    public static function getVersionString() {
518
+        OC_Util::loadVersion();
519
+        return self::$versionCache['OC_VersionString'];
520
+    }
521
+
522
+    /**
523
+     * @deprecated the value is of no use anymore
524
+     * @return string
525
+     */
526
+    public static function getEditionString() {
527
+        return '';
528
+    }
529
+
530
+    /**
531
+     * @description get the update channel of the current installed of ownCloud.
532
+     * @return string
533
+     */
534
+    public static function getChannel() {
535
+        OC_Util::loadVersion();
536
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
537
+    }
538
+
539
+    /**
540
+     * @description get the build number of the current installed of ownCloud.
541
+     * @return string
542
+     */
543
+    public static function getBuild() {
544
+        OC_Util::loadVersion();
545
+        return self::$versionCache['OC_Build'];
546
+    }
547
+
548
+    /**
549
+     * @description load the version.php into the session as cache
550
+     * @suppress PhanUndeclaredVariable
551
+     */
552
+    private static function loadVersion() {
553
+        if (self::$versionCache !== null) {
554
+            return;
555
+        }
556
+
557
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
558
+        require OC::$SERVERROOT . '/version.php';
559
+        /** @var int $timestamp */
560
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
561
+        /** @var string $OC_Version */
562
+        self::$versionCache['OC_Version'] = $OC_Version;
563
+        /** @var string $OC_VersionString */
564
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
565
+        /** @var string $OC_Build */
566
+        self::$versionCache['OC_Build'] = $OC_Build;
567
+
568
+        /** @var string $OC_Channel */
569
+        self::$versionCache['OC_Channel'] = $OC_Channel;
570
+    }
571
+
572
+    /**
573
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
574
+     *
575
+     * @param string $application application to get the files from
576
+     * @param string $directory directory within this application (css, js, vendor, etc)
577
+     * @param string $file the file inside of the above folder
578
+     * @return string the path
579
+     */
580
+    private static function generatePath($application, $directory, $file) {
581
+        if (is_null($file)) {
582
+            $file = $application;
583
+            $application = "";
584
+        }
585
+        if (!empty($application)) {
586
+            return "$application/$directory/$file";
587
+        } else {
588
+            return "$directory/$file";
589
+        }
590
+    }
591
+
592
+    /**
593
+     * add a javascript file
594
+     *
595
+     * @param string $application application id
596
+     * @param string|null $file filename
597
+     * @param bool $prepend prepend the Script to the beginning of the list
598
+     * @return void
599
+     */
600
+    public static function addScript($application, $file = null, $prepend = false) {
601
+        $path = OC_Util::generatePath($application, 'js', $file);
602
+
603
+        // core js files need separate handling
604
+        if ($application !== 'core' && $file !== null) {
605
+            self::addTranslations($application);
606
+        }
607
+        self::addExternalResource($application, $prepend, $path, "script");
608
+    }
609
+
610
+    /**
611
+     * add a javascript file from the vendor sub folder
612
+     *
613
+     * @param string $application application id
614
+     * @param string|null $file filename
615
+     * @param bool $prepend prepend the Script to the beginning of the list
616
+     * @return void
617
+     */
618
+    public static function addVendorScript($application, $file = null, $prepend = false) {
619
+        $path = OC_Util::generatePath($application, 'vendor', $file);
620
+        self::addExternalResource($application, $prepend, $path, "script");
621
+    }
622
+
623
+    /**
624
+     * add a translation JS file
625
+     *
626
+     * @param string $application application id
627
+     * @param string|null $languageCode language code, defaults to the current language
628
+     * @param bool|null $prepend prepend the Script to the beginning of the list
629
+     */
630
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
631
+        if (is_null($languageCode)) {
632
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
633
+        }
634
+        if (!empty($application)) {
635
+            $path = "$application/l10n/$languageCode";
636
+        } else {
637
+            $path = "l10n/$languageCode";
638
+        }
639
+        self::addExternalResource($application, $prepend, $path, "script");
640
+    }
641
+
642
+    /**
643
+     * add a css file
644
+     *
645
+     * @param string $application application id
646
+     * @param string|null $file filename
647
+     * @param bool $prepend prepend the Style to the beginning of the list
648
+     * @return void
649
+     */
650
+    public static function addStyle($application, $file = null, $prepend = false) {
651
+        $path = OC_Util::generatePath($application, 'css', $file);
652
+        self::addExternalResource($application, $prepend, $path, "style");
653
+    }
654
+
655
+    /**
656
+     * add a css file from the vendor sub folder
657
+     *
658
+     * @param string $application application id
659
+     * @param string|null $file filename
660
+     * @param bool $prepend prepend the Style to the beginning of the list
661
+     * @return void
662
+     */
663
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
664
+        $path = OC_Util::generatePath($application, 'vendor', $file);
665
+        self::addExternalResource($application, $prepend, $path, "style");
666
+    }
667
+
668
+    /**
669
+     * add an external resource css/js file
670
+     *
671
+     * @param string $application application id
672
+     * @param bool $prepend prepend the file to the beginning of the list
673
+     * @param string $path
674
+     * @param string $type (script or style)
675
+     * @return void
676
+     */
677
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
678
+        if ($type === "style") {
679
+            if (!in_array($path, self::$styles)) {
680
+                if ($prepend === true) {
681
+                    array_unshift(self::$styles, $path);
682
+                } else {
683
+                    self::$styles[] = $path;
684
+                }
685
+            }
686
+        } elseif ($type === "script") {
687
+            if (!in_array($path, self::$scripts)) {
688
+                if ($prepend === true) {
689
+                    array_unshift(self::$scripts, $path);
690
+                } else {
691
+                    self::$scripts [] = $path;
692
+                }
693
+            }
694
+        }
695
+    }
696
+
697
+    /**
698
+     * Add a custom element to the header
699
+     * If $text is null then the element will be written as empty element.
700
+     * So use "" to get a closing tag.
701
+     * @param string $tag tag name of the element
702
+     * @param array $attributes array of attributes for the element
703
+     * @param string $text the text content for the element
704
+     * @param bool $prepend prepend the header to the beginning of the list
705
+     */
706
+    public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
707
+        $header = [
708
+            'tag' => $tag,
709
+            'attributes' => $attributes,
710
+            'text' => $text
711
+        ];
712
+        if ($prepend === true) {
713
+            array_unshift(self::$headers, $header);
714
+        } else {
715
+            self::$headers[] = $header;
716
+        }
717
+    }
718
+
719
+    /**
720
+     * check if the current server configuration is suitable for ownCloud
721
+     *
722
+     * @param \OC\SystemConfig $config
723
+     * @return array arrays with error messages and hints
724
+     */
725
+    public static function checkServer(\OC\SystemConfig $config) {
726
+        $l = \OC::$server->getL10N('lib');
727
+        $errors = [];
728
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
729
+
730
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
731
+            // this check needs to be done every time
732
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
733
+        }
734
+
735
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
736
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
737
+            return $errors;
738
+        }
739
+
740
+        $webServerRestart = false;
741
+        $setup = new \OC\Setup(
742
+            $config,
743
+            \OC::$server->get(IniGetWrapper::class),
744
+            \OC::$server->getL10N('lib'),
745
+            \OC::$server->query(\OCP\Defaults::class),
746
+            \OC::$server->getLogger(),
747
+            \OC::$server->getSecureRandom(),
748
+            \OC::$server->query(\OC\Installer::class)
749
+        );
750
+
751
+        $urlGenerator = \OC::$server->getURLGenerator();
752
+
753
+        $availableDatabases = $setup->getSupportedDatabases();
754
+        if (empty($availableDatabases)) {
755
+            $errors[] = [
756
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
757
+                'hint' => '' //TODO: sane hint
758
+            ];
759
+            $webServerRestart = true;
760
+        }
761
+
762
+        // Check if config folder is writable.
763
+        if (!OC_Helper::isReadOnlyConfigEnabled()) {
764
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
765
+                $errors[] = [
766
+                    'error' => $l->t('Cannot write into "config" directory'),
767
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
768
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
769
+                        . $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',
770
+                        [ $urlGenerator->linkToDocs('admin-config') ])
771
+                ];
772
+            }
773
+        }
774
+
775
+        // Check if there is a writable install folder.
776
+        if ($config->getValue('appstoreenabled', true)) {
777
+            if (OC_App::getInstallPath() === null
778
+                || !is_writable(OC_App::getInstallPath())
779
+                || !is_readable(OC_App::getInstallPath())
780
+            ) {
781
+                $errors[] = [
782
+                    'error' => $l->t('Cannot write into "apps" directory'),
783
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
784
+                        . ' or disabling the appstore in the config file.')
785
+                ];
786
+            }
787
+        }
788
+        // Create root dir.
789
+        if ($config->getValue('installed', false)) {
790
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
791
+                $success = @mkdir($CONFIG_DATADIRECTORY);
792
+                if ($success) {
793
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
794
+                } else {
795
+                    $errors[] = [
796
+                        'error' => $l->t('Cannot create "data" directory'),
797
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
798
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
799
+                    ];
800
+                }
801
+            } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
802
+                // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
803
+                $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
804
+                $handle = fopen($testFile, 'w');
805
+                if (!$handle || fwrite($handle, 'Test write operation') === false) {
806
+                    $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
807
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')]);
808
+                    $errors[] = [
809
+                        'error' => 'Your data directory is not writable',
810
+                        'hint' => $permissionsHint
811
+                    ];
812
+                } else {
813
+                    fclose($handle);
814
+                    unlink($testFile);
815
+                }
816
+            } else {
817
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
818
+            }
819
+        }
820
+
821
+        if (!OC_Util::isSetLocaleWorking()) {
822
+            $errors[] = [
823
+                'error' => $l->t('Setting locale to %s failed',
824
+                    ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
825
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
826
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
827
+            ];
828
+        }
829
+
830
+        // Contains the dependencies that should be checked against
831
+        // classes = class_exists
832
+        // functions = function_exists
833
+        // defined = defined
834
+        // ini = ini_get
835
+        // If the dependency is not found the missing module name is shown to the EndUser
836
+        // When adding new checks always verify that they pass on Travis as well
837
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
838
+        $dependencies = [
839
+            'classes' => [
840
+                'ZipArchive' => 'zip',
841
+                'DOMDocument' => 'dom',
842
+                'XMLWriter' => 'XMLWriter',
843
+                'XMLReader' => 'XMLReader',
844
+            ],
845
+            'functions' => [
846
+                'xml_parser_create' => 'libxml',
847
+                'mb_strcut' => 'mbstring',
848
+                'ctype_digit' => 'ctype',
849
+                'json_encode' => 'JSON',
850
+                'gd_info' => 'GD',
851
+                'gzencode' => 'zlib',
852
+                'iconv' => 'iconv',
853
+                'simplexml_load_string' => 'SimpleXML',
854
+                'hash' => 'HASH Message Digest Framework',
855
+                'curl_init' => 'cURL',
856
+                'openssl_verify' => 'OpenSSL',
857
+            ],
858
+            'defined' => [
859
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
860
+            ],
861
+            'ini' => [
862
+                'default_charset' => 'UTF-8',
863
+            ],
864
+        ];
865
+        $missingDependencies = [];
866
+        $invalidIniSettings = [];
867
+
868
+        $iniWrapper = \OC::$server->get(IniGetWrapper::class);
869
+        foreach ($dependencies['classes'] as $class => $module) {
870
+            if (!class_exists($class)) {
871
+                $missingDependencies[] = $module;
872
+            }
873
+        }
874
+        foreach ($dependencies['functions'] as $function => $module) {
875
+            if (!function_exists($function)) {
876
+                $missingDependencies[] = $module;
877
+            }
878
+        }
879
+        foreach ($dependencies['defined'] as $defined => $module) {
880
+            if (!defined($defined)) {
881
+                $missingDependencies[] = $module;
882
+            }
883
+        }
884
+        foreach ($dependencies['ini'] as $setting => $expected) {
885
+            if (is_bool($expected)) {
886
+                if ($iniWrapper->getBool($setting) !== $expected) {
887
+                    $invalidIniSettings[] = [$setting, $expected];
888
+                }
889
+            }
890
+            if (is_int($expected)) {
891
+                if ($iniWrapper->getNumeric($setting) !== $expected) {
892
+                    $invalidIniSettings[] = [$setting, $expected];
893
+                }
894
+            }
895
+            if (is_string($expected)) {
896
+                if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
897
+                    $invalidIniSettings[] = [$setting, $expected];
898
+                }
899
+            }
900
+        }
901
+
902
+        foreach ($missingDependencies as $missingDependency) {
903
+            $errors[] = [
904
+                'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
905
+                'hint' => $l->t('Please ask your server administrator to install the module.'),
906
+            ];
907
+            $webServerRestart = true;
908
+        }
909
+        foreach ($invalidIniSettings as $setting) {
910
+            if (is_bool($setting[1])) {
911
+                $setting[1] = $setting[1] ? 'on' : 'off';
912
+            }
913
+            $errors[] = [
914
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
915
+                'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
916
+            ];
917
+            $webServerRestart = true;
918
+        }
919
+
920
+        /**
921
+         * The mbstring.func_overload check can only be performed if the mbstring
922
+         * module is installed as it will return null if the checking setting is
923
+         * not available and thus a check on the boolean value fails.
924
+         *
925
+         * TODO: Should probably be implemented in the above generic dependency
926
+         *       check somehow in the long-term.
927
+         */
928
+        if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
929
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
930
+            $errors[] = [
931
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
932
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
933
+            ];
934
+        }
935
+
936
+        if (function_exists('xml_parser_create') &&
937
+            LIBXML_LOADED_VERSION < 20700) {
938
+            $version = LIBXML_LOADED_VERSION;
939
+            $major = floor($version / 10000);
940
+            $version -= ($major * 10000);
941
+            $minor = floor($version / 100);
942
+            $version -= ($minor * 100);
943
+            $patch = $version;
944
+            $errors[] = [
945
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
946
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
947
+            ];
948
+        }
949
+
950
+        if (!self::isAnnotationsWorking()) {
951
+            $errors[] = [
952
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
953
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
954
+            ];
955
+        }
956
+
957
+        if (!\OC::$CLI && $webServerRestart) {
958
+            $errors[] = [
959
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
960
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
961
+            ];
962
+        }
963
+
964
+        $errors = array_merge($errors, self::checkDatabaseVersion());
965
+
966
+        // Cache the result of this function
967
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
968
+
969
+        return $errors;
970
+    }
971
+
972
+    /**
973
+     * Check the database version
974
+     *
975
+     * @return array errors array
976
+     */
977
+    public static function checkDatabaseVersion() {
978
+        $l = \OC::$server->getL10N('lib');
979
+        $errors = [];
980
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
981
+        if ($dbType === 'pgsql') {
982
+            // check PostgreSQL version
983
+            try {
984
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
985
+                $data = $result->fetchRow();
986
+                $result->closeCursor();
987
+                if (isset($data['server_version'])) {
988
+                    $version = $data['server_version'];
989
+                    if (version_compare($version, '9.0.0', '<')) {
990
+                        $errors[] = [
991
+                            'error' => $l->t('PostgreSQL >= 9 required'),
992
+                            'hint' => $l->t('Please upgrade your database version')
993
+                        ];
994
+                    }
995
+                }
996
+            } catch (\Doctrine\DBAL\DBALException $e) {
997
+                $logger = \OC::$server->getLogger();
998
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
999
+                $logger->logException($e);
1000
+            }
1001
+        }
1002
+        return $errors;
1003
+    }
1004
+
1005
+    /**
1006
+     * Check for correct file permissions of data directory
1007
+     *
1008
+     * @param string $dataDirectory
1009
+     * @return array arrays with error messages and hints
1010
+     */
1011
+    public static function checkDataDirectoryPermissions($dataDirectory) {
1012
+        if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1013
+            return  [];
1014
+        }
1015
+
1016
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1017
+        if (substr($perms, -1) !== '0') {
1018
+            chmod($dataDirectory, 0770);
1019
+            clearstatcache();
1020
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1021
+            if ($perms[2] !== '0') {
1022
+                $l = \OC::$server->getL10N('lib');
1023
+                return [[
1024
+                    'error' => $l->t('Your data directory is readable by other users'),
1025
+                    'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1026
+                ]];
1027
+            }
1028
+        }
1029
+        return [];
1030
+    }
1031
+
1032
+    /**
1033
+     * Check that the data directory exists and is valid by
1034
+     * checking the existence of the ".ocdata" file.
1035
+     *
1036
+     * @param string $dataDirectory data directory path
1037
+     * @return array errors found
1038
+     */
1039
+    public static function checkDataDirectoryValidity($dataDirectory) {
1040
+        $l = \OC::$server->getL10N('lib');
1041
+        $errors = [];
1042
+        if ($dataDirectory[0] !== '/') {
1043
+            $errors[] = [
1044
+                'error' => $l->t('Your data directory must be an absolute path'),
1045
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1046
+            ];
1047
+        }
1048
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1049
+            $errors[] = [
1050
+                'error' => $l->t('Your data directory is invalid'),
1051
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1052
+                    ' in the root of the data directory.')
1053
+            ];
1054
+        }
1055
+        return $errors;
1056
+    }
1057
+
1058
+    /**
1059
+     * Check if the user is logged in, redirects to home if not. With
1060
+     * redirect URL parameter to the request URI.
1061
+     *
1062
+     * @return void
1063
+     */
1064
+    public static function checkLoggedIn() {
1065
+        // Check if we are a user
1066
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1067
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1068
+                        'core.login.showLoginForm',
1069
+                        [
1070
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1071
+                        ]
1072
+                    )
1073
+            );
1074
+            exit();
1075
+        }
1076
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1077
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1078
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1079
+            exit();
1080
+        }
1081
+    }
1082
+
1083
+    /**
1084
+     * Check if the user is a admin, redirects to home if not
1085
+     *
1086
+     * @return void
1087
+     */
1088
+    public static function checkAdminUser() {
1089
+        OC_Util::checkLoggedIn();
1090
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1091
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1092
+            exit();
1093
+        }
1094
+    }
1095
+
1096
+    /**
1097
+     * Returns the URL of the default page
1098
+     * based on the system configuration and
1099
+     * the apps visible for the current user
1100
+     *
1101
+     * @return string URL
1102
+     * @suppress PhanDeprecatedFunction
1103
+     */
1104
+    public static function getDefaultPageUrl() {
1105
+        /** @var IConfig $config */
1106
+        $config = \OC::$server->get(IConfig::class);
1107
+        $urlGenerator = \OC::$server->getURLGenerator();
1108
+        // Deny the redirect if the URL contains a @
1109
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1110
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1111
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1112
+        } else {
1113
+            $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1114
+            if ($defaultPage) {
1115
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1116
+            } else {
1117
+                $appId = 'files';
1118
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'dashboard,files'));
1119
+
1120
+                /** @var IUserSession $userSession */
1121
+                $userSession = \OC::$server->get(IUserSession::class);
1122
+                $user = $userSession->getUser();
1123
+                if ($user) {
1124
+                    $userDefaultApps = explode(',', $config->getUserValue($user->getUID(), 'core', 'defaultapp'));
1125
+                    $defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
1126
+                }
1127
+
1128
+                // find the first app that is enabled for the current user
1129
+                foreach ($defaultApps as $defaultApp) {
1130
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1131
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1132
+                        $appId = $defaultApp;
1133
+                        break;
1134
+                    }
1135
+                }
1136
+
1137
+                if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1138
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1139
+                } else {
1140
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1141
+                }
1142
+            }
1143
+        }
1144
+        return $location;
1145
+    }
1146
+
1147
+    /**
1148
+     * Redirect to the user default page
1149
+     *
1150
+     * @return void
1151
+     */
1152
+    public static function redirectToDefaultPage() {
1153
+        $location = self::getDefaultPageUrl();
1154
+        header('Location: ' . $location);
1155
+        exit();
1156
+    }
1157
+
1158
+    /**
1159
+     * get an id unique for this instance
1160
+     *
1161
+     * @return string
1162
+     */
1163
+    public static function getInstanceId() {
1164
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1165
+        if (is_null($id)) {
1166
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1167
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1168
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1169
+        }
1170
+        return $id;
1171
+    }
1172
+
1173
+    /**
1174
+     * Public function to sanitize HTML
1175
+     *
1176
+     * This function is used to sanitize HTML and should be applied on any
1177
+     * string or array of strings before displaying it on a web page.
1178
+     *
1179
+     * @param string|array $value
1180
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1181
+     */
1182
+    public static function sanitizeHTML($value) {
1183
+        if (is_array($value)) {
1184
+            $value = array_map(function ($value) {
1185
+                return self::sanitizeHTML($value);
1186
+            }, $value);
1187
+        } else {
1188
+            // Specify encoding for PHP<5.4
1189
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1190
+        }
1191
+        return $value;
1192
+    }
1193
+
1194
+    /**
1195
+     * Public function to encode url parameters
1196
+     *
1197
+     * This function is used to encode path to file before output.
1198
+     * Encoding is done according to RFC 3986 with one exception:
1199
+     * Character '/' is preserved as is.
1200
+     *
1201
+     * @param string $component part of URI to encode
1202
+     * @return string
1203
+     */
1204
+    public static function encodePath($component) {
1205
+        $encoded = rawurlencode($component);
1206
+        $encoded = str_replace('%2F', '/', $encoded);
1207
+        return $encoded;
1208
+    }
1209
+
1210
+
1211
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1212
+        // php dev server does not support htaccess
1213
+        if (php_sapi_name() === 'cli-server') {
1214
+            return false;
1215
+        }
1216
+
1217
+        // testdata
1218
+        $fileName = '/htaccesstest.txt';
1219
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1220
+
1221
+        // creating a test file
1222
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1223
+
1224
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1225
+            return false;
1226
+        }
1227
+
1228
+        $fp = @fopen($testFile, 'w');
1229
+        if (!$fp) {
1230
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1231
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1232
+        }
1233
+        fwrite($fp, $testContent);
1234
+        fclose($fp);
1235
+
1236
+        return $testContent;
1237
+    }
1238
+
1239
+    /**
1240
+     * Check if the .htaccess file is working
1241
+     * @param \OCP\IConfig $config
1242
+     * @return bool
1243
+     * @throws Exception
1244
+     * @throws \OC\HintException If the test file can't get written.
1245
+     */
1246
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1247
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1248
+            return true;
1249
+        }
1250
+
1251
+        $testContent = $this->createHtaccessTestFile($config);
1252
+        if ($testContent === false) {
1253
+            return false;
1254
+        }
1255
+
1256
+        $fileName = '/htaccesstest.txt';
1257
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1258
+
1259
+        // accessing the file via http
1260
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1261
+        try {
1262
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1263
+        } catch (\Exception $e) {
1264
+            $content = false;
1265
+        }
1266
+
1267
+        if (strpos($url, 'https:') === 0) {
1268
+            $url = 'http:' . substr($url, 6);
1269
+        } else {
1270
+            $url = 'https:' . substr($url, 5);
1271
+        }
1272
+
1273
+        try {
1274
+            $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1275
+        } catch (\Exception $e) {
1276
+            $fallbackContent = false;
1277
+        }
1278
+
1279
+        // cleanup
1280
+        @unlink($testFile);
1281
+
1282
+        /*
1283 1283
 		 * If the content is not equal to test content our .htaccess
1284 1284
 		 * is working as required
1285 1285
 		 */
1286
-		return $content !== $testContent && $fallbackContent !== $testContent;
1287
-	}
1288
-
1289
-	/**
1290
-	 * Check if the setlocal call does not work. This can happen if the right
1291
-	 * local packages are not available on the server.
1292
-	 *
1293
-	 * @return bool
1294
-	 */
1295
-	public static function isSetLocaleWorking() {
1296
-		if ('' === basename('§')) {
1297
-			// Borrowed from \Patchwork\Utf8\Bootup::initLocale
1298
-			setlocale(LC_ALL, 'C.UTF-8', 'C');
1299
-			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');
1300
-		}
1301
-
1302
-		// Check again
1303
-		if ('' === basename('§')) {
1304
-			return false;
1305
-		}
1306
-		return true;
1307
-	}
1308
-
1309
-	/**
1310
-	 * Check if it's possible to get the inline annotations
1311
-	 *
1312
-	 * @return bool
1313
-	 */
1314
-	public static function isAnnotationsWorking() {
1315
-		$reflection = new \ReflectionMethod(__METHOD__);
1316
-		$docs = $reflection->getDocComment();
1317
-
1318
-		return (is_string($docs) && strlen($docs) > 50);
1319
-	}
1320
-
1321
-	/**
1322
-	 * Check if the PHP module fileinfo is loaded.
1323
-	 *
1324
-	 * @return bool
1325
-	 */
1326
-	public static function fileInfoLoaded() {
1327
-		return function_exists('finfo_open');
1328
-	}
1329
-
1330
-	/**
1331
-	 * clear all levels of output buffering
1332
-	 *
1333
-	 * @return void
1334
-	 */
1335
-	public static function obEnd() {
1336
-		while (ob_get_level()) {
1337
-			ob_end_clean();
1338
-		}
1339
-	}
1340
-
1341
-	/**
1342
-	 * Checks whether the server is running on Mac OS X
1343
-	 *
1344
-	 * @return bool true if running on Mac OS X, false otherwise
1345
-	 */
1346
-	public static function runningOnMac() {
1347
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1348
-	}
1349
-
1350
-	/**
1351
-	 * Handles the case that there may not be a theme, then check if a "default"
1352
-	 * theme exists and take that one
1353
-	 *
1354
-	 * @return string the theme
1355
-	 */
1356
-	public static function getTheme() {
1357
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1358
-
1359
-		if ($theme === '') {
1360
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1361
-				$theme = 'default';
1362
-			}
1363
-		}
1364
-
1365
-		return $theme;
1366
-	}
1367
-
1368
-	/**
1369
-	 * Normalize a unicode string
1370
-	 *
1371
-	 * @param string $value a not normalized string
1372
-	 * @return bool|string
1373
-	 */
1374
-	public static function normalizeUnicode($value) {
1375
-		if (Normalizer::isNormalized($value)) {
1376
-			return $value;
1377
-		}
1378
-
1379
-		$normalizedValue = Normalizer::normalize($value);
1380
-		if ($normalizedValue === null || $normalizedValue === false) {
1381
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1382
-			return $value;
1383
-		}
1384
-
1385
-		return $normalizedValue;
1386
-	}
1387
-
1388
-	/**
1389
-	 * A human readable string is generated based on version and build number
1390
-	 *
1391
-	 * @return string
1392
-	 */
1393
-	public static function getHumanVersion() {
1394
-		$version = OC_Util::getVersionString();
1395
-		$build = OC_Util::getBuild();
1396
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1397
-			$version .= ' Build:' . $build;
1398
-		}
1399
-		return $version;
1400
-	}
1401
-
1402
-	/**
1403
-	 * Returns whether the given file name is valid
1404
-	 *
1405
-	 * @param string $file file name to check
1406
-	 * @return bool true if the file name is valid, false otherwise
1407
-	 * @deprecated use \OC\Files\View::verifyPath()
1408
-	 */
1409
-	public static function isValidFileName($file) {
1410
-		$trimmed = trim($file);
1411
-		if ($trimmed === '') {
1412
-			return false;
1413
-		}
1414
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1415
-			return false;
1416
-		}
1417
-
1418
-		// detect part files
1419
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1420
-			return false;
1421
-		}
1422
-
1423
-		foreach (str_split($trimmed) as $char) {
1424
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1425
-				return false;
1426
-			}
1427
-		}
1428
-		return true;
1429
-	}
1430
-
1431
-	/**
1432
-	 * Check whether the instance needs to perform an upgrade,
1433
-	 * either when the core version is higher or any app requires
1434
-	 * an upgrade.
1435
-	 *
1436
-	 * @param \OC\SystemConfig $config
1437
-	 * @return bool whether the core or any app needs an upgrade
1438
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1439
-	 */
1440
-	public static function needUpgrade(\OC\SystemConfig $config) {
1441
-		if ($config->getValue('installed', false)) {
1442
-			$installedVersion = $config->getValue('version', '0.0.0');
1443
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1444
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1445
-			if ($versionDiff > 0) {
1446
-				return true;
1447
-			} elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1448
-				// downgrade with debug
1449
-				$installedMajor = explode('.', $installedVersion);
1450
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1451
-				$currentMajor = explode('.', $currentVersion);
1452
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1453
-				if ($installedMajor === $currentMajor) {
1454
-					// Same major, allow downgrade for developers
1455
-					return true;
1456
-				} else {
1457
-					// downgrade attempt, throw exception
1458
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1459
-				}
1460
-			} elseif ($versionDiff < 0) {
1461
-				// downgrade attempt, throw exception
1462
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1463
-			}
1464
-
1465
-			// also check for upgrades for apps (independently from the user)
1466
-			$apps = \OC_App::getEnabledApps(false, true);
1467
-			$shouldUpgrade = false;
1468
-			foreach ($apps as $app) {
1469
-				if (\OC_App::shouldUpgrade($app)) {
1470
-					$shouldUpgrade = true;
1471
-					break;
1472
-				}
1473
-			}
1474
-			return $shouldUpgrade;
1475
-		} else {
1476
-			return false;
1477
-		}
1478
-	}
1479
-
1480
-	/**
1481
-	 * is this Internet explorer ?
1482
-	 *
1483
-	 * @return boolean
1484
-	 */
1485
-	public static function isIe() {
1486
-		if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1487
-			return false;
1488
-		}
1489
-
1490
-		return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1491
-	}
1286
+        return $content !== $testContent && $fallbackContent !== $testContent;
1287
+    }
1288
+
1289
+    /**
1290
+     * Check if the setlocal call does not work. This can happen if the right
1291
+     * local packages are not available on the server.
1292
+     *
1293
+     * @return bool
1294
+     */
1295
+    public static function isSetLocaleWorking() {
1296
+        if ('' === basename('§')) {
1297
+            // Borrowed from \Patchwork\Utf8\Bootup::initLocale
1298
+            setlocale(LC_ALL, 'C.UTF-8', 'C');
1299
+            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');
1300
+        }
1301
+
1302
+        // Check again
1303
+        if ('' === basename('§')) {
1304
+            return false;
1305
+        }
1306
+        return true;
1307
+    }
1308
+
1309
+    /**
1310
+     * Check if it's possible to get the inline annotations
1311
+     *
1312
+     * @return bool
1313
+     */
1314
+    public static function isAnnotationsWorking() {
1315
+        $reflection = new \ReflectionMethod(__METHOD__);
1316
+        $docs = $reflection->getDocComment();
1317
+
1318
+        return (is_string($docs) && strlen($docs) > 50);
1319
+    }
1320
+
1321
+    /**
1322
+     * Check if the PHP module fileinfo is loaded.
1323
+     *
1324
+     * @return bool
1325
+     */
1326
+    public static function fileInfoLoaded() {
1327
+        return function_exists('finfo_open');
1328
+    }
1329
+
1330
+    /**
1331
+     * clear all levels of output buffering
1332
+     *
1333
+     * @return void
1334
+     */
1335
+    public static function obEnd() {
1336
+        while (ob_get_level()) {
1337
+            ob_end_clean();
1338
+        }
1339
+    }
1340
+
1341
+    /**
1342
+     * Checks whether the server is running on Mac OS X
1343
+     *
1344
+     * @return bool true if running on Mac OS X, false otherwise
1345
+     */
1346
+    public static function runningOnMac() {
1347
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1348
+    }
1349
+
1350
+    /**
1351
+     * Handles the case that there may not be a theme, then check if a "default"
1352
+     * theme exists and take that one
1353
+     *
1354
+     * @return string the theme
1355
+     */
1356
+    public static function getTheme() {
1357
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1358
+
1359
+        if ($theme === '') {
1360
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1361
+                $theme = 'default';
1362
+            }
1363
+        }
1364
+
1365
+        return $theme;
1366
+    }
1367
+
1368
+    /**
1369
+     * Normalize a unicode string
1370
+     *
1371
+     * @param string $value a not normalized string
1372
+     * @return bool|string
1373
+     */
1374
+    public static function normalizeUnicode($value) {
1375
+        if (Normalizer::isNormalized($value)) {
1376
+            return $value;
1377
+        }
1378
+
1379
+        $normalizedValue = Normalizer::normalize($value);
1380
+        if ($normalizedValue === null || $normalizedValue === false) {
1381
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1382
+            return $value;
1383
+        }
1384
+
1385
+        return $normalizedValue;
1386
+    }
1387
+
1388
+    /**
1389
+     * A human readable string is generated based on version and build number
1390
+     *
1391
+     * @return string
1392
+     */
1393
+    public static function getHumanVersion() {
1394
+        $version = OC_Util::getVersionString();
1395
+        $build = OC_Util::getBuild();
1396
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1397
+            $version .= ' Build:' . $build;
1398
+        }
1399
+        return $version;
1400
+    }
1401
+
1402
+    /**
1403
+     * Returns whether the given file name is valid
1404
+     *
1405
+     * @param string $file file name to check
1406
+     * @return bool true if the file name is valid, false otherwise
1407
+     * @deprecated use \OC\Files\View::verifyPath()
1408
+     */
1409
+    public static function isValidFileName($file) {
1410
+        $trimmed = trim($file);
1411
+        if ($trimmed === '') {
1412
+            return false;
1413
+        }
1414
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1415
+            return false;
1416
+        }
1417
+
1418
+        // detect part files
1419
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1420
+            return false;
1421
+        }
1422
+
1423
+        foreach (str_split($trimmed) as $char) {
1424
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1425
+                return false;
1426
+            }
1427
+        }
1428
+        return true;
1429
+    }
1430
+
1431
+    /**
1432
+     * Check whether the instance needs to perform an upgrade,
1433
+     * either when the core version is higher or any app requires
1434
+     * an upgrade.
1435
+     *
1436
+     * @param \OC\SystemConfig $config
1437
+     * @return bool whether the core or any app needs an upgrade
1438
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1439
+     */
1440
+    public static function needUpgrade(\OC\SystemConfig $config) {
1441
+        if ($config->getValue('installed', false)) {
1442
+            $installedVersion = $config->getValue('version', '0.0.0');
1443
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1444
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1445
+            if ($versionDiff > 0) {
1446
+                return true;
1447
+            } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1448
+                // downgrade with debug
1449
+                $installedMajor = explode('.', $installedVersion);
1450
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1451
+                $currentMajor = explode('.', $currentVersion);
1452
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1453
+                if ($installedMajor === $currentMajor) {
1454
+                    // Same major, allow downgrade for developers
1455
+                    return true;
1456
+                } else {
1457
+                    // downgrade attempt, throw exception
1458
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1459
+                }
1460
+            } elseif ($versionDiff < 0) {
1461
+                // downgrade attempt, throw exception
1462
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1463
+            }
1464
+
1465
+            // also check for upgrades for apps (independently from the user)
1466
+            $apps = \OC_App::getEnabledApps(false, true);
1467
+            $shouldUpgrade = false;
1468
+            foreach ($apps as $app) {
1469
+                if (\OC_App::shouldUpgrade($app)) {
1470
+                    $shouldUpgrade = true;
1471
+                    break;
1472
+                }
1473
+            }
1474
+            return $shouldUpgrade;
1475
+        } else {
1476
+            return false;
1477
+        }
1478
+    }
1479
+
1480
+    /**
1481
+     * is this Internet explorer ?
1482
+     *
1483
+     * @return boolean
1484
+     */
1485
+    public static function isIe() {
1486
+        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1487
+            return false;
1488
+        }
1489
+
1490
+        return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1491
+    }
1492 1492
 }
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +1003 added lines, -1003 removed lines patch added patch discarded remove patch
@@ -77,1009 +77,1009 @@
 block discarded – undo
77 77
  * OC_autoload!
78 78
  */
79 79
 class OC {
80
-	/**
81
-	 * Associative array for autoloading. classname => filename
82
-	 */
83
-	public static $CLASSPATH = [];
84
-	/**
85
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
86
-	 */
87
-	public static $SERVERROOT = '';
88
-	/**
89
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
90
-	 */
91
-	private static $SUBURI = '';
92
-	/**
93
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
94
-	 */
95
-	public static $WEBROOT = '';
96
-	/**
97
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
98
-	 * web path in 'url'
99
-	 */
100
-	public static $APPSROOTS = [];
101
-
102
-	/**
103
-	 * @var string
104
-	 */
105
-	public static $configDir;
106
-
107
-	/**
108
-	 * requested app
109
-	 */
110
-	public static $REQUESTEDAPP = '';
111
-
112
-	/**
113
-	 * check if Nextcloud runs in cli mode
114
-	 */
115
-	public static $CLI = false;
116
-
117
-	/**
118
-	 * @var \OC\Autoloader $loader
119
-	 */
120
-	public static $loader = null;
121
-
122
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
123
-	public static $composerAutoloader = null;
124
-
125
-	/**
126
-	 * @var \OC\Server
127
-	 */
128
-	public static $server = null;
129
-
130
-	/**
131
-	 * @var \OC\Config
132
-	 */
133
-	private static $config = null;
134
-
135
-	/**
136
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
137
-	 * the app path list is empty or contains an invalid path
138
-	 */
139
-	public static function initPaths() {
140
-		if (defined('PHPUNIT_CONFIG_DIR')) {
141
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
142
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
143
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
144
-		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
145
-			self::$configDir = rtrim($dir, '/') . '/';
146
-		} else {
147
-			self::$configDir = OC::$SERVERROOT . '/config/';
148
-		}
149
-		self::$config = new \OC\Config(self::$configDir);
150
-
151
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
152
-		/**
153
-		 * FIXME: The following lines are required because we can't yet instantiate
154
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
155
-		 */
156
-		$params = [
157
-			'server' => [
158
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
159
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
160
-			],
161
-		];
162
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, new \OC\Security\SecureRandom(), new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
163
-		$scriptName = $fakeRequest->getScriptName();
164
-		if (substr($scriptName, -1) == '/') {
165
-			$scriptName .= 'index.php';
166
-			//make sure suburi follows the same rules as scriptName
167
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
168
-				if (substr(OC::$SUBURI, -1) != '/') {
169
-					OC::$SUBURI = OC::$SUBURI . '/';
170
-				}
171
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
172
-			}
173
-		}
174
-
175
-
176
-		if (OC::$CLI) {
177
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
178
-		} else {
179
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
180
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
181
-
182
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
183
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
184
-				}
185
-			} else {
186
-				// The scriptName is not ending with OC::$SUBURI
187
-				// This most likely means that we are calling from CLI.
188
-				// However some cron jobs still need to generate
189
-				// a web URL, so we use overwritewebroot as a fallback.
190
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
191
-			}
192
-
193
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
194
-			// slash which is required by URL generation.
195
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
196
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
197
-				header('Location: '.\OC::$WEBROOT.'/');
198
-				exit();
199
-			}
200
-		}
201
-
202
-		// search the apps folder
203
-		$config_paths = self::$config->getValue('apps_paths', []);
204
-		if (!empty($config_paths)) {
205
-			foreach ($config_paths as $paths) {
206
-				if (isset($paths['url']) && isset($paths['path'])) {
207
-					$paths['url'] = rtrim($paths['url'], '/');
208
-					$paths['path'] = rtrim($paths['path'], '/');
209
-					OC::$APPSROOTS[] = $paths;
210
-				}
211
-			}
212
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
213
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
214
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
215
-			OC::$APPSROOTS[] = [
216
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
217
-				'url' => '/apps',
218
-				'writable' => true
219
-			];
220
-		}
221
-
222
-		if (empty(OC::$APPSROOTS)) {
223
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
224
-				. ' or the folder above. You can also configure the location in the config.php file.');
225
-		}
226
-		$paths = [];
227
-		foreach (OC::$APPSROOTS as $path) {
228
-			$paths[] = $path['path'];
229
-			if (!is_dir($path['path'])) {
230
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
231
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
232
-					. ' config.php file.', $path['path']));
233
-			}
234
-		}
235
-
236
-		// set the right include path
237
-		set_include_path(
238
-			implode(PATH_SEPARATOR, $paths)
239
-		);
240
-	}
241
-
242
-	public static function checkConfig() {
243
-		$l = \OC::$server->getL10N('lib');
244
-
245
-		// Create config if it does not already exist
246
-		$configFilePath = self::$configDir .'/config.php';
247
-		if (!file_exists($configFilePath)) {
248
-			@touch($configFilePath);
249
-		}
250
-
251
-		// Check if config is writable
252
-		$configFileWritable = is_writable($configFilePath);
253
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
254
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
255
-			$urlGenerator = \OC::$server->getURLGenerator();
256
-
257
-			if (self::$CLI) {
258
-				echo $l->t('Cannot write into "config" directory!')."\n";
259
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
260
-				echo "\n";
261
-				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
262
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
263
-				exit;
264
-			} else {
265
-				OC_Template::printErrorPage(
266
-					$l->t('Cannot write into "config" directory!'),
267
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
268
-					. $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',
269
-					[ $urlGenerator->linkToDocs('admin-config') ]),
270
-					503
271
-				);
272
-			}
273
-		}
274
-	}
275
-
276
-	public static function checkInstalled() {
277
-		if (defined('OC_CONSOLE')) {
278
-			return;
279
-		}
280
-		// Redirect to installer if not installed
281
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
282
-			if (OC::$CLI) {
283
-				throw new Exception('Not installed');
284
-			} else {
285
-				$url = OC::$WEBROOT . '/index.php';
286
-				header('Location: ' . $url);
287
-			}
288
-			exit();
289
-		}
290
-	}
291
-
292
-	public static function checkMaintenanceMode() {
293
-		// Allow ajax update script to execute without being stopped
294
-		if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
295
-			// send http status 503
296
-			http_response_code(503);
297
-			header('Retry-After: 120');
298
-
299
-			// render error page
300
-			$template = new OC_Template('', 'update.user', 'guest');
301
-			OC_Util::addScript('dist/maintenance');
302
-			OC_Util::addStyle('core', 'guest');
303
-			$template->printPage();
304
-			die();
305
-		}
306
-	}
307
-
308
-	/**
309
-	 * Prints the upgrade page
310
-	 *
311
-	 * @param \OC\SystemConfig $systemConfig
312
-	 */
313
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
314
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
315
-		$tooBig = false;
316
-		if (!$disableWebUpdater) {
317
-			$apps = \OC::$server->getAppManager();
318
-			if ($apps->isInstalled('user_ldap')) {
319
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
320
-
321
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
322
-					->from('ldap_user_mapping')
323
-					->execute();
324
-				$row = $result->fetch();
325
-				$result->closeCursor();
326
-
327
-				$tooBig = ($row['user_count'] > 50);
328
-			}
329
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
330
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
331
-
332
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
333
-					->from('user_saml_users')
334
-					->execute();
335
-				$row = $result->fetch();
336
-				$result->closeCursor();
337
-
338
-				$tooBig = ($row['user_count'] > 50);
339
-			}
340
-			if (!$tooBig) {
341
-				// count users
342
-				$stats = \OC::$server->getUserManager()->countUsers();
343
-				$totalUsers = array_sum($stats);
344
-				$tooBig = ($totalUsers > 50);
345
-			}
346
-		}
347
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
348
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
349
-
350
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
351
-			// send http status 503
352
-			http_response_code(503);
353
-			header('Retry-After: 120');
354
-
355
-			// render error page
356
-			$template = new OC_Template('', 'update.use-cli', 'guest');
357
-			$template->assign('productName', 'nextcloud'); // for now
358
-			$template->assign('version', OC_Util::getVersionString());
359
-			$template->assign('tooBig', $tooBig);
360
-
361
-			$template->printPage();
362
-			die();
363
-		}
364
-
365
-		// check whether this is a core update or apps update
366
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
367
-		$currentVersion = implode('.', \OCP\Util::getVersion());
368
-
369
-		// if not a core upgrade, then it's apps upgrade
370
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
371
-
372
-		$oldTheme = $systemConfig->getValue('theme');
373
-		$systemConfig->setValue('theme', '');
374
-		OC_Util::addScript('update');
375
-
376
-		/** @var \OC\App\AppManager $appManager */
377
-		$appManager = \OC::$server->getAppManager();
378
-
379
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
380
-		$tmpl->assign('version', OC_Util::getVersionString());
381
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
382
-
383
-		// get third party apps
384
-		$ocVersion = \OCP\Util::getVersion();
385
-		$ocVersion = implode('.', $ocVersion);
386
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
387
-		$incompatibleShippedApps = [];
388
-		foreach ($incompatibleApps as $appInfo) {
389
-			if ($appManager->isShipped($appInfo['id'])) {
390
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
391
-			}
392
-		}
393
-
394
-		if (!empty($incompatibleShippedApps)) {
395
-			$l = \OC::$server->getL10N('core');
396
-			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
397
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
398
-		}
399
-
400
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
401
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
402
-		$tmpl->assign('productName', 'Nextcloud'); // for now
403
-		$tmpl->assign('oldTheme', $oldTheme);
404
-		$tmpl->printPage();
405
-	}
406
-
407
-	public static function initSession() {
408
-		if (self::$server->getRequest()->getServerProtocol() === 'https') {
409
-			ini_set('session.cookie_secure', true);
410
-		}
411
-
412
-		// prevents javascript from accessing php session cookies
413
-		ini_set('session.cookie_httponly', 'true');
414
-
415
-		// set the cookie path to the Nextcloud directory
416
-		$cookie_path = OC::$WEBROOT ? : '/';
417
-		ini_set('session.cookie_path', $cookie_path);
418
-
419
-		// Let the session name be changed in the initSession Hook
420
-		$sessionName = OC_Util::getInstanceId();
421
-
422
-		try {
423
-			// set the session name to the instance id - which is unique
424
-			$session = new \OC\Session\Internal($sessionName);
425
-
426
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
427
-			$session = $cryptoWrapper->wrapSession($session);
428
-			self::$server->setSession($session);
429
-
430
-			// if session can't be started break with http 500 error
431
-		} catch (Exception $e) {
432
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
433
-			//show the user a detailed error page
434
-			OC_Template::printExceptionErrorPage($e, 500);
435
-			die();
436
-		}
437
-
438
-		$sessionLifeTime = self::getSessionLifeTime();
439
-
440
-		// session timeout
441
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
442
-			if (isset($_COOKIE[session_name()])) {
443
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
444
-			}
445
-			\OC::$server->getUserSession()->logout();
446
-		}
447
-
448
-		$session->set('LAST_ACTIVITY', time());
449
-	}
450
-
451
-	/**
452
-	 * @return string
453
-	 */
454
-	private static function getSessionLifeTime() {
455
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
456
-	}
457
-
458
-	/**
459
-	 * Try to set some values to the required Nextcloud default
460
-	 */
461
-	public static function setRequiredIniValues() {
462
-		@ini_set('default_charset', 'UTF-8');
463
-		@ini_set('gd.jpeg_ignore_warning', '1');
464
-	}
465
-
466
-	/**
467
-	 * Send the same site cookies
468
-	 */
469
-	private static function sendSameSiteCookies() {
470
-		$cookieParams = session_get_cookie_params();
471
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
472
-		$policies = [
473
-			'lax',
474
-			'strict',
475
-		];
476
-
477
-		// Append __Host to the cookie if it meets the requirements
478
-		$cookiePrefix = '';
479
-		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
480
-			$cookiePrefix = '__Host-';
481
-		}
482
-
483
-		foreach ($policies as $policy) {
484
-			header(
485
-				sprintf(
486
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
487
-					$cookiePrefix,
488
-					$policy,
489
-					$cookieParams['path'],
490
-					$policy
491
-				),
492
-				false
493
-			);
494
-		}
495
-	}
496
-
497
-	/**
498
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
499
-	 * be set in every request if cookies are sent to add a second level of
500
-	 * defense against CSRF.
501
-	 *
502
-	 * If the cookie is not sent this will set the cookie and reload the page.
503
-	 * We use an additional cookie since we want to protect logout CSRF and
504
-	 * also we can't directly interfere with PHP's session mechanism.
505
-	 */
506
-	private static function performSameSiteCookieProtection() {
507
-		$request = \OC::$server->getRequest();
508
-
509
-		// Some user agents are notorious and don't really properly follow HTTP
510
-		// specifications. For those, have an automated opt-out. Since the protection
511
-		// for remote.php is applied in base.php as starting point we need to opt out
512
-		// here.
513
-		$incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
514
-
515
-		// Fallback, if csrf.optout is unset
516
-		if (!is_array($incompatibleUserAgents)) {
517
-			$incompatibleUserAgents = [
518
-				// OS X Finder
519
-				'/^WebDAVFS/',
520
-				// Windows webdav drive
521
-				'/^Microsoft-WebDAV-MiniRedir/',
522
-			];
523
-		}
524
-
525
-		if ($request->isUserAgent($incompatibleUserAgents)) {
526
-			return;
527
-		}
528
-
529
-		if (count($_COOKIE) > 0) {
530
-			$requestUri = $request->getScriptName();
531
-			$processingScript = explode('/', $requestUri);
532
-			$processingScript = $processingScript[count($processingScript) - 1];
533
-
534
-			// index.php routes are handled in the middleware
535
-			if ($processingScript === 'index.php') {
536
-				return;
537
-			}
538
-
539
-			// All other endpoints require the lax and the strict cookie
540
-			if (!$request->passesStrictCookieCheck()) {
541
-				self::sendSameSiteCookies();
542
-				// Debug mode gets access to the resources without strict cookie
543
-				// due to the fact that the SabreDAV browser also lives there.
544
-				if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
545
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
546
-					exit();
547
-				}
548
-			}
549
-		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
550
-			self::sendSameSiteCookies();
551
-		}
552
-	}
553
-
554
-	public static function init() {
555
-		// calculate the root directories
556
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
557
-
558
-		// register autoloader
559
-		$loaderStart = microtime(true);
560
-		require_once __DIR__ . '/autoloader.php';
561
-		self::$loader = new \OC\Autoloader([
562
-			OC::$SERVERROOT . '/lib/private/legacy',
563
-		]);
564
-		if (defined('PHPUNIT_RUN')) {
565
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
566
-		}
567
-		spl_autoload_register([self::$loader, 'load']);
568
-		$loaderEnd = microtime(true);
569
-
570
-		self::$CLI = (php_sapi_name() == 'cli');
571
-
572
-		// Add default composer PSR-4 autoloader
573
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
574
-
575
-		try {
576
-			self::initPaths();
577
-			// setup 3rdparty autoloader
578
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
579
-			if (!file_exists($vendorAutoLoad)) {
580
-				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".');
581
-			}
582
-			require_once $vendorAutoLoad;
583
-		} catch (\RuntimeException $e) {
584
-			if (!self::$CLI) {
585
-				http_response_code(503);
586
-			}
587
-			// we can't use the template error page here, because this needs the
588
-			// DI container which isn't available yet
589
-			print($e->getMessage());
590
-			exit();
591
-		}
592
-
593
-		// setup the basic server
594
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
595
-		self::$server->boot();
596
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
597
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
598
-
599
-		// Override php.ini and log everything if we're troubleshooting
600
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
601
-			error_reporting(E_ALL);
602
-		}
603
-
604
-		// Don't display errors and log them
605
-		@ini_set('display_errors', '0');
606
-		@ini_set('log_errors', '1');
607
-
608
-		if (!date_default_timezone_set('UTC')) {
609
-			throw new \RuntimeException('Could not set timezone to UTC');
610
-		}
611
-
612
-		//try to configure php to enable big file uploads.
613
-		//this doesn´t work always depending on the webserver and php configuration.
614
-		//Let´s try to overwrite some defaults anyway
615
-
616
-		//try to set the maximum execution time to 60min
617
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
618
-			@set_time_limit(3600);
619
-		}
620
-		@ini_set('max_execution_time', '3600');
621
-		@ini_set('max_input_time', '3600');
622
-
623
-		self::setRequiredIniValues();
624
-		self::handleAuthHeaders();
625
-		self::registerAutoloaderCache();
626
-
627
-		// initialize intl fallback if necessary
628
-		OC_Util::isSetLocaleWorking();
629
-
630
-		if (!defined('PHPUNIT_RUN')) {
631
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
632
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
633
-			OC\Log\ErrorHandler::register($debug);
634
-		}
635
-
636
-		/** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
637
-		$bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
638
-		$bootstrapCoordinator->runInitialRegistration();
639
-
640
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
641
-		OC_App::loadApps(['session']);
642
-		if (!self::$CLI) {
643
-			self::initSession();
644
-		}
645
-		\OC::$server->getEventLogger()->end('init_session');
646
-		self::checkConfig();
647
-		self::checkInstalled();
648
-
649
-		OC_Response::addSecurityHeaders();
650
-
651
-		self::performSameSiteCookieProtection();
652
-
653
-		if (!defined('OC_CONSOLE')) {
654
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
655
-			if (count($errors) > 0) {
656
-				if (!self::$CLI) {
657
-					http_response_code(503);
658
-					OC_Util::addStyle('guest');
659
-					try {
660
-						OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
661
-						exit;
662
-					} catch (\Exception $e) {
663
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
664
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
665
-					}
666
-				}
667
-
668
-				// Convert l10n string into regular string for usage in database
669
-				$staticErrors = [];
670
-				foreach ($errors as $error) {
671
-					echo $error['error'] . "\n";
672
-					echo $error['hint'] . "\n\n";
673
-					$staticErrors[] = [
674
-						'error' => (string)$error['error'],
675
-						'hint' => (string)$error['hint'],
676
-					];
677
-				}
678
-
679
-				try {
680
-					\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
681
-				} catch (\Exception $e) {
682
-					echo('Writing to database failed');
683
-				}
684
-				exit(1);
685
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
686
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
687
-			}
688
-		}
689
-		//try to set the session lifetime
690
-		$sessionLifeTime = self::getSessionLifeTime();
691
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
692
-
693
-		$systemConfig = \OC::$server->getSystemConfig();
694
-
695
-		// User and Groups
696
-		if (!$systemConfig->getValue("installed", false)) {
697
-			self::$server->getSession()->set('user_id', '');
698
-		}
699
-
700
-		OC_User::useBackend(new \OC\User\Database());
701
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
702
-
703
-		// Subscribe to the hook
704
-		\OCP\Util::connectHook(
705
-			'\OCA\Files_Sharing\API\Server2Server',
706
-			'preLoginNameUsedAsUserName',
707
-			'\OC\User\Database',
708
-			'preLoginNameUsedAsUserName'
709
-		);
710
-
711
-		//setup extra user backends
712
-		if (!\OCP\Util::needUpgrade()) {
713
-			OC_User::setupBackends();
714
-		} else {
715
-			// Run upgrades in incognito mode
716
-			OC_User::setIncognitoMode(true);
717
-		}
718
-
719
-		self::registerCleanupHooks();
720
-		self::registerFilesystemHooks();
721
-		self::registerShareHooks();
722
-		self::registerEncryptionWrapper();
723
-		self::registerEncryptionHooks();
724
-		self::registerAccountHooks();
725
-		self::registerResourceCollectionHooks();
726
-		self::registerAppRestrictionsHooks();
727
-
728
-		// Make sure that the application class is not loaded before the database is setup
729
-		if ($systemConfig->getValue("installed", false)) {
730
-			OC_App::loadApp('settings');
731
-		}
732
-
733
-		//make sure temporary files are cleaned up
734
-		$tmpManager = \OC::$server->getTempManager();
735
-		register_shutdown_function([$tmpManager, 'clean']);
736
-		$lockProvider = \OC::$server->getLockingProvider();
737
-		register_shutdown_function([$lockProvider, 'releaseAll']);
738
-
739
-		// Check whether the sample configuration has been copied
740
-		if ($systemConfig->getValue('copied_sample_config', false)) {
741
-			$l = \OC::$server->getL10N('lib');
742
-			OC_Template::printErrorPage(
743
-				$l->t('Sample configuration detected'),
744
-				$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'),
745
-				503
746
-			);
747
-			return;
748
-		}
749
-
750
-		$request = \OC::$server->getRequest();
751
-		$host = $request->getInsecureServerHost();
752
-		/**
753
-		 * if the host passed in headers isn't trusted
754
-		 * FIXME: Should not be in here at all :see_no_evil:
755
-		 */
756
-		if (!OC::$CLI
757
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
758
-			&& self::$server->getConfig()->getSystemValue('installed', false)
759
-		) {
760
-			// Allow access to CSS resources
761
-			$isScssRequest = false;
762
-			if (strpos($request->getPathInfo(), '/css/') === 0) {
763
-				$isScssRequest = true;
764
-			}
765
-
766
-			if (substr($request->getRequestUri(), -11) === '/status.php') {
767
-				http_response_code(400);
768
-				header('Content-Type: application/json');
769
-				echo '{"error": "Trusted domain error.", "code": 15}';
770
-				exit();
771
-			}
772
-
773
-			if (!$isScssRequest) {
774
-				http_response_code(400);
775
-
776
-				\OC::$server->getLogger()->info(
777
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
778
-					[
779
-						'app' => 'core',
780
-						'remoteAddress' => $request->getRemoteAddress(),
781
-						'host' => $host,
782
-					]
783
-				);
784
-
785
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
786
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
787
-				$tmpl->printPage();
788
-
789
-				exit();
790
-			}
791
-		}
792
-		\OC::$server->getEventLogger()->end('boot');
793
-	}
794
-
795
-	/**
796
-	 * register hooks for the cleanup of cache and bruteforce protection
797
-	 */
798
-	public static function registerCleanupHooks() {
799
-		//don't try to do this before we are properly setup
800
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
801
-
802
-			// NOTE: This will be replaced to use OCP
803
-			$userSession = self::$server->getUserSession();
804
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
805
-				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
806
-					// reset brute force delay for this IP address and username
807
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
808
-					$request = \OC::$server->getRequest();
809
-					$throttler = \OC::$server->getBruteForceThrottler();
810
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
811
-				}
812
-
813
-				try {
814
-					$cache = new \OC\Cache\File();
815
-					$cache->gc();
816
-				} catch (\OC\ServerNotAvailableException $e) {
817
-					// not a GC exception, pass it on
818
-					throw $e;
819
-				} catch (\OC\ForbiddenException $e) {
820
-					// filesystem blocked for this request, ignore
821
-				} catch (\Exception $e) {
822
-					// a GC exception should not prevent users from using OC,
823
-					// so log the exception
824
-					\OC::$server->getLogger()->logException($e, [
825
-						'message' => 'Exception when running cache gc.',
826
-						'level' => ILogger::WARN,
827
-						'app' => 'core',
828
-					]);
829
-				}
830
-			});
831
-		}
832
-	}
833
-
834
-	private static function registerEncryptionWrapper() {
835
-		$manager = self::$server->getEncryptionManager();
836
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
837
-	}
838
-
839
-	private static function registerEncryptionHooks() {
840
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
841
-		if ($enabled) {
842
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
843
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
844
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
845
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
846
-		}
847
-	}
848
-
849
-	private static function registerAccountHooks() {
850
-		$hookHandler = \OC::$server->get(\OC\Accounts\Hooks::class);
851
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
852
-	}
853
-
854
-	private static function registerAppRestrictionsHooks() {
855
-		/** @var \OC\Group\Manager $groupManager */
856
-		$groupManager = self::$server->query(\OCP\IGroupManager::class);
857
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
858
-			$appManager = self::$server->getAppManager();
859
-			$apps = $appManager->getEnabledAppsForGroup($group);
860
-			foreach ($apps as $appId) {
861
-				$restrictions = $appManager->getAppRestriction($appId);
862
-				if (empty($restrictions)) {
863
-					continue;
864
-				}
865
-				$key = array_search($group->getGID(), $restrictions);
866
-				unset($restrictions[$key]);
867
-				$restrictions = array_values($restrictions);
868
-				if (empty($restrictions)) {
869
-					$appManager->disableApp($appId);
870
-				} else {
871
-					$appManager->enableAppForGroups($appId, $restrictions);
872
-				}
873
-			}
874
-		});
875
-	}
876
-
877
-	private static function registerResourceCollectionHooks() {
878
-		\OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
879
-	}
880
-
881
-	/**
882
-	 * register hooks for the filesystem
883
-	 */
884
-	public static function registerFilesystemHooks() {
885
-		// Check for blacklisted files
886
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
887
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
888
-	}
889
-
890
-	/**
891
-	 * register hooks for sharing
892
-	 */
893
-	public static function registerShareHooks() {
894
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
895
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
896
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
897
-
898
-			/** @var IEventDispatcher $dispatcher */
899
-			$dispatcher = \OC::$server->get(IEventDispatcher::class);
900
-			$dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
901
-		}
902
-	}
903
-
904
-	protected static function registerAutoloaderCache() {
905
-		// The class loader takes an optional low-latency cache, which MUST be
906
-		// namespaced. The instanceid is used for namespacing, but might be
907
-		// unavailable at this point. Furthermore, it might not be possible to
908
-		// generate an instanceid via \OC_Util::getInstanceId() because the
909
-		// config file may not be writable. As such, we only register a class
910
-		// loader cache if instanceid is available without trying to create one.
911
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
912
-		if ($instanceId) {
913
-			try {
914
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
915
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
916
-			} catch (\Exception $ex) {
917
-			}
918
-		}
919
-	}
920
-
921
-	/**
922
-	 * Handle the request
923
-	 */
924
-	public static function handleRequest() {
925
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
926
-		$systemConfig = \OC::$server->getSystemConfig();
927
-
928
-		// Check if Nextcloud is installed or in maintenance (update) mode
929
-		if (!$systemConfig->getValue('installed', false)) {
930
-			\OC::$server->getSession()->clear();
931
-			$setupHelper = new OC\Setup(
932
-				$systemConfig,
933
-				\OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
934
-				\OC::$server->getL10N('lib'),
935
-				\OC::$server->query(\OCP\Defaults::class),
936
-				\OC::$server->getLogger(),
937
-				\OC::$server->getSecureRandom(),
938
-				\OC::$server->query(\OC\Installer::class)
939
-			);
940
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
941
-			$controller->run($_POST);
942
-			exit();
943
-		}
944
-
945
-		$request = \OC::$server->getRequest();
946
-		$requestPath = $request->getRawPathInfo();
947
-		if ($requestPath === '/heartbeat') {
948
-			return;
949
-		}
950
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
951
-			self::checkMaintenanceMode();
952
-
953
-			if (\OCP\Util::needUpgrade()) {
954
-				if (function_exists('opcache_reset')) {
955
-					opcache_reset();
956
-				}
957
-				if (!((bool) $systemConfig->getValue('maintenance', false))) {
958
-					self::printUpgradePage($systemConfig);
959
-					exit();
960
-				}
961
-			}
962
-		}
963
-
964
-		// emergency app disabling
965
-		if ($requestPath === '/disableapp'
966
-			&& $request->getMethod() === 'POST'
967
-			&& ((array)$request->getParam('appid')) !== ''
968
-		) {
969
-			\OC_JSON::callCheck();
970
-			\OC_JSON::checkAdminUser();
971
-			$appIds = (array)$request->getParam('appid');
972
-			foreach ($appIds as $appId) {
973
-				$appId = \OC_App::cleanAppId($appId);
974
-				\OC::$server->getAppManager()->disableApp($appId);
975
-			}
976
-			\OC_JSON::success();
977
-			exit();
978
-		}
979
-
980
-		// Always load authentication apps
981
-		OC_App::loadApps(['authentication']);
982
-
983
-		// Load minimum set of apps
984
-		if (!\OCP\Util::needUpgrade()
985
-			&& !((bool) $systemConfig->getValue('maintenance', false))) {
986
-			// For logged-in users: Load everything
987
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
988
-				OC_App::loadApps();
989
-			} else {
990
-				// For guests: Load only filesystem and logging
991
-				OC_App::loadApps(['filesystem', 'logging']);
992
-				self::handleLogin($request);
993
-			}
994
-		}
995
-
996
-		if (!self::$CLI) {
997
-			try {
998
-				if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
999
-					OC_App::loadApps(['filesystem', 'logging']);
1000
-					OC_App::loadApps();
1001
-				}
1002
-				OC::$server->get(\OC\Route\Router::class)->match(\OC::$server->getRequest()->getRawPathInfo());
1003
-				return;
1004
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1005
-				//header('HTTP/1.0 404 Not Found');
1006
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1007
-				http_response_code(405);
1008
-				return;
1009
-			}
1010
-		}
1011
-
1012
-		// Handle WebDAV
1013
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1014
-			// not allowed any more to prevent people
1015
-			// mounting this root directly.
1016
-			// Users need to mount remote.php/webdav instead.
1017
-			http_response_code(405);
1018
-			return;
1019
-		}
1020
-
1021
-		// Someone is logged in
1022
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1023
-			OC_App::loadApps();
1024
-			OC_User::setupBackends();
1025
-			OC_Util::setupFS();
1026
-			// FIXME
1027
-			// Redirect to default application
1028
-			OC_Util::redirectToDefaultPage();
1029
-		} else {
1030
-			// Not handled and not logged in
1031
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1032
-		}
1033
-	}
1034
-
1035
-	/**
1036
-	 * Check login: apache auth, auth token, basic auth
1037
-	 *
1038
-	 * @param OCP\IRequest $request
1039
-	 * @return boolean
1040
-	 */
1041
-	public static function handleLogin(OCP\IRequest $request) {
1042
-		$userSession = self::$server->getUserSession();
1043
-		if (OC_User::handleApacheAuth()) {
1044
-			return true;
1045
-		}
1046
-		if ($userSession->tryTokenLogin($request)) {
1047
-			return true;
1048
-		}
1049
-		if (isset($_COOKIE['nc_username'])
1050
-			&& isset($_COOKIE['nc_token'])
1051
-			&& isset($_COOKIE['nc_session_id'])
1052
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1053
-			return true;
1054
-		}
1055
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1056
-			return true;
1057
-		}
1058
-		return false;
1059
-	}
1060
-
1061
-	protected static function handleAuthHeaders() {
1062
-		//copy http auth headers for apache+php-fcgid work around
1063
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1064
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1065
-		}
1066
-
1067
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1068
-		$vars = [
1069
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1070
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1071
-		];
1072
-		foreach ($vars as $var) {
1073
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1074
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1075
-				if (count($credentials) === 2) {
1076
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1077
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1078
-					break;
1079
-				}
1080
-			}
1081
-		}
1082
-	}
80
+    /**
81
+     * Associative array for autoloading. classname => filename
82
+     */
83
+    public static $CLASSPATH = [];
84
+    /**
85
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
86
+     */
87
+    public static $SERVERROOT = '';
88
+    /**
89
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
90
+     */
91
+    private static $SUBURI = '';
92
+    /**
93
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
94
+     */
95
+    public static $WEBROOT = '';
96
+    /**
97
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
98
+     * web path in 'url'
99
+     */
100
+    public static $APPSROOTS = [];
101
+
102
+    /**
103
+     * @var string
104
+     */
105
+    public static $configDir;
106
+
107
+    /**
108
+     * requested app
109
+     */
110
+    public static $REQUESTEDAPP = '';
111
+
112
+    /**
113
+     * check if Nextcloud runs in cli mode
114
+     */
115
+    public static $CLI = false;
116
+
117
+    /**
118
+     * @var \OC\Autoloader $loader
119
+     */
120
+    public static $loader = null;
121
+
122
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
123
+    public static $composerAutoloader = null;
124
+
125
+    /**
126
+     * @var \OC\Server
127
+     */
128
+    public static $server = null;
129
+
130
+    /**
131
+     * @var \OC\Config
132
+     */
133
+    private static $config = null;
134
+
135
+    /**
136
+     * @throws \RuntimeException when the 3rdparty directory is missing or
137
+     * the app path list is empty or contains an invalid path
138
+     */
139
+    public static function initPaths() {
140
+        if (defined('PHPUNIT_CONFIG_DIR')) {
141
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
142
+        } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
143
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
144
+        } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
145
+            self::$configDir = rtrim($dir, '/') . '/';
146
+        } else {
147
+            self::$configDir = OC::$SERVERROOT . '/config/';
148
+        }
149
+        self::$config = new \OC\Config(self::$configDir);
150
+
151
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
152
+        /**
153
+         * FIXME: The following lines are required because we can't yet instantiate
154
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
155
+         */
156
+        $params = [
157
+            'server' => [
158
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
159
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
160
+            ],
161
+        ];
162
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, new \OC\Security\SecureRandom(), new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
163
+        $scriptName = $fakeRequest->getScriptName();
164
+        if (substr($scriptName, -1) == '/') {
165
+            $scriptName .= 'index.php';
166
+            //make sure suburi follows the same rules as scriptName
167
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
168
+                if (substr(OC::$SUBURI, -1) != '/') {
169
+                    OC::$SUBURI = OC::$SUBURI . '/';
170
+                }
171
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
172
+            }
173
+        }
174
+
175
+
176
+        if (OC::$CLI) {
177
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
178
+        } else {
179
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
180
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
181
+
182
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
183
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
184
+                }
185
+            } else {
186
+                // The scriptName is not ending with OC::$SUBURI
187
+                // This most likely means that we are calling from CLI.
188
+                // However some cron jobs still need to generate
189
+                // a web URL, so we use overwritewebroot as a fallback.
190
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
191
+            }
192
+
193
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
194
+            // slash which is required by URL generation.
195
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
196
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
197
+                header('Location: '.\OC::$WEBROOT.'/');
198
+                exit();
199
+            }
200
+        }
201
+
202
+        // search the apps folder
203
+        $config_paths = self::$config->getValue('apps_paths', []);
204
+        if (!empty($config_paths)) {
205
+            foreach ($config_paths as $paths) {
206
+                if (isset($paths['url']) && isset($paths['path'])) {
207
+                    $paths['url'] = rtrim($paths['url'], '/');
208
+                    $paths['path'] = rtrim($paths['path'], '/');
209
+                    OC::$APPSROOTS[] = $paths;
210
+                }
211
+            }
212
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
213
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
214
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
215
+            OC::$APPSROOTS[] = [
216
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
217
+                'url' => '/apps',
218
+                'writable' => true
219
+            ];
220
+        }
221
+
222
+        if (empty(OC::$APPSROOTS)) {
223
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
224
+                . ' or the folder above. You can also configure the location in the config.php file.');
225
+        }
226
+        $paths = [];
227
+        foreach (OC::$APPSROOTS as $path) {
228
+            $paths[] = $path['path'];
229
+            if (!is_dir($path['path'])) {
230
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
231
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
232
+                    . ' config.php file.', $path['path']));
233
+            }
234
+        }
235
+
236
+        // set the right include path
237
+        set_include_path(
238
+            implode(PATH_SEPARATOR, $paths)
239
+        );
240
+    }
241
+
242
+    public static function checkConfig() {
243
+        $l = \OC::$server->getL10N('lib');
244
+
245
+        // Create config if it does not already exist
246
+        $configFilePath = self::$configDir .'/config.php';
247
+        if (!file_exists($configFilePath)) {
248
+            @touch($configFilePath);
249
+        }
250
+
251
+        // Check if config is writable
252
+        $configFileWritable = is_writable($configFilePath);
253
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
254
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
255
+            $urlGenerator = \OC::$server->getURLGenerator();
256
+
257
+            if (self::$CLI) {
258
+                echo $l->t('Cannot write into "config" directory!')."\n";
259
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
260
+                echo "\n";
261
+                echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
262
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
263
+                exit;
264
+            } else {
265
+                OC_Template::printErrorPage(
266
+                    $l->t('Cannot write into "config" directory!'),
267
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
268
+                    . $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',
269
+                    [ $urlGenerator->linkToDocs('admin-config') ]),
270
+                    503
271
+                );
272
+            }
273
+        }
274
+    }
275
+
276
+    public static function checkInstalled() {
277
+        if (defined('OC_CONSOLE')) {
278
+            return;
279
+        }
280
+        // Redirect to installer if not installed
281
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
282
+            if (OC::$CLI) {
283
+                throw new Exception('Not installed');
284
+            } else {
285
+                $url = OC::$WEBROOT . '/index.php';
286
+                header('Location: ' . $url);
287
+            }
288
+            exit();
289
+        }
290
+    }
291
+
292
+    public static function checkMaintenanceMode() {
293
+        // Allow ajax update script to execute without being stopped
294
+        if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
295
+            // send http status 503
296
+            http_response_code(503);
297
+            header('Retry-After: 120');
298
+
299
+            // render error page
300
+            $template = new OC_Template('', 'update.user', 'guest');
301
+            OC_Util::addScript('dist/maintenance');
302
+            OC_Util::addStyle('core', 'guest');
303
+            $template->printPage();
304
+            die();
305
+        }
306
+    }
307
+
308
+    /**
309
+     * Prints the upgrade page
310
+     *
311
+     * @param \OC\SystemConfig $systemConfig
312
+     */
313
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
314
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
315
+        $tooBig = false;
316
+        if (!$disableWebUpdater) {
317
+            $apps = \OC::$server->getAppManager();
318
+            if ($apps->isInstalled('user_ldap')) {
319
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
320
+
321
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
322
+                    ->from('ldap_user_mapping')
323
+                    ->execute();
324
+                $row = $result->fetch();
325
+                $result->closeCursor();
326
+
327
+                $tooBig = ($row['user_count'] > 50);
328
+            }
329
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
330
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
331
+
332
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
333
+                    ->from('user_saml_users')
334
+                    ->execute();
335
+                $row = $result->fetch();
336
+                $result->closeCursor();
337
+
338
+                $tooBig = ($row['user_count'] > 50);
339
+            }
340
+            if (!$tooBig) {
341
+                // count users
342
+                $stats = \OC::$server->getUserManager()->countUsers();
343
+                $totalUsers = array_sum($stats);
344
+                $tooBig = ($totalUsers > 50);
345
+            }
346
+        }
347
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
348
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
349
+
350
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
351
+            // send http status 503
352
+            http_response_code(503);
353
+            header('Retry-After: 120');
354
+
355
+            // render error page
356
+            $template = new OC_Template('', 'update.use-cli', 'guest');
357
+            $template->assign('productName', 'nextcloud'); // for now
358
+            $template->assign('version', OC_Util::getVersionString());
359
+            $template->assign('tooBig', $tooBig);
360
+
361
+            $template->printPage();
362
+            die();
363
+        }
364
+
365
+        // check whether this is a core update or apps update
366
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
367
+        $currentVersion = implode('.', \OCP\Util::getVersion());
368
+
369
+        // if not a core upgrade, then it's apps upgrade
370
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
371
+
372
+        $oldTheme = $systemConfig->getValue('theme');
373
+        $systemConfig->setValue('theme', '');
374
+        OC_Util::addScript('update');
375
+
376
+        /** @var \OC\App\AppManager $appManager */
377
+        $appManager = \OC::$server->getAppManager();
378
+
379
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
380
+        $tmpl->assign('version', OC_Util::getVersionString());
381
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
382
+
383
+        // get third party apps
384
+        $ocVersion = \OCP\Util::getVersion();
385
+        $ocVersion = implode('.', $ocVersion);
386
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
387
+        $incompatibleShippedApps = [];
388
+        foreach ($incompatibleApps as $appInfo) {
389
+            if ($appManager->isShipped($appInfo['id'])) {
390
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
391
+            }
392
+        }
393
+
394
+        if (!empty($incompatibleShippedApps)) {
395
+            $l = \OC::$server->getL10N('core');
396
+            $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
397
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
398
+        }
399
+
400
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
401
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
402
+        $tmpl->assign('productName', 'Nextcloud'); // for now
403
+        $tmpl->assign('oldTheme', $oldTheme);
404
+        $tmpl->printPage();
405
+    }
406
+
407
+    public static function initSession() {
408
+        if (self::$server->getRequest()->getServerProtocol() === 'https') {
409
+            ini_set('session.cookie_secure', true);
410
+        }
411
+
412
+        // prevents javascript from accessing php session cookies
413
+        ini_set('session.cookie_httponly', 'true');
414
+
415
+        // set the cookie path to the Nextcloud directory
416
+        $cookie_path = OC::$WEBROOT ? : '/';
417
+        ini_set('session.cookie_path', $cookie_path);
418
+
419
+        // Let the session name be changed in the initSession Hook
420
+        $sessionName = OC_Util::getInstanceId();
421
+
422
+        try {
423
+            // set the session name to the instance id - which is unique
424
+            $session = new \OC\Session\Internal($sessionName);
425
+
426
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
427
+            $session = $cryptoWrapper->wrapSession($session);
428
+            self::$server->setSession($session);
429
+
430
+            // if session can't be started break with http 500 error
431
+        } catch (Exception $e) {
432
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
433
+            //show the user a detailed error page
434
+            OC_Template::printExceptionErrorPage($e, 500);
435
+            die();
436
+        }
437
+
438
+        $sessionLifeTime = self::getSessionLifeTime();
439
+
440
+        // session timeout
441
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
442
+            if (isset($_COOKIE[session_name()])) {
443
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
444
+            }
445
+            \OC::$server->getUserSession()->logout();
446
+        }
447
+
448
+        $session->set('LAST_ACTIVITY', time());
449
+    }
450
+
451
+    /**
452
+     * @return string
453
+     */
454
+    private static function getSessionLifeTime() {
455
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
456
+    }
457
+
458
+    /**
459
+     * Try to set some values to the required Nextcloud default
460
+     */
461
+    public static function setRequiredIniValues() {
462
+        @ini_set('default_charset', 'UTF-8');
463
+        @ini_set('gd.jpeg_ignore_warning', '1');
464
+    }
465
+
466
+    /**
467
+     * Send the same site cookies
468
+     */
469
+    private static function sendSameSiteCookies() {
470
+        $cookieParams = session_get_cookie_params();
471
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
472
+        $policies = [
473
+            'lax',
474
+            'strict',
475
+        ];
476
+
477
+        // Append __Host to the cookie if it meets the requirements
478
+        $cookiePrefix = '';
479
+        if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
480
+            $cookiePrefix = '__Host-';
481
+        }
482
+
483
+        foreach ($policies as $policy) {
484
+            header(
485
+                sprintf(
486
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
487
+                    $cookiePrefix,
488
+                    $policy,
489
+                    $cookieParams['path'],
490
+                    $policy
491
+                ),
492
+                false
493
+            );
494
+        }
495
+    }
496
+
497
+    /**
498
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
499
+     * be set in every request if cookies are sent to add a second level of
500
+     * defense against CSRF.
501
+     *
502
+     * If the cookie is not sent this will set the cookie and reload the page.
503
+     * We use an additional cookie since we want to protect logout CSRF and
504
+     * also we can't directly interfere with PHP's session mechanism.
505
+     */
506
+    private static function performSameSiteCookieProtection() {
507
+        $request = \OC::$server->getRequest();
508
+
509
+        // Some user agents are notorious and don't really properly follow HTTP
510
+        // specifications. For those, have an automated opt-out. Since the protection
511
+        // for remote.php is applied in base.php as starting point we need to opt out
512
+        // here.
513
+        $incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
514
+
515
+        // Fallback, if csrf.optout is unset
516
+        if (!is_array($incompatibleUserAgents)) {
517
+            $incompatibleUserAgents = [
518
+                // OS X Finder
519
+                '/^WebDAVFS/',
520
+                // Windows webdav drive
521
+                '/^Microsoft-WebDAV-MiniRedir/',
522
+            ];
523
+        }
524
+
525
+        if ($request->isUserAgent($incompatibleUserAgents)) {
526
+            return;
527
+        }
528
+
529
+        if (count($_COOKIE) > 0) {
530
+            $requestUri = $request->getScriptName();
531
+            $processingScript = explode('/', $requestUri);
532
+            $processingScript = $processingScript[count($processingScript) - 1];
533
+
534
+            // index.php routes are handled in the middleware
535
+            if ($processingScript === 'index.php') {
536
+                return;
537
+            }
538
+
539
+            // All other endpoints require the lax and the strict cookie
540
+            if (!$request->passesStrictCookieCheck()) {
541
+                self::sendSameSiteCookies();
542
+                // Debug mode gets access to the resources without strict cookie
543
+                // due to the fact that the SabreDAV browser also lives there.
544
+                if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
545
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
546
+                    exit();
547
+                }
548
+            }
549
+        } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
550
+            self::sendSameSiteCookies();
551
+        }
552
+    }
553
+
554
+    public static function init() {
555
+        // calculate the root directories
556
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
557
+
558
+        // register autoloader
559
+        $loaderStart = microtime(true);
560
+        require_once __DIR__ . '/autoloader.php';
561
+        self::$loader = new \OC\Autoloader([
562
+            OC::$SERVERROOT . '/lib/private/legacy',
563
+        ]);
564
+        if (defined('PHPUNIT_RUN')) {
565
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
566
+        }
567
+        spl_autoload_register([self::$loader, 'load']);
568
+        $loaderEnd = microtime(true);
569
+
570
+        self::$CLI = (php_sapi_name() == 'cli');
571
+
572
+        // Add default composer PSR-4 autoloader
573
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
574
+
575
+        try {
576
+            self::initPaths();
577
+            // setup 3rdparty autoloader
578
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
579
+            if (!file_exists($vendorAutoLoad)) {
580
+                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".');
581
+            }
582
+            require_once $vendorAutoLoad;
583
+        } catch (\RuntimeException $e) {
584
+            if (!self::$CLI) {
585
+                http_response_code(503);
586
+            }
587
+            // we can't use the template error page here, because this needs the
588
+            // DI container which isn't available yet
589
+            print($e->getMessage());
590
+            exit();
591
+        }
592
+
593
+        // setup the basic server
594
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
595
+        self::$server->boot();
596
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
597
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
598
+
599
+        // Override php.ini and log everything if we're troubleshooting
600
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
601
+            error_reporting(E_ALL);
602
+        }
603
+
604
+        // Don't display errors and log them
605
+        @ini_set('display_errors', '0');
606
+        @ini_set('log_errors', '1');
607
+
608
+        if (!date_default_timezone_set('UTC')) {
609
+            throw new \RuntimeException('Could not set timezone to UTC');
610
+        }
611
+
612
+        //try to configure php to enable big file uploads.
613
+        //this doesn´t work always depending on the webserver and php configuration.
614
+        //Let´s try to overwrite some defaults anyway
615
+
616
+        //try to set the maximum execution time to 60min
617
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
618
+            @set_time_limit(3600);
619
+        }
620
+        @ini_set('max_execution_time', '3600');
621
+        @ini_set('max_input_time', '3600');
622
+
623
+        self::setRequiredIniValues();
624
+        self::handleAuthHeaders();
625
+        self::registerAutoloaderCache();
626
+
627
+        // initialize intl fallback if necessary
628
+        OC_Util::isSetLocaleWorking();
629
+
630
+        if (!defined('PHPUNIT_RUN')) {
631
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
632
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
633
+            OC\Log\ErrorHandler::register($debug);
634
+        }
635
+
636
+        /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
637
+        $bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
638
+        $bootstrapCoordinator->runInitialRegistration();
639
+
640
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
641
+        OC_App::loadApps(['session']);
642
+        if (!self::$CLI) {
643
+            self::initSession();
644
+        }
645
+        \OC::$server->getEventLogger()->end('init_session');
646
+        self::checkConfig();
647
+        self::checkInstalled();
648
+
649
+        OC_Response::addSecurityHeaders();
650
+
651
+        self::performSameSiteCookieProtection();
652
+
653
+        if (!defined('OC_CONSOLE')) {
654
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
655
+            if (count($errors) > 0) {
656
+                if (!self::$CLI) {
657
+                    http_response_code(503);
658
+                    OC_Util::addStyle('guest');
659
+                    try {
660
+                        OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
661
+                        exit;
662
+                    } catch (\Exception $e) {
663
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
664
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
665
+                    }
666
+                }
667
+
668
+                // Convert l10n string into regular string for usage in database
669
+                $staticErrors = [];
670
+                foreach ($errors as $error) {
671
+                    echo $error['error'] . "\n";
672
+                    echo $error['hint'] . "\n\n";
673
+                    $staticErrors[] = [
674
+                        'error' => (string)$error['error'],
675
+                        'hint' => (string)$error['hint'],
676
+                    ];
677
+                }
678
+
679
+                try {
680
+                    \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
681
+                } catch (\Exception $e) {
682
+                    echo('Writing to database failed');
683
+                }
684
+                exit(1);
685
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
686
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
687
+            }
688
+        }
689
+        //try to set the session lifetime
690
+        $sessionLifeTime = self::getSessionLifeTime();
691
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
692
+
693
+        $systemConfig = \OC::$server->getSystemConfig();
694
+
695
+        // User and Groups
696
+        if (!$systemConfig->getValue("installed", false)) {
697
+            self::$server->getSession()->set('user_id', '');
698
+        }
699
+
700
+        OC_User::useBackend(new \OC\User\Database());
701
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
702
+
703
+        // Subscribe to the hook
704
+        \OCP\Util::connectHook(
705
+            '\OCA\Files_Sharing\API\Server2Server',
706
+            'preLoginNameUsedAsUserName',
707
+            '\OC\User\Database',
708
+            'preLoginNameUsedAsUserName'
709
+        );
710
+
711
+        //setup extra user backends
712
+        if (!\OCP\Util::needUpgrade()) {
713
+            OC_User::setupBackends();
714
+        } else {
715
+            // Run upgrades in incognito mode
716
+            OC_User::setIncognitoMode(true);
717
+        }
718
+
719
+        self::registerCleanupHooks();
720
+        self::registerFilesystemHooks();
721
+        self::registerShareHooks();
722
+        self::registerEncryptionWrapper();
723
+        self::registerEncryptionHooks();
724
+        self::registerAccountHooks();
725
+        self::registerResourceCollectionHooks();
726
+        self::registerAppRestrictionsHooks();
727
+
728
+        // Make sure that the application class is not loaded before the database is setup
729
+        if ($systemConfig->getValue("installed", false)) {
730
+            OC_App::loadApp('settings');
731
+        }
732
+
733
+        //make sure temporary files are cleaned up
734
+        $tmpManager = \OC::$server->getTempManager();
735
+        register_shutdown_function([$tmpManager, 'clean']);
736
+        $lockProvider = \OC::$server->getLockingProvider();
737
+        register_shutdown_function([$lockProvider, 'releaseAll']);
738
+
739
+        // Check whether the sample configuration has been copied
740
+        if ($systemConfig->getValue('copied_sample_config', false)) {
741
+            $l = \OC::$server->getL10N('lib');
742
+            OC_Template::printErrorPage(
743
+                $l->t('Sample configuration detected'),
744
+                $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'),
745
+                503
746
+            );
747
+            return;
748
+        }
749
+
750
+        $request = \OC::$server->getRequest();
751
+        $host = $request->getInsecureServerHost();
752
+        /**
753
+         * if the host passed in headers isn't trusted
754
+         * FIXME: Should not be in here at all :see_no_evil:
755
+         */
756
+        if (!OC::$CLI
757
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
758
+            && self::$server->getConfig()->getSystemValue('installed', false)
759
+        ) {
760
+            // Allow access to CSS resources
761
+            $isScssRequest = false;
762
+            if (strpos($request->getPathInfo(), '/css/') === 0) {
763
+                $isScssRequest = true;
764
+            }
765
+
766
+            if (substr($request->getRequestUri(), -11) === '/status.php') {
767
+                http_response_code(400);
768
+                header('Content-Type: application/json');
769
+                echo '{"error": "Trusted domain error.", "code": 15}';
770
+                exit();
771
+            }
772
+
773
+            if (!$isScssRequest) {
774
+                http_response_code(400);
775
+
776
+                \OC::$server->getLogger()->info(
777
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
778
+                    [
779
+                        'app' => 'core',
780
+                        'remoteAddress' => $request->getRemoteAddress(),
781
+                        'host' => $host,
782
+                    ]
783
+                );
784
+
785
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
786
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
787
+                $tmpl->printPage();
788
+
789
+                exit();
790
+            }
791
+        }
792
+        \OC::$server->getEventLogger()->end('boot');
793
+    }
794
+
795
+    /**
796
+     * register hooks for the cleanup of cache and bruteforce protection
797
+     */
798
+    public static function registerCleanupHooks() {
799
+        //don't try to do this before we are properly setup
800
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
801
+
802
+            // NOTE: This will be replaced to use OCP
803
+            $userSession = self::$server->getUserSession();
804
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
805
+                if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
806
+                    // reset brute force delay for this IP address and username
807
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
808
+                    $request = \OC::$server->getRequest();
809
+                    $throttler = \OC::$server->getBruteForceThrottler();
810
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
811
+                }
812
+
813
+                try {
814
+                    $cache = new \OC\Cache\File();
815
+                    $cache->gc();
816
+                } catch (\OC\ServerNotAvailableException $e) {
817
+                    // not a GC exception, pass it on
818
+                    throw $e;
819
+                } catch (\OC\ForbiddenException $e) {
820
+                    // filesystem blocked for this request, ignore
821
+                } catch (\Exception $e) {
822
+                    // a GC exception should not prevent users from using OC,
823
+                    // so log the exception
824
+                    \OC::$server->getLogger()->logException($e, [
825
+                        'message' => 'Exception when running cache gc.',
826
+                        'level' => ILogger::WARN,
827
+                        'app' => 'core',
828
+                    ]);
829
+                }
830
+            });
831
+        }
832
+    }
833
+
834
+    private static function registerEncryptionWrapper() {
835
+        $manager = self::$server->getEncryptionManager();
836
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
837
+    }
838
+
839
+    private static function registerEncryptionHooks() {
840
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
841
+        if ($enabled) {
842
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
843
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
844
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
845
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
846
+        }
847
+    }
848
+
849
+    private static function registerAccountHooks() {
850
+        $hookHandler = \OC::$server->get(\OC\Accounts\Hooks::class);
851
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
852
+    }
853
+
854
+    private static function registerAppRestrictionsHooks() {
855
+        /** @var \OC\Group\Manager $groupManager */
856
+        $groupManager = self::$server->query(\OCP\IGroupManager::class);
857
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
858
+            $appManager = self::$server->getAppManager();
859
+            $apps = $appManager->getEnabledAppsForGroup($group);
860
+            foreach ($apps as $appId) {
861
+                $restrictions = $appManager->getAppRestriction($appId);
862
+                if (empty($restrictions)) {
863
+                    continue;
864
+                }
865
+                $key = array_search($group->getGID(), $restrictions);
866
+                unset($restrictions[$key]);
867
+                $restrictions = array_values($restrictions);
868
+                if (empty($restrictions)) {
869
+                    $appManager->disableApp($appId);
870
+                } else {
871
+                    $appManager->enableAppForGroups($appId, $restrictions);
872
+                }
873
+            }
874
+        });
875
+    }
876
+
877
+    private static function registerResourceCollectionHooks() {
878
+        \OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
879
+    }
880
+
881
+    /**
882
+     * register hooks for the filesystem
883
+     */
884
+    public static function registerFilesystemHooks() {
885
+        // Check for blacklisted files
886
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
887
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
888
+    }
889
+
890
+    /**
891
+     * register hooks for sharing
892
+     */
893
+    public static function registerShareHooks() {
894
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
895
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
896
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
897
+
898
+            /** @var IEventDispatcher $dispatcher */
899
+            $dispatcher = \OC::$server->get(IEventDispatcher::class);
900
+            $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
901
+        }
902
+    }
903
+
904
+    protected static function registerAutoloaderCache() {
905
+        // The class loader takes an optional low-latency cache, which MUST be
906
+        // namespaced. The instanceid is used for namespacing, but might be
907
+        // unavailable at this point. Furthermore, it might not be possible to
908
+        // generate an instanceid via \OC_Util::getInstanceId() because the
909
+        // config file may not be writable. As such, we only register a class
910
+        // loader cache if instanceid is available without trying to create one.
911
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
912
+        if ($instanceId) {
913
+            try {
914
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
915
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
916
+            } catch (\Exception $ex) {
917
+            }
918
+        }
919
+    }
920
+
921
+    /**
922
+     * Handle the request
923
+     */
924
+    public static function handleRequest() {
925
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
926
+        $systemConfig = \OC::$server->getSystemConfig();
927
+
928
+        // Check if Nextcloud is installed or in maintenance (update) mode
929
+        if (!$systemConfig->getValue('installed', false)) {
930
+            \OC::$server->getSession()->clear();
931
+            $setupHelper = new OC\Setup(
932
+                $systemConfig,
933
+                \OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
934
+                \OC::$server->getL10N('lib'),
935
+                \OC::$server->query(\OCP\Defaults::class),
936
+                \OC::$server->getLogger(),
937
+                \OC::$server->getSecureRandom(),
938
+                \OC::$server->query(\OC\Installer::class)
939
+            );
940
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
941
+            $controller->run($_POST);
942
+            exit();
943
+        }
944
+
945
+        $request = \OC::$server->getRequest();
946
+        $requestPath = $request->getRawPathInfo();
947
+        if ($requestPath === '/heartbeat') {
948
+            return;
949
+        }
950
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
951
+            self::checkMaintenanceMode();
952
+
953
+            if (\OCP\Util::needUpgrade()) {
954
+                if (function_exists('opcache_reset')) {
955
+                    opcache_reset();
956
+                }
957
+                if (!((bool) $systemConfig->getValue('maintenance', false))) {
958
+                    self::printUpgradePage($systemConfig);
959
+                    exit();
960
+                }
961
+            }
962
+        }
963
+
964
+        // emergency app disabling
965
+        if ($requestPath === '/disableapp'
966
+            && $request->getMethod() === 'POST'
967
+            && ((array)$request->getParam('appid')) !== ''
968
+        ) {
969
+            \OC_JSON::callCheck();
970
+            \OC_JSON::checkAdminUser();
971
+            $appIds = (array)$request->getParam('appid');
972
+            foreach ($appIds as $appId) {
973
+                $appId = \OC_App::cleanAppId($appId);
974
+                \OC::$server->getAppManager()->disableApp($appId);
975
+            }
976
+            \OC_JSON::success();
977
+            exit();
978
+        }
979
+
980
+        // Always load authentication apps
981
+        OC_App::loadApps(['authentication']);
982
+
983
+        // Load minimum set of apps
984
+        if (!\OCP\Util::needUpgrade()
985
+            && !((bool) $systemConfig->getValue('maintenance', false))) {
986
+            // For logged-in users: Load everything
987
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
988
+                OC_App::loadApps();
989
+            } else {
990
+                // For guests: Load only filesystem and logging
991
+                OC_App::loadApps(['filesystem', 'logging']);
992
+                self::handleLogin($request);
993
+            }
994
+        }
995
+
996
+        if (!self::$CLI) {
997
+            try {
998
+                if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
999
+                    OC_App::loadApps(['filesystem', 'logging']);
1000
+                    OC_App::loadApps();
1001
+                }
1002
+                OC::$server->get(\OC\Route\Router::class)->match(\OC::$server->getRequest()->getRawPathInfo());
1003
+                return;
1004
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1005
+                //header('HTTP/1.0 404 Not Found');
1006
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1007
+                http_response_code(405);
1008
+                return;
1009
+            }
1010
+        }
1011
+
1012
+        // Handle WebDAV
1013
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1014
+            // not allowed any more to prevent people
1015
+            // mounting this root directly.
1016
+            // Users need to mount remote.php/webdav instead.
1017
+            http_response_code(405);
1018
+            return;
1019
+        }
1020
+
1021
+        // Someone is logged in
1022
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1023
+            OC_App::loadApps();
1024
+            OC_User::setupBackends();
1025
+            OC_Util::setupFS();
1026
+            // FIXME
1027
+            // Redirect to default application
1028
+            OC_Util::redirectToDefaultPage();
1029
+        } else {
1030
+            // Not handled and not logged in
1031
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1032
+        }
1033
+    }
1034
+
1035
+    /**
1036
+     * Check login: apache auth, auth token, basic auth
1037
+     *
1038
+     * @param OCP\IRequest $request
1039
+     * @return boolean
1040
+     */
1041
+    public static function handleLogin(OCP\IRequest $request) {
1042
+        $userSession = self::$server->getUserSession();
1043
+        if (OC_User::handleApacheAuth()) {
1044
+            return true;
1045
+        }
1046
+        if ($userSession->tryTokenLogin($request)) {
1047
+            return true;
1048
+        }
1049
+        if (isset($_COOKIE['nc_username'])
1050
+            && isset($_COOKIE['nc_token'])
1051
+            && isset($_COOKIE['nc_session_id'])
1052
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1053
+            return true;
1054
+        }
1055
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1056
+            return true;
1057
+        }
1058
+        return false;
1059
+    }
1060
+
1061
+    protected static function handleAuthHeaders() {
1062
+        //copy http auth headers for apache+php-fcgid work around
1063
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1064
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1065
+        }
1066
+
1067
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1068
+        $vars = [
1069
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1070
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1071
+        ];
1072
+        foreach ($vars as $var) {
1073
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1074
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1075
+                if (count($credentials) === 2) {
1076
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1077
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1078
+                    break;
1079
+                }
1080
+            }
1081
+        }
1082
+    }
1083 1083
 }
1084 1084
 
1085 1085
 OC::init();
Please login to merge, or discard this patch.