Passed
Push — master ( 586450...f3768e )
by Roeland
11:34 queued 12s
created
lib/private/legacy/OC_Util.php 1 patch
Indentation   +1384 added lines, -1384 removed lines patch added patch discarded remove patch
@@ -70,1393 +70,1393 @@
 block discarded – undo
70 70
 use OCP\IUser;
71 71
 
72 72
 class OC_Util {
73
-	public static $scripts = [];
74
-	public static $styles = [];
75
-	public static $headers = [];
76
-	private static $rootMounted = false;
77
-	private static $fsSetup = false;
78
-
79
-	/** @var array Local cache of version.php */
80
-	private static $versionCache = null;
81
-
82
-	protected static function getAppManager() {
83
-		return \OC::$server->getAppManager();
84
-	}
85
-
86
-	private static function initLocalStorageRootFS() {
87
-		// mount local file backend as root
88
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
89
-		//first set up the local "root" storage
90
-		\OC\Files\Filesystem::initMountManager();
91
-		if (!self::$rootMounted) {
92
-			\OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
93
-			self::$rootMounted = true;
94
-		}
95
-	}
96
-
97
-	/**
98
-	 * mounting an object storage as the root fs will in essence remove the
99
-	 * necessity of a data folder being present.
100
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
101
-	 *
102
-	 * @param array $config containing 'class' and optional 'arguments'
103
-	 * @suppress PhanDeprecatedFunction
104
-	 */
105
-	private static function initObjectStoreRootFS($config) {
106
-		// check misconfiguration
107
-		if (empty($config['class'])) {
108
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
109
-		}
110
-		if (!isset($config['arguments'])) {
111
-			$config['arguments'] = [];
112
-		}
113
-
114
-		// instantiate object store implementation
115
-		$name = $config['class'];
116
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
117
-			$segments = explode('\\', $name);
118
-			OC_App::loadApp(strtolower($segments[1]));
119
-		}
120
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
121
-		// mount with plain / root object store implementation
122
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
123
-
124
-		// mount object storage as root
125
-		\OC\Files\Filesystem::initMountManager();
126
-		if (!self::$rootMounted) {
127
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
128
-			self::$rootMounted = true;
129
-		}
130
-	}
131
-
132
-	/**
133
-	 * mounting an object storage as the root fs will in essence remove the
134
-	 * necessity of a data folder being present.
135
-	 *
136
-	 * @param array $config containing 'class' and optional 'arguments'
137
-	 * @suppress PhanDeprecatedFunction
138
-	 */
139
-	private static function initObjectStoreMultibucketRootFS($config) {
140
-		// check misconfiguration
141
-		if (empty($config['class'])) {
142
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
143
-		}
144
-		if (!isset($config['arguments'])) {
145
-			$config['arguments'] = [];
146
-		}
147
-
148
-		// instantiate object store implementation
149
-		$name = $config['class'];
150
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
151
-			$segments = explode('\\', $name);
152
-			OC_App::loadApp(strtolower($segments[1]));
153
-		}
154
-
155
-		if (!isset($config['arguments']['bucket'])) {
156
-			$config['arguments']['bucket'] = '';
157
-		}
158
-		// put the root FS always in first bucket for multibucket configuration
159
-		$config['arguments']['bucket'] .= '0';
160
-
161
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
162
-		// mount with plain / root object store implementation
163
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
164
-
165
-		// mount object storage as root
166
-		\OC\Files\Filesystem::initMountManager();
167
-		if (!self::$rootMounted) {
168
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
169
-			self::$rootMounted = true;
170
-		}
171
-	}
172
-
173
-	/**
174
-	 * Can be set up
175
-	 *
176
-	 * @param string $user
177
-	 * @return boolean
178
-	 * @description configure the initial filesystem based on the configuration
179
-	 * @suppress PhanDeprecatedFunction
180
-	 * @suppress PhanAccessMethodInternal
181
-	 */
182
-	public static function setupFS($user = '') {
183
-		//setting up the filesystem twice can only lead to trouble
184
-		if (self::$fsSetup) {
185
-			return false;
186
-		}
187
-
188
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
189
-
190
-		// If we are not forced to load a specific user we load the one that is logged in
191
-		if ($user === null) {
192
-			$user = '';
193
-		} elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
194
-			$user = OC_User::getUser();
195
-		}
196
-
197
-		// load all filesystem apps before, so no setup-hook gets lost
198
-		OC_App::loadApps(['filesystem']);
199
-
200
-		// the filesystem will finish when $user is not empty,
201
-		// mark fs setup here to avoid doing the setup from loading
202
-		// OC_Filesystem
203
-		if ($user != '') {
204
-			self::$fsSetup = true;
205
-		}
206
-
207
-		\OC\Files\Filesystem::initMountManager();
208
-
209
-		$prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
210
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
211
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
212
-				/** @var \OC\Files\Storage\Common $storage */
213
-				$storage->setMountOptions($mount->getOptions());
214
-			}
215
-			return $storage;
216
-		});
217
-
218
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
219
-			if (!$mount->getOption('enable_sharing', true)) {
220
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
221
-					'storage' => $storage,
222
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
223
-				]);
224
-			}
225
-			return $storage;
226
-		});
227
-
228
-		// install storage availability wrapper, before most other wrappers
229
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
230
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
231
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
232
-			}
233
-			return $storage;
234
-		});
235
-
236
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
237
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
238
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
239
-			}
240
-			return $storage;
241
-		});
242
-
243
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
244
-			// set up quota for home storages, even for other users
245
-			// which can happen when using sharing
246
-
247
-			/**
248
-			 * @var \OC\Files\Storage\Storage $storage
249
-			 */
250
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
251
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
252
-			) {
253
-				/** @var \OC\Files\Storage\Home $storage */
254
-				if (is_object($storage->getUser())) {
255
-					$quota = OC_Util::getUserQuota($storage->getUser());
256
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
257
-						return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
258
-					}
259
-				}
260
-			}
261
-
262
-			return $storage;
263
-		});
264
-
265
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
266
-			/*
73
+    public static $scripts = [];
74
+    public static $styles = [];
75
+    public static $headers = [];
76
+    private static $rootMounted = false;
77
+    private static $fsSetup = false;
78
+
79
+    /** @var array Local cache of version.php */
80
+    private static $versionCache = null;
81
+
82
+    protected static function getAppManager() {
83
+        return \OC::$server->getAppManager();
84
+    }
85
+
86
+    private static function initLocalStorageRootFS() {
87
+        // mount local file backend as root
88
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
89
+        //first set up the local "root" storage
90
+        \OC\Files\Filesystem::initMountManager();
91
+        if (!self::$rootMounted) {
92
+            \OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
93
+            self::$rootMounted = true;
94
+        }
95
+    }
96
+
97
+    /**
98
+     * mounting an object storage as the root fs will in essence remove the
99
+     * necessity of a data folder being present.
100
+     * TODO make home storage aware of this and use the object storage instead of local disk access
101
+     *
102
+     * @param array $config containing 'class' and optional 'arguments'
103
+     * @suppress PhanDeprecatedFunction
104
+     */
105
+    private static function initObjectStoreRootFS($config) {
106
+        // check misconfiguration
107
+        if (empty($config['class'])) {
108
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
109
+        }
110
+        if (!isset($config['arguments'])) {
111
+            $config['arguments'] = [];
112
+        }
113
+
114
+        // instantiate object store implementation
115
+        $name = $config['class'];
116
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
117
+            $segments = explode('\\', $name);
118
+            OC_App::loadApp(strtolower($segments[1]));
119
+        }
120
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
121
+        // mount with plain / root object store implementation
122
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
123
+
124
+        // mount object storage as root
125
+        \OC\Files\Filesystem::initMountManager();
126
+        if (!self::$rootMounted) {
127
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
128
+            self::$rootMounted = true;
129
+        }
130
+    }
131
+
132
+    /**
133
+     * mounting an object storage as the root fs will in essence remove the
134
+     * necessity of a data folder being present.
135
+     *
136
+     * @param array $config containing 'class' and optional 'arguments'
137
+     * @suppress PhanDeprecatedFunction
138
+     */
139
+    private static function initObjectStoreMultibucketRootFS($config) {
140
+        // check misconfiguration
141
+        if (empty($config['class'])) {
142
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
143
+        }
144
+        if (!isset($config['arguments'])) {
145
+            $config['arguments'] = [];
146
+        }
147
+
148
+        // instantiate object store implementation
149
+        $name = $config['class'];
150
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
151
+            $segments = explode('\\', $name);
152
+            OC_App::loadApp(strtolower($segments[1]));
153
+        }
154
+
155
+        if (!isset($config['arguments']['bucket'])) {
156
+            $config['arguments']['bucket'] = '';
157
+        }
158
+        // put the root FS always in first bucket for multibucket configuration
159
+        $config['arguments']['bucket'] .= '0';
160
+
161
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
162
+        // mount with plain / root object store implementation
163
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
164
+
165
+        // mount object storage as root
166
+        \OC\Files\Filesystem::initMountManager();
167
+        if (!self::$rootMounted) {
168
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
169
+            self::$rootMounted = true;
170
+        }
171
+    }
172
+
173
+    /**
174
+     * Can be set up
175
+     *
176
+     * @param string $user
177
+     * @return boolean
178
+     * @description configure the initial filesystem based on the configuration
179
+     * @suppress PhanDeprecatedFunction
180
+     * @suppress PhanAccessMethodInternal
181
+     */
182
+    public static function setupFS($user = '') {
183
+        //setting up the filesystem twice can only lead to trouble
184
+        if (self::$fsSetup) {
185
+            return false;
186
+        }
187
+
188
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
189
+
190
+        // If we are not forced to load a specific user we load the one that is logged in
191
+        if ($user === null) {
192
+            $user = '';
193
+        } elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
194
+            $user = OC_User::getUser();
195
+        }
196
+
197
+        // load all filesystem apps before, so no setup-hook gets lost
198
+        OC_App::loadApps(['filesystem']);
199
+
200
+        // the filesystem will finish when $user is not empty,
201
+        // mark fs setup here to avoid doing the setup from loading
202
+        // OC_Filesystem
203
+        if ($user != '') {
204
+            self::$fsSetup = true;
205
+        }
206
+
207
+        \OC\Files\Filesystem::initMountManager();
208
+
209
+        $prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
210
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
211
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
212
+                /** @var \OC\Files\Storage\Common $storage */
213
+                $storage->setMountOptions($mount->getOptions());
214
+            }
215
+            return $storage;
216
+        });
217
+
218
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
219
+            if (!$mount->getOption('enable_sharing', true)) {
220
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
221
+                    'storage' => $storage,
222
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
223
+                ]);
224
+            }
225
+            return $storage;
226
+        });
227
+
228
+        // install storage availability wrapper, before most other wrappers
229
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
230
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
231
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
232
+            }
233
+            return $storage;
234
+        });
235
+
236
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
237
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
238
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
239
+            }
240
+            return $storage;
241
+        });
242
+
243
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
244
+            // set up quota for home storages, even for other users
245
+            // which can happen when using sharing
246
+
247
+            /**
248
+             * @var \OC\Files\Storage\Storage $storage
249
+             */
250
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
251
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
252
+            ) {
253
+                /** @var \OC\Files\Storage\Home $storage */
254
+                if (is_object($storage->getUser())) {
255
+                    $quota = OC_Util::getUserQuota($storage->getUser());
256
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
257
+                        return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
258
+                    }
259
+                }
260
+            }
261
+
262
+            return $storage;
263
+        });
264
+
265
+        \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
266
+            /*
267 267
 			 * Do not allow any operations that modify the storage
268 268
 			 */
269
-			if ($mount->getOption('readonly', false)) {
270
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
271
-					'storage' => $storage,
272
-					'mask' => \OCP\Constants::PERMISSION_ALL & ~(
273
-						\OCP\Constants::PERMISSION_UPDATE |
274
-						\OCP\Constants::PERMISSION_CREATE |
275
-						\OCP\Constants::PERMISSION_DELETE
276
-					),
277
-				]);
278
-			}
279
-			return $storage;
280
-		});
281
-
282
-		OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
283
-
284
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
285
-
286
-		//check if we are using an object storage
287
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
288
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
289
-
290
-		// use the same order as in ObjectHomeMountProvider
291
-		if (isset($objectStoreMultibucket)) {
292
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
293
-		} elseif (isset($objectStore)) {
294
-			self::initObjectStoreRootFS($objectStore);
295
-		} else {
296
-			self::initLocalStorageRootFS();
297
-		}
298
-
299
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
300
-			\OC::$server->getEventLogger()->end('setup_fs');
301
-			return false;
302
-		}
303
-
304
-		//if we aren't logged in, there is no use to set up the filesystem
305
-		if ($user != "") {
306
-			$userDir = '/' . $user . '/files';
307
-
308
-			//jail the user into his "home" directory
309
-			\OC\Files\Filesystem::init($user, $userDir);
310
-
311
-			OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
312
-		}
313
-		\OC::$server->getEventLogger()->end('setup_fs');
314
-		return true;
315
-	}
316
-
317
-	/**
318
-	 * check if a password is required for each public link
319
-	 *
320
-	 * @return boolean
321
-	 * @suppress PhanDeprecatedFunction
322
-	 */
323
-	public static function isPublicLinkPasswordRequired() {
324
-		$enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
325
-		return $enforcePassword === 'yes';
326
-	}
327
-
328
-	/**
329
-	 * check if sharing is disabled for the current user
330
-	 * @param IConfig $config
331
-	 * @param IGroupManager $groupManager
332
-	 * @param IUser|null $user
333
-	 * @return bool
334
-	 */
335
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
336
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
337
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
338
-			$excludedGroups = json_decode($groupsList);
339
-			if (is_null($excludedGroups)) {
340
-				$excludedGroups = explode(',', $groupsList);
341
-				$newValue = json_encode($excludedGroups);
342
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
343
-			}
344
-			$usersGroups = $groupManager->getUserGroupIds($user);
345
-			if (!empty($usersGroups)) {
346
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
347
-				// if the user is only in groups which are disabled for sharing then
348
-				// sharing is also disabled for the user
349
-				if (empty($remainingGroups)) {
350
-					return true;
351
-				}
352
-			}
353
-		}
354
-		return false;
355
-	}
356
-
357
-	/**
358
-	 * check if share API enforces a default expire date
359
-	 *
360
-	 * @return boolean
361
-	 * @suppress PhanDeprecatedFunction
362
-	 */
363
-	public static function isDefaultExpireDateEnforced() {
364
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
365
-		$enforceDefaultExpireDate = false;
366
-		if ($isDefaultExpireDateEnabled === 'yes') {
367
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
368
-			$enforceDefaultExpireDate = $value === 'yes';
369
-		}
370
-
371
-		return $enforceDefaultExpireDate;
372
-	}
373
-
374
-	/**
375
-	 * Get the quota of a user
376
-	 *
377
-	 * @param IUser|null $user
378
-	 * @return float Quota bytes
379
-	 */
380
-	public static function getUserQuota(?IUser $user) {
381
-		if (is_null($user)) {
382
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
383
-		}
384
-		$userQuota = $user->getQuota();
385
-		if ($userQuota === 'none') {
386
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
387
-		}
388
-		return OC_Helper::computerFileSize($userQuota);
389
-	}
390
-
391
-	/**
392
-	 * copies the skeleton to the users /files
393
-	 *
394
-	 * @param string $userId
395
-	 * @param \OCP\Files\Folder $userDirectory
396
-	 * @throws \OCP\Files\NotFoundException
397
-	 * @throws \OCP\Files\NotPermittedException
398
-	 * @suppress PhanDeprecatedFunction
399
-	 */
400
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
401
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
402
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
403
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
404
-
405
-		if (!file_exists($skeletonDirectory)) {
406
-			$dialectStart = strpos($userLang, '_');
407
-			if ($dialectStart !== false) {
408
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
409
-			}
410
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
411
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
412
-			}
413
-			if (!file_exists($skeletonDirectory)) {
414
-				$skeletonDirectory = '';
415
-			}
416
-		}
417
-
418
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
419
-
420
-		if ($instanceId === null) {
421
-			throw new \RuntimeException('no instance id!');
422
-		}
423
-		$appdata = 'appdata_' . $instanceId;
424
-		if ($userId === $appdata) {
425
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
426
-		}
427
-
428
-		if (!empty($skeletonDirectory)) {
429
-			\OCP\Util::writeLog(
430
-				'files_skeleton',
431
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
432
-				ILogger::DEBUG
433
-			);
434
-			self::copyr($skeletonDirectory, $userDirectory);
435
-			// update the file cache
436
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
437
-		}
438
-	}
439
-
440
-	/**
441
-	 * copies a directory recursively by using streams
442
-	 *
443
-	 * @param string $source
444
-	 * @param \OCP\Files\Folder $target
445
-	 * @return void
446
-	 */
447
-	public static function copyr($source, \OCP\Files\Folder $target) {
448
-		$logger = \OC::$server->getLogger();
449
-
450
-		// Verify if folder exists
451
-		$dir = opendir($source);
452
-		if ($dir === false) {
453
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
454
-			return;
455
-		}
456
-
457
-		// Copy the files
458
-		while (false !== ($file = readdir($dir))) {
459
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
460
-				if (is_dir($source . '/' . $file)) {
461
-					$child = $target->newFolder($file);
462
-					self::copyr($source . '/' . $file, $child);
463
-				} else {
464
-					$child = $target->newFile($file);
465
-					$sourceStream = fopen($source . '/' . $file, 'r');
466
-					if ($sourceStream === false) {
467
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
468
-						closedir($dir);
469
-						return;
470
-					}
471
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
472
-				}
473
-			}
474
-		}
475
-		closedir($dir);
476
-	}
477
-
478
-	/**
479
-	 * @return void
480
-	 * @suppress PhanUndeclaredMethod
481
-	 */
482
-	public static function tearDownFS() {
483
-		\OC\Files\Filesystem::tearDown();
484
-		\OC::$server->getRootFolder()->clearCache();
485
-		self::$fsSetup = false;
486
-		self::$rootMounted = false;
487
-	}
488
-
489
-	/**
490
-	 * get the current installed version of ownCloud
491
-	 *
492
-	 * @return array
493
-	 */
494
-	public static function getVersion() {
495
-		OC_Util::loadVersion();
496
-		return self::$versionCache['OC_Version'];
497
-	}
498
-
499
-	/**
500
-	 * get the current installed version string of ownCloud
501
-	 *
502
-	 * @return string
503
-	 */
504
-	public static function getVersionString() {
505
-		OC_Util::loadVersion();
506
-		return self::$versionCache['OC_VersionString'];
507
-	}
508
-
509
-	/**
510
-	 * @deprecated the value is of no use anymore
511
-	 * @return string
512
-	 */
513
-	public static function getEditionString() {
514
-		return '';
515
-	}
516
-
517
-	/**
518
-	 * @description get the update channel of the current installed of ownCloud.
519
-	 * @return string
520
-	 */
521
-	public static function getChannel() {
522
-		OC_Util::loadVersion();
523
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
524
-	}
525
-
526
-	/**
527
-	 * @description get the build number of the current installed of ownCloud.
528
-	 * @return string
529
-	 */
530
-	public static function getBuild() {
531
-		OC_Util::loadVersion();
532
-		return self::$versionCache['OC_Build'];
533
-	}
534
-
535
-	/**
536
-	 * @description load the version.php into the session as cache
537
-	 * @suppress PhanUndeclaredVariable
538
-	 */
539
-	private static function loadVersion() {
540
-		if (self::$versionCache !== null) {
541
-			return;
542
-		}
543
-
544
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
545
-		require OC::$SERVERROOT . '/version.php';
546
-		/** @var $timestamp int */
547
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
548
-		/** @var $OC_Version string */
549
-		self::$versionCache['OC_Version'] = $OC_Version;
550
-		/** @var $OC_VersionString string */
551
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
552
-		/** @var $OC_Build string */
553
-		self::$versionCache['OC_Build'] = $OC_Build;
554
-
555
-		/** @var $OC_Channel string */
556
-		self::$versionCache['OC_Channel'] = $OC_Channel;
557
-	}
558
-
559
-	/**
560
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
561
-	 *
562
-	 * @param string $application application to get the files from
563
-	 * @param string $directory directory within this application (css, js, vendor, etc)
564
-	 * @param string $file the file inside of the above folder
565
-	 * @return string the path
566
-	 */
567
-	private static function generatePath($application, $directory, $file) {
568
-		if (is_null($file)) {
569
-			$file = $application;
570
-			$application = "";
571
-		}
572
-		if (!empty($application)) {
573
-			return "$application/$directory/$file";
574
-		} else {
575
-			return "$directory/$file";
576
-		}
577
-	}
578
-
579
-	/**
580
-	 * add a javascript file
581
-	 *
582
-	 * @param string $application application id
583
-	 * @param string|null $file filename
584
-	 * @param bool $prepend prepend the Script to the beginning of the list
585
-	 * @return void
586
-	 */
587
-	public static function addScript($application, $file = null, $prepend = false) {
588
-		$path = OC_Util::generatePath($application, 'js', $file);
589
-
590
-		// core js files need separate handling
591
-		if ($application !== 'core' && $file !== null) {
592
-			self::addTranslations($application);
593
-		}
594
-		self::addExternalResource($application, $prepend, $path, "script");
595
-	}
596
-
597
-	/**
598
-	 * add a javascript file from the vendor sub folder
599
-	 *
600
-	 * @param string $application application id
601
-	 * @param string|null $file filename
602
-	 * @param bool $prepend prepend the Script to the beginning of the list
603
-	 * @return void
604
-	 */
605
-	public static function addVendorScript($application, $file = null, $prepend = false) {
606
-		$path = OC_Util::generatePath($application, 'vendor', $file);
607
-		self::addExternalResource($application, $prepend, $path, "script");
608
-	}
609
-
610
-	/**
611
-	 * add a translation JS file
612
-	 *
613
-	 * @param string $application application id
614
-	 * @param string|null $languageCode language code, defaults to the current language
615
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
616
-	 */
617
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
618
-		if (is_null($languageCode)) {
619
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
620
-		}
621
-		if (!empty($application)) {
622
-			$path = "$application/l10n/$languageCode";
623
-		} else {
624
-			$path = "l10n/$languageCode";
625
-		}
626
-		self::addExternalResource($application, $prepend, $path, "script");
627
-	}
628
-
629
-	/**
630
-	 * add a css file
631
-	 *
632
-	 * @param string $application application id
633
-	 * @param string|null $file filename
634
-	 * @param bool $prepend prepend the Style to the beginning of the list
635
-	 * @return void
636
-	 */
637
-	public static function addStyle($application, $file = null, $prepend = false) {
638
-		$path = OC_Util::generatePath($application, 'css', $file);
639
-		self::addExternalResource($application, $prepend, $path, "style");
640
-	}
641
-
642
-	/**
643
-	 * add a css file from the vendor sub folder
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 addVendorStyle($application, $file = null, $prepend = false) {
651
-		$path = OC_Util::generatePath($application, 'vendor', $file);
652
-		self::addExternalResource($application, $prepend, $path, "style");
653
-	}
654
-
655
-	/**
656
-	 * add an external resource css/js file
657
-	 *
658
-	 * @param string $application application id
659
-	 * @param bool $prepend prepend the file to the beginning of the list
660
-	 * @param string $path
661
-	 * @param string $type (script or style)
662
-	 * @return void
663
-	 */
664
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
665
-		if ($type === "style") {
666
-			if (!in_array($path, self::$styles)) {
667
-				if ($prepend === true) {
668
-					array_unshift(self::$styles, $path);
669
-				} else {
670
-					self::$styles[] = $path;
671
-				}
672
-			}
673
-		} elseif ($type === "script") {
674
-			if (!in_array($path, self::$scripts)) {
675
-				if ($prepend === true) {
676
-					array_unshift(self::$scripts, $path);
677
-				} else {
678
-					self::$scripts [] = $path;
679
-				}
680
-			}
681
-		}
682
-	}
683
-
684
-	/**
685
-	 * Add a custom element to the header
686
-	 * If $text is null then the element will be written as empty element.
687
-	 * So use "" to get a closing tag.
688
-	 * @param string $tag tag name of the element
689
-	 * @param array $attributes array of attributes for the element
690
-	 * @param string $text the text content for the element
691
-	 * @param bool $prepend prepend the header to the beginning of the list
692
-	 */
693
-	public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
694
-		$header = [
695
-			'tag' => $tag,
696
-			'attributes' => $attributes,
697
-			'text' => $text
698
-		];
699
-		if ($prepend === true) {
700
-			array_unshift(self::$headers, $header);
701
-		} else {
702
-			self::$headers[] = $header;
703
-		}
704
-	}
705
-
706
-	/**
707
-	 * check if the current server configuration is suitable for ownCloud
708
-	 *
709
-	 * @param \OC\SystemConfig $config
710
-	 * @return array arrays with error messages and hints
711
-	 */
712
-	public static function checkServer(\OC\SystemConfig $config) {
713
-		$l = \OC::$server->getL10N('lib');
714
-		$errors = [];
715
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
716
-
717
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
718
-			// this check needs to be done every time
719
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
720
-		}
721
-
722
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
723
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
724
-			return $errors;
725
-		}
726
-
727
-		$webServerRestart = false;
728
-		$setup = new \OC\Setup(
729
-			$config,
730
-			\OC::$server->getIniWrapper(),
731
-			\OC::$server->getL10N('lib'),
732
-			\OC::$server->query(\OCP\Defaults::class),
733
-			\OC::$server->getLogger(),
734
-			\OC::$server->getSecureRandom(),
735
-			\OC::$server->query(\OC\Installer::class)
736
-		);
737
-
738
-		$urlGenerator = \OC::$server->getURLGenerator();
739
-
740
-		$availableDatabases = $setup->getSupportedDatabases();
741
-		if (empty($availableDatabases)) {
742
-			$errors[] = [
743
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
744
-				'hint' => '' //TODO: sane hint
745
-			];
746
-			$webServerRestart = true;
747
-		}
748
-
749
-		// Check if config folder is writable.
750
-		if (!OC_Helper::isReadOnlyConfigEnabled()) {
751
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
752
-				$errors[] = [
753
-					'error' => $l->t('Cannot write into "config" directory'),
754
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
755
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
756
-						. $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',
757
-						[ $urlGenerator->linkToDocs('admin-config') ])
758
-				];
759
-			}
760
-		}
761
-
762
-		// Check if there is a writable install folder.
763
-		if ($config->getValue('appstoreenabled', true)) {
764
-			if (OC_App::getInstallPath() === null
765
-				|| !is_writable(OC_App::getInstallPath())
766
-				|| !is_readable(OC_App::getInstallPath())
767
-			) {
768
-				$errors[] = [
769
-					'error' => $l->t('Cannot write into "apps" directory'),
770
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
771
-						. ' or disabling the appstore in the config file.')
772
-				];
773
-			}
774
-		}
775
-		// Create root dir.
776
-		if ($config->getValue('installed', false)) {
777
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
778
-				$success = @mkdir($CONFIG_DATADIRECTORY);
779
-				if ($success) {
780
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
781
-				} else {
782
-					$errors[] = [
783
-						'error' => $l->t('Cannot create "data" directory'),
784
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
785
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
786
-					];
787
-				}
788
-			} elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
789
-				// is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
790
-				$testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
791
-				$handle = fopen($testFile, 'w');
792
-				if (!$handle || fwrite($handle, 'Test write operation') === false) {
793
-					$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
794
-						[$urlGenerator->linkToDocs('admin-dir_permissions')]);
795
-					$errors[] = [
796
-						'error' => 'Your data directory is not writable',
797
-						'hint' => $permissionsHint
798
-					];
799
-				} else {
800
-					fclose($handle);
801
-					unlink($testFile);
802
-				}
803
-			} else {
804
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
805
-			}
806
-		}
807
-
808
-		if (!OC_Util::isSetLocaleWorking()) {
809
-			$errors[] = [
810
-				'error' => $l->t('Setting locale to %s failed',
811
-					['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
812
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
813
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
814
-			];
815
-		}
816
-
817
-		// Contains the dependencies that should be checked against
818
-		// classes = class_exists
819
-		// functions = function_exists
820
-		// defined = defined
821
-		// ini = ini_get
822
-		// If the dependency is not found the missing module name is shown to the EndUser
823
-		// When adding new checks always verify that they pass on Travis as well
824
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
825
-		$dependencies = [
826
-			'classes' => [
827
-				'ZipArchive' => 'zip',
828
-				'DOMDocument' => 'dom',
829
-				'XMLWriter' => 'XMLWriter',
830
-				'XMLReader' => 'XMLReader',
831
-			],
832
-			'functions' => [
833
-				'xml_parser_create' => 'libxml',
834
-				'mb_strcut' => 'mbstring',
835
-				'ctype_digit' => 'ctype',
836
-				'json_encode' => 'JSON',
837
-				'gd_info' => 'GD',
838
-				'gzencode' => 'zlib',
839
-				'iconv' => 'iconv',
840
-				'simplexml_load_string' => 'SimpleXML',
841
-				'hash' => 'HASH Message Digest Framework',
842
-				'curl_init' => 'cURL',
843
-				'openssl_verify' => 'OpenSSL',
844
-			],
845
-			'defined' => [
846
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
847
-			],
848
-			'ini' => [
849
-				'default_charset' => 'UTF-8',
850
-			],
851
-		];
852
-		$missingDependencies = [];
853
-		$invalidIniSettings = [];
854
-
855
-		$iniWrapper = \OC::$server->getIniWrapper();
856
-		foreach ($dependencies['classes'] as $class => $module) {
857
-			if (!class_exists($class)) {
858
-				$missingDependencies[] = $module;
859
-			}
860
-		}
861
-		foreach ($dependencies['functions'] as $function => $module) {
862
-			if (!function_exists($function)) {
863
-				$missingDependencies[] = $module;
864
-			}
865
-		}
866
-		foreach ($dependencies['defined'] as $defined => $module) {
867
-			if (!defined($defined)) {
868
-				$missingDependencies[] = $module;
869
-			}
870
-		}
871
-		foreach ($dependencies['ini'] as $setting => $expected) {
872
-			if (is_bool($expected)) {
873
-				if ($iniWrapper->getBool($setting) !== $expected) {
874
-					$invalidIniSettings[] = [$setting, $expected];
875
-				}
876
-			}
877
-			if (is_int($expected)) {
878
-				if ($iniWrapper->getNumeric($setting) !== $expected) {
879
-					$invalidIniSettings[] = [$setting, $expected];
880
-				}
881
-			}
882
-			if (is_string($expected)) {
883
-				if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
884
-					$invalidIniSettings[] = [$setting, $expected];
885
-				}
886
-			}
887
-		}
888
-
889
-		foreach ($missingDependencies as $missingDependency) {
890
-			$errors[] = [
891
-				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
892
-				'hint' => $l->t('Please ask your server administrator to install the module.'),
893
-			];
894
-			$webServerRestart = true;
895
-		}
896
-		foreach ($invalidIniSettings as $setting) {
897
-			if (is_bool($setting[1])) {
898
-				$setting[1] = $setting[1] ? 'on' : 'off';
899
-			}
900
-			$errors[] = [
901
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
902
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
903
-			];
904
-			$webServerRestart = true;
905
-		}
906
-
907
-		/**
908
-		 * The mbstring.func_overload check can only be performed if the mbstring
909
-		 * module is installed as it will return null if the checking setting is
910
-		 * not available and thus a check on the boolean value fails.
911
-		 *
912
-		 * TODO: Should probably be implemented in the above generic dependency
913
-		 *       check somehow in the long-term.
914
-		 */
915
-		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
916
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
917
-			$errors[] = [
918
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
919
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
920
-			];
921
-		}
922
-
923
-		if (function_exists('xml_parser_create') &&
924
-			LIBXML_LOADED_VERSION < 20700) {
925
-			$version = LIBXML_LOADED_VERSION;
926
-			$major = floor($version/10000);
927
-			$version -= ($major * 10000);
928
-			$minor = floor($version/100);
929
-			$version -= ($minor * 100);
930
-			$patch = $version;
931
-			$errors[] = [
932
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
933
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
934
-			];
935
-		}
936
-
937
-		if (!self::isAnnotationsWorking()) {
938
-			$errors[] = [
939
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
940
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
941
-			];
942
-		}
943
-
944
-		if (!\OC::$CLI && $webServerRestart) {
945
-			$errors[] = [
946
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
947
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
948
-			];
949
-		}
950
-
951
-		$errors = array_merge($errors, self::checkDatabaseVersion());
952
-
953
-		// Cache the result of this function
954
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
955
-
956
-		return $errors;
957
-	}
958
-
959
-	/**
960
-	 * Check the database version
961
-	 *
962
-	 * @return array errors array
963
-	 */
964
-	public static function checkDatabaseVersion() {
965
-		$l = \OC::$server->getL10N('lib');
966
-		$errors = [];
967
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
968
-		if ($dbType === 'pgsql') {
969
-			// check PostgreSQL version
970
-			try {
971
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
972
-				$data = $result->fetchRow();
973
-				if (isset($data['server_version'])) {
974
-					$version = $data['server_version'];
975
-					if (version_compare($version, '9.0.0', '<')) {
976
-						$errors[] = [
977
-							'error' => $l->t('PostgreSQL >= 9 required'),
978
-							'hint' => $l->t('Please upgrade your database version')
979
-						];
980
-					}
981
-				}
982
-			} catch (\Doctrine\DBAL\DBALException $e) {
983
-				$logger = \OC::$server->getLogger();
984
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
985
-				$logger->logException($e);
986
-			}
987
-		}
988
-		return $errors;
989
-	}
990
-
991
-	/**
992
-	 * Check for correct file permissions of data directory
993
-	 *
994
-	 * @param string $dataDirectory
995
-	 * @return array arrays with error messages and hints
996
-	 */
997
-	public static function checkDataDirectoryPermissions($dataDirectory) {
998
-		if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
999
-			return  [];
1000
-		}
1001
-
1002
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1003
-		if (substr($perms, -1) !== '0') {
1004
-			chmod($dataDirectory, 0770);
1005
-			clearstatcache();
1006
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1007
-			if ($perms[2] !== '0') {
1008
-				$l = \OC::$server->getL10N('lib');
1009
-				return [
1010
-					'error' => $l->t('Your data directory is readable by other users'),
1011
-					'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1012
-				];
1013
-			}
1014
-		}
1015
-		return [];
1016
-	}
1017
-
1018
-	/**
1019
-	 * Check that the data directory exists and is valid by
1020
-	 * checking the existence of the ".ocdata" file.
1021
-	 *
1022
-	 * @param string $dataDirectory data directory path
1023
-	 * @return array errors found
1024
-	 */
1025
-	public static function checkDataDirectoryValidity($dataDirectory) {
1026
-		$l = \OC::$server->getL10N('lib');
1027
-		$errors = [];
1028
-		if ($dataDirectory[0] !== '/') {
1029
-			$errors[] = [
1030
-				'error' => $l->t('Your data directory must be an absolute path'),
1031
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1032
-			];
1033
-		}
1034
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1035
-			$errors[] = [
1036
-				'error' => $l->t('Your data directory is invalid'),
1037
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1038
-					' in the root of the data directory.')
1039
-			];
1040
-		}
1041
-		return $errors;
1042
-	}
1043
-
1044
-	/**
1045
-	 * Check if the user is logged in, redirects to home if not. With
1046
-	 * redirect URL parameter to the request URI.
1047
-	 *
1048
-	 * @return void
1049
-	 */
1050
-	public static function checkLoggedIn() {
1051
-		// Check if we are a user
1052
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1053
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1054
-						'core.login.showLoginForm',
1055
-						[
1056
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1057
-						]
1058
-					)
1059
-			);
1060
-			exit();
1061
-		}
1062
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1063
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1064
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1065
-			exit();
1066
-		}
1067
-	}
1068
-
1069
-	/**
1070
-	 * Check if the user is a admin, redirects to home if not
1071
-	 *
1072
-	 * @return void
1073
-	 */
1074
-	public static function checkAdminUser() {
1075
-		OC_Util::checkLoggedIn();
1076
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1077
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1078
-			exit();
1079
-		}
1080
-	}
1081
-
1082
-	/**
1083
-	 * Returns the URL of the default page
1084
-	 * based on the system configuration and
1085
-	 * the apps visible for the current user
1086
-	 *
1087
-	 * @return string URL
1088
-	 * @suppress PhanDeprecatedFunction
1089
-	 */
1090
-	public static function getDefaultPageUrl() {
1091
-		$urlGenerator = \OC::$server->getURLGenerator();
1092
-		// Deny the redirect if the URL contains a @
1093
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1094
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1095
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1096
-		} else {
1097
-			$defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1098
-			if ($defaultPage) {
1099
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1100
-			} else {
1101
-				$appId = 'files';
1102
-				$config = \OC::$server->getConfig();
1103
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1104
-				// find the first app that is enabled for the current user
1105
-				foreach ($defaultApps as $defaultApp) {
1106
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1107
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1108
-						$appId = $defaultApp;
1109
-						break;
1110
-					}
1111
-				}
1112
-
1113
-				if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1114
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1115
-				} else {
1116
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1117
-				}
1118
-			}
1119
-		}
1120
-		return $location;
1121
-	}
1122
-
1123
-	/**
1124
-	 * Redirect to the user default page
1125
-	 *
1126
-	 * @return void
1127
-	 */
1128
-	public static function redirectToDefaultPage() {
1129
-		$location = self::getDefaultPageUrl();
1130
-		header('Location: ' . $location);
1131
-		exit();
1132
-	}
1133
-
1134
-	/**
1135
-	 * get an id unique for this instance
1136
-	 *
1137
-	 * @return string
1138
-	 */
1139
-	public static function getInstanceId() {
1140
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1141
-		if (is_null($id)) {
1142
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1143
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1144
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1145
-		}
1146
-		return $id;
1147
-	}
1148
-
1149
-	/**
1150
-	 * Public function to sanitize HTML
1151
-	 *
1152
-	 * This function is used to sanitize HTML and should be applied on any
1153
-	 * string or array of strings before displaying it on a web page.
1154
-	 *
1155
-	 * @param string|array $value
1156
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1157
-	 */
1158
-	public static function sanitizeHTML($value) {
1159
-		if (is_array($value)) {
1160
-			$value = array_map(function ($value) {
1161
-				return self::sanitizeHTML($value);
1162
-			}, $value);
1163
-		} else {
1164
-			// Specify encoding for PHP<5.4
1165
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1166
-		}
1167
-		return $value;
1168
-	}
1169
-
1170
-	/**
1171
-	 * Public function to encode url parameters
1172
-	 *
1173
-	 * This function is used to encode path to file before output.
1174
-	 * Encoding is done according to RFC 3986 with one exception:
1175
-	 * Character '/' is preserved as is.
1176
-	 *
1177
-	 * @param string $component part of URI to encode
1178
-	 * @return string
1179
-	 */
1180
-	public static function encodePath($component) {
1181
-		$encoded = rawurlencode($component);
1182
-		$encoded = str_replace('%2F', '/', $encoded);
1183
-		return $encoded;
1184
-	}
1185
-
1186
-
1187
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1188
-		// php dev server does not support htaccess
1189
-		if (php_sapi_name() === 'cli-server') {
1190
-			return false;
1191
-		}
1192
-
1193
-		// testdata
1194
-		$fileName = '/htaccesstest.txt';
1195
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1196
-
1197
-		// creating a test file
1198
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1199
-
1200
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1201
-			return false;
1202
-		}
1203
-
1204
-		$fp = @fopen($testFile, 'w');
1205
-		if (!$fp) {
1206
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1207
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1208
-		}
1209
-		fwrite($fp, $testContent);
1210
-		fclose($fp);
1211
-
1212
-		return $testContent;
1213
-	}
1214
-
1215
-	/**
1216
-	 * Check if the .htaccess file is working
1217
-	 * @param \OCP\IConfig $config
1218
-	 * @return bool
1219
-	 * @throws Exception
1220
-	 * @throws \OC\HintException If the test file can't get written.
1221
-	 */
1222
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1223
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1224
-			return true;
1225
-		}
1226
-
1227
-		$testContent = $this->createHtaccessTestFile($config);
1228
-		if ($testContent === false) {
1229
-			return false;
1230
-		}
1231
-
1232
-		$fileName = '/htaccesstest.txt';
1233
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1234
-
1235
-		// accessing the file via http
1236
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1237
-		try {
1238
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1239
-		} catch (\Exception $e) {
1240
-			$content = false;
1241
-		}
1242
-
1243
-		if (strpos($url, 'https:') === 0) {
1244
-			$url = 'http:' . substr($url, 6);
1245
-		} else {
1246
-			$url = 'https:' . substr($url, 5);
1247
-		}
1248
-
1249
-		try {
1250
-			$fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1251
-		} catch (\Exception $e) {
1252
-			$fallbackContent = false;
1253
-		}
1254
-
1255
-		// cleanup
1256
-		@unlink($testFile);
1257
-
1258
-		/*
269
+            if ($mount->getOption('readonly', false)) {
270
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
271
+                    'storage' => $storage,
272
+                    'mask' => \OCP\Constants::PERMISSION_ALL & ~(
273
+                        \OCP\Constants::PERMISSION_UPDATE |
274
+                        \OCP\Constants::PERMISSION_CREATE |
275
+                        \OCP\Constants::PERMISSION_DELETE
276
+                    ),
277
+                ]);
278
+            }
279
+            return $storage;
280
+        });
281
+
282
+        OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
283
+
284
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
285
+
286
+        //check if we are using an object storage
287
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
288
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
289
+
290
+        // use the same order as in ObjectHomeMountProvider
291
+        if (isset($objectStoreMultibucket)) {
292
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
293
+        } elseif (isset($objectStore)) {
294
+            self::initObjectStoreRootFS($objectStore);
295
+        } else {
296
+            self::initLocalStorageRootFS();
297
+        }
298
+
299
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
300
+            \OC::$server->getEventLogger()->end('setup_fs');
301
+            return false;
302
+        }
303
+
304
+        //if we aren't logged in, there is no use to set up the filesystem
305
+        if ($user != "") {
306
+            $userDir = '/' . $user . '/files';
307
+
308
+            //jail the user into his "home" directory
309
+            \OC\Files\Filesystem::init($user, $userDir);
310
+
311
+            OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
312
+        }
313
+        \OC::$server->getEventLogger()->end('setup_fs');
314
+        return true;
315
+    }
316
+
317
+    /**
318
+     * check if a password is required for each public link
319
+     *
320
+     * @return boolean
321
+     * @suppress PhanDeprecatedFunction
322
+     */
323
+    public static function isPublicLinkPasswordRequired() {
324
+        $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
325
+        return $enforcePassword === 'yes';
326
+    }
327
+
328
+    /**
329
+     * check if sharing is disabled for the current user
330
+     * @param IConfig $config
331
+     * @param IGroupManager $groupManager
332
+     * @param IUser|null $user
333
+     * @return bool
334
+     */
335
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
336
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
337
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
338
+            $excludedGroups = json_decode($groupsList);
339
+            if (is_null($excludedGroups)) {
340
+                $excludedGroups = explode(',', $groupsList);
341
+                $newValue = json_encode($excludedGroups);
342
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
343
+            }
344
+            $usersGroups = $groupManager->getUserGroupIds($user);
345
+            if (!empty($usersGroups)) {
346
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
347
+                // if the user is only in groups which are disabled for sharing then
348
+                // sharing is also disabled for the user
349
+                if (empty($remainingGroups)) {
350
+                    return true;
351
+                }
352
+            }
353
+        }
354
+        return false;
355
+    }
356
+
357
+    /**
358
+     * check if share API enforces a default expire date
359
+     *
360
+     * @return boolean
361
+     * @suppress PhanDeprecatedFunction
362
+     */
363
+    public static function isDefaultExpireDateEnforced() {
364
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
365
+        $enforceDefaultExpireDate = false;
366
+        if ($isDefaultExpireDateEnabled === 'yes') {
367
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
368
+            $enforceDefaultExpireDate = $value === 'yes';
369
+        }
370
+
371
+        return $enforceDefaultExpireDate;
372
+    }
373
+
374
+    /**
375
+     * Get the quota of a user
376
+     *
377
+     * @param IUser|null $user
378
+     * @return float Quota bytes
379
+     */
380
+    public static function getUserQuota(?IUser $user) {
381
+        if (is_null($user)) {
382
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
383
+        }
384
+        $userQuota = $user->getQuota();
385
+        if ($userQuota === 'none') {
386
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
387
+        }
388
+        return OC_Helper::computerFileSize($userQuota);
389
+    }
390
+
391
+    /**
392
+     * copies the skeleton to the users /files
393
+     *
394
+     * @param string $userId
395
+     * @param \OCP\Files\Folder $userDirectory
396
+     * @throws \OCP\Files\NotFoundException
397
+     * @throws \OCP\Files\NotPermittedException
398
+     * @suppress PhanDeprecatedFunction
399
+     */
400
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
401
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
402
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
403
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
404
+
405
+        if (!file_exists($skeletonDirectory)) {
406
+            $dialectStart = strpos($userLang, '_');
407
+            if ($dialectStart !== false) {
408
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
409
+            }
410
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
411
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
412
+            }
413
+            if (!file_exists($skeletonDirectory)) {
414
+                $skeletonDirectory = '';
415
+            }
416
+        }
417
+
418
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
419
+
420
+        if ($instanceId === null) {
421
+            throw new \RuntimeException('no instance id!');
422
+        }
423
+        $appdata = 'appdata_' . $instanceId;
424
+        if ($userId === $appdata) {
425
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
426
+        }
427
+
428
+        if (!empty($skeletonDirectory)) {
429
+            \OCP\Util::writeLog(
430
+                'files_skeleton',
431
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
432
+                ILogger::DEBUG
433
+            );
434
+            self::copyr($skeletonDirectory, $userDirectory);
435
+            // update the file cache
436
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
437
+        }
438
+    }
439
+
440
+    /**
441
+     * copies a directory recursively by using streams
442
+     *
443
+     * @param string $source
444
+     * @param \OCP\Files\Folder $target
445
+     * @return void
446
+     */
447
+    public static function copyr($source, \OCP\Files\Folder $target) {
448
+        $logger = \OC::$server->getLogger();
449
+
450
+        // Verify if folder exists
451
+        $dir = opendir($source);
452
+        if ($dir === false) {
453
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
454
+            return;
455
+        }
456
+
457
+        // Copy the files
458
+        while (false !== ($file = readdir($dir))) {
459
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
460
+                if (is_dir($source . '/' . $file)) {
461
+                    $child = $target->newFolder($file);
462
+                    self::copyr($source . '/' . $file, $child);
463
+                } else {
464
+                    $child = $target->newFile($file);
465
+                    $sourceStream = fopen($source . '/' . $file, 'r');
466
+                    if ($sourceStream === false) {
467
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
468
+                        closedir($dir);
469
+                        return;
470
+                    }
471
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
472
+                }
473
+            }
474
+        }
475
+        closedir($dir);
476
+    }
477
+
478
+    /**
479
+     * @return void
480
+     * @suppress PhanUndeclaredMethod
481
+     */
482
+    public static function tearDownFS() {
483
+        \OC\Files\Filesystem::tearDown();
484
+        \OC::$server->getRootFolder()->clearCache();
485
+        self::$fsSetup = false;
486
+        self::$rootMounted = false;
487
+    }
488
+
489
+    /**
490
+     * get the current installed version of ownCloud
491
+     *
492
+     * @return array
493
+     */
494
+    public static function getVersion() {
495
+        OC_Util::loadVersion();
496
+        return self::$versionCache['OC_Version'];
497
+    }
498
+
499
+    /**
500
+     * get the current installed version string of ownCloud
501
+     *
502
+     * @return string
503
+     */
504
+    public static function getVersionString() {
505
+        OC_Util::loadVersion();
506
+        return self::$versionCache['OC_VersionString'];
507
+    }
508
+
509
+    /**
510
+     * @deprecated the value is of no use anymore
511
+     * @return string
512
+     */
513
+    public static function getEditionString() {
514
+        return '';
515
+    }
516
+
517
+    /**
518
+     * @description get the update channel of the current installed of ownCloud.
519
+     * @return string
520
+     */
521
+    public static function getChannel() {
522
+        OC_Util::loadVersion();
523
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
524
+    }
525
+
526
+    /**
527
+     * @description get the build number of the current installed of ownCloud.
528
+     * @return string
529
+     */
530
+    public static function getBuild() {
531
+        OC_Util::loadVersion();
532
+        return self::$versionCache['OC_Build'];
533
+    }
534
+
535
+    /**
536
+     * @description load the version.php into the session as cache
537
+     * @suppress PhanUndeclaredVariable
538
+     */
539
+    private static function loadVersion() {
540
+        if (self::$versionCache !== null) {
541
+            return;
542
+        }
543
+
544
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
545
+        require OC::$SERVERROOT . '/version.php';
546
+        /** @var $timestamp int */
547
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
548
+        /** @var $OC_Version string */
549
+        self::$versionCache['OC_Version'] = $OC_Version;
550
+        /** @var $OC_VersionString string */
551
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
552
+        /** @var $OC_Build string */
553
+        self::$versionCache['OC_Build'] = $OC_Build;
554
+
555
+        /** @var $OC_Channel string */
556
+        self::$versionCache['OC_Channel'] = $OC_Channel;
557
+    }
558
+
559
+    /**
560
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
561
+     *
562
+     * @param string $application application to get the files from
563
+     * @param string $directory directory within this application (css, js, vendor, etc)
564
+     * @param string $file the file inside of the above folder
565
+     * @return string the path
566
+     */
567
+    private static function generatePath($application, $directory, $file) {
568
+        if (is_null($file)) {
569
+            $file = $application;
570
+            $application = "";
571
+        }
572
+        if (!empty($application)) {
573
+            return "$application/$directory/$file";
574
+        } else {
575
+            return "$directory/$file";
576
+        }
577
+    }
578
+
579
+    /**
580
+     * add a javascript file
581
+     *
582
+     * @param string $application application id
583
+     * @param string|null $file filename
584
+     * @param bool $prepend prepend the Script to the beginning of the list
585
+     * @return void
586
+     */
587
+    public static function addScript($application, $file = null, $prepend = false) {
588
+        $path = OC_Util::generatePath($application, 'js', $file);
589
+
590
+        // core js files need separate handling
591
+        if ($application !== 'core' && $file !== null) {
592
+            self::addTranslations($application);
593
+        }
594
+        self::addExternalResource($application, $prepend, $path, "script");
595
+    }
596
+
597
+    /**
598
+     * add a javascript file from the vendor sub folder
599
+     *
600
+     * @param string $application application id
601
+     * @param string|null $file filename
602
+     * @param bool $prepend prepend the Script to the beginning of the list
603
+     * @return void
604
+     */
605
+    public static function addVendorScript($application, $file = null, $prepend = false) {
606
+        $path = OC_Util::generatePath($application, 'vendor', $file);
607
+        self::addExternalResource($application, $prepend, $path, "script");
608
+    }
609
+
610
+    /**
611
+     * add a translation JS file
612
+     *
613
+     * @param string $application application id
614
+     * @param string|null $languageCode language code, defaults to the current language
615
+     * @param bool|null $prepend prepend the Script to the beginning of the list
616
+     */
617
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
618
+        if (is_null($languageCode)) {
619
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
620
+        }
621
+        if (!empty($application)) {
622
+            $path = "$application/l10n/$languageCode";
623
+        } else {
624
+            $path = "l10n/$languageCode";
625
+        }
626
+        self::addExternalResource($application, $prepend, $path, "script");
627
+    }
628
+
629
+    /**
630
+     * add a css file
631
+     *
632
+     * @param string $application application id
633
+     * @param string|null $file filename
634
+     * @param bool $prepend prepend the Style to the beginning of the list
635
+     * @return void
636
+     */
637
+    public static function addStyle($application, $file = null, $prepend = false) {
638
+        $path = OC_Util::generatePath($application, 'css', $file);
639
+        self::addExternalResource($application, $prepend, $path, "style");
640
+    }
641
+
642
+    /**
643
+     * add a css file from the vendor sub folder
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 addVendorStyle($application, $file = null, $prepend = false) {
651
+        $path = OC_Util::generatePath($application, 'vendor', $file);
652
+        self::addExternalResource($application, $prepend, $path, "style");
653
+    }
654
+
655
+    /**
656
+     * add an external resource css/js file
657
+     *
658
+     * @param string $application application id
659
+     * @param bool $prepend prepend the file to the beginning of the list
660
+     * @param string $path
661
+     * @param string $type (script or style)
662
+     * @return void
663
+     */
664
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
665
+        if ($type === "style") {
666
+            if (!in_array($path, self::$styles)) {
667
+                if ($prepend === true) {
668
+                    array_unshift(self::$styles, $path);
669
+                } else {
670
+                    self::$styles[] = $path;
671
+                }
672
+            }
673
+        } elseif ($type === "script") {
674
+            if (!in_array($path, self::$scripts)) {
675
+                if ($prepend === true) {
676
+                    array_unshift(self::$scripts, $path);
677
+                } else {
678
+                    self::$scripts [] = $path;
679
+                }
680
+            }
681
+        }
682
+    }
683
+
684
+    /**
685
+     * Add a custom element to the header
686
+     * If $text is null then the element will be written as empty element.
687
+     * So use "" to get a closing tag.
688
+     * @param string $tag tag name of the element
689
+     * @param array $attributes array of attributes for the element
690
+     * @param string $text the text content for the element
691
+     * @param bool $prepend prepend the header to the beginning of the list
692
+     */
693
+    public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
694
+        $header = [
695
+            'tag' => $tag,
696
+            'attributes' => $attributes,
697
+            'text' => $text
698
+        ];
699
+        if ($prepend === true) {
700
+            array_unshift(self::$headers, $header);
701
+        } else {
702
+            self::$headers[] = $header;
703
+        }
704
+    }
705
+
706
+    /**
707
+     * check if the current server configuration is suitable for ownCloud
708
+     *
709
+     * @param \OC\SystemConfig $config
710
+     * @return array arrays with error messages and hints
711
+     */
712
+    public static function checkServer(\OC\SystemConfig $config) {
713
+        $l = \OC::$server->getL10N('lib');
714
+        $errors = [];
715
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
716
+
717
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
718
+            // this check needs to be done every time
719
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
720
+        }
721
+
722
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
723
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
724
+            return $errors;
725
+        }
726
+
727
+        $webServerRestart = false;
728
+        $setup = new \OC\Setup(
729
+            $config,
730
+            \OC::$server->getIniWrapper(),
731
+            \OC::$server->getL10N('lib'),
732
+            \OC::$server->query(\OCP\Defaults::class),
733
+            \OC::$server->getLogger(),
734
+            \OC::$server->getSecureRandom(),
735
+            \OC::$server->query(\OC\Installer::class)
736
+        );
737
+
738
+        $urlGenerator = \OC::$server->getURLGenerator();
739
+
740
+        $availableDatabases = $setup->getSupportedDatabases();
741
+        if (empty($availableDatabases)) {
742
+            $errors[] = [
743
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
744
+                'hint' => '' //TODO: sane hint
745
+            ];
746
+            $webServerRestart = true;
747
+        }
748
+
749
+        // Check if config folder is writable.
750
+        if (!OC_Helper::isReadOnlyConfigEnabled()) {
751
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
752
+                $errors[] = [
753
+                    'error' => $l->t('Cannot write into "config" directory'),
754
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
755
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
756
+                        . $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',
757
+                        [ $urlGenerator->linkToDocs('admin-config') ])
758
+                ];
759
+            }
760
+        }
761
+
762
+        // Check if there is a writable install folder.
763
+        if ($config->getValue('appstoreenabled', true)) {
764
+            if (OC_App::getInstallPath() === null
765
+                || !is_writable(OC_App::getInstallPath())
766
+                || !is_readable(OC_App::getInstallPath())
767
+            ) {
768
+                $errors[] = [
769
+                    'error' => $l->t('Cannot write into "apps" directory'),
770
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
771
+                        . ' or disabling the appstore in the config file.')
772
+                ];
773
+            }
774
+        }
775
+        // Create root dir.
776
+        if ($config->getValue('installed', false)) {
777
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
778
+                $success = @mkdir($CONFIG_DATADIRECTORY);
779
+                if ($success) {
780
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
781
+                } else {
782
+                    $errors[] = [
783
+                        'error' => $l->t('Cannot create "data" directory'),
784
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
785
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
786
+                    ];
787
+                }
788
+            } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
789
+                // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
790
+                $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
791
+                $handle = fopen($testFile, 'w');
792
+                if (!$handle || fwrite($handle, 'Test write operation') === false) {
793
+                    $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
794
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')]);
795
+                    $errors[] = [
796
+                        'error' => 'Your data directory is not writable',
797
+                        'hint' => $permissionsHint
798
+                    ];
799
+                } else {
800
+                    fclose($handle);
801
+                    unlink($testFile);
802
+                }
803
+            } else {
804
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
805
+            }
806
+        }
807
+
808
+        if (!OC_Util::isSetLocaleWorking()) {
809
+            $errors[] = [
810
+                'error' => $l->t('Setting locale to %s failed',
811
+                    ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
812
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
813
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
814
+            ];
815
+        }
816
+
817
+        // Contains the dependencies that should be checked against
818
+        // classes = class_exists
819
+        // functions = function_exists
820
+        // defined = defined
821
+        // ini = ini_get
822
+        // If the dependency is not found the missing module name is shown to the EndUser
823
+        // When adding new checks always verify that they pass on Travis as well
824
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
825
+        $dependencies = [
826
+            'classes' => [
827
+                'ZipArchive' => 'zip',
828
+                'DOMDocument' => 'dom',
829
+                'XMLWriter' => 'XMLWriter',
830
+                'XMLReader' => 'XMLReader',
831
+            ],
832
+            'functions' => [
833
+                'xml_parser_create' => 'libxml',
834
+                'mb_strcut' => 'mbstring',
835
+                'ctype_digit' => 'ctype',
836
+                'json_encode' => 'JSON',
837
+                'gd_info' => 'GD',
838
+                'gzencode' => 'zlib',
839
+                'iconv' => 'iconv',
840
+                'simplexml_load_string' => 'SimpleXML',
841
+                'hash' => 'HASH Message Digest Framework',
842
+                'curl_init' => 'cURL',
843
+                'openssl_verify' => 'OpenSSL',
844
+            ],
845
+            'defined' => [
846
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
847
+            ],
848
+            'ini' => [
849
+                'default_charset' => 'UTF-8',
850
+            ],
851
+        ];
852
+        $missingDependencies = [];
853
+        $invalidIniSettings = [];
854
+
855
+        $iniWrapper = \OC::$server->getIniWrapper();
856
+        foreach ($dependencies['classes'] as $class => $module) {
857
+            if (!class_exists($class)) {
858
+                $missingDependencies[] = $module;
859
+            }
860
+        }
861
+        foreach ($dependencies['functions'] as $function => $module) {
862
+            if (!function_exists($function)) {
863
+                $missingDependencies[] = $module;
864
+            }
865
+        }
866
+        foreach ($dependencies['defined'] as $defined => $module) {
867
+            if (!defined($defined)) {
868
+                $missingDependencies[] = $module;
869
+            }
870
+        }
871
+        foreach ($dependencies['ini'] as $setting => $expected) {
872
+            if (is_bool($expected)) {
873
+                if ($iniWrapper->getBool($setting) !== $expected) {
874
+                    $invalidIniSettings[] = [$setting, $expected];
875
+                }
876
+            }
877
+            if (is_int($expected)) {
878
+                if ($iniWrapper->getNumeric($setting) !== $expected) {
879
+                    $invalidIniSettings[] = [$setting, $expected];
880
+                }
881
+            }
882
+            if (is_string($expected)) {
883
+                if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
884
+                    $invalidIniSettings[] = [$setting, $expected];
885
+                }
886
+            }
887
+        }
888
+
889
+        foreach ($missingDependencies as $missingDependency) {
890
+            $errors[] = [
891
+                'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
892
+                'hint' => $l->t('Please ask your server administrator to install the module.'),
893
+            ];
894
+            $webServerRestart = true;
895
+        }
896
+        foreach ($invalidIniSettings as $setting) {
897
+            if (is_bool($setting[1])) {
898
+                $setting[1] = $setting[1] ? 'on' : 'off';
899
+            }
900
+            $errors[] = [
901
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
902
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
903
+            ];
904
+            $webServerRestart = true;
905
+        }
906
+
907
+        /**
908
+         * The mbstring.func_overload check can only be performed if the mbstring
909
+         * module is installed as it will return null if the checking setting is
910
+         * not available and thus a check on the boolean value fails.
911
+         *
912
+         * TODO: Should probably be implemented in the above generic dependency
913
+         *       check somehow in the long-term.
914
+         */
915
+        if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
916
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
917
+            $errors[] = [
918
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
919
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
920
+            ];
921
+        }
922
+
923
+        if (function_exists('xml_parser_create') &&
924
+            LIBXML_LOADED_VERSION < 20700) {
925
+            $version = LIBXML_LOADED_VERSION;
926
+            $major = floor($version/10000);
927
+            $version -= ($major * 10000);
928
+            $minor = floor($version/100);
929
+            $version -= ($minor * 100);
930
+            $patch = $version;
931
+            $errors[] = [
932
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
933
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
934
+            ];
935
+        }
936
+
937
+        if (!self::isAnnotationsWorking()) {
938
+            $errors[] = [
939
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
940
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
941
+            ];
942
+        }
943
+
944
+        if (!\OC::$CLI && $webServerRestart) {
945
+            $errors[] = [
946
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
947
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
948
+            ];
949
+        }
950
+
951
+        $errors = array_merge($errors, self::checkDatabaseVersion());
952
+
953
+        // Cache the result of this function
954
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
955
+
956
+        return $errors;
957
+    }
958
+
959
+    /**
960
+     * Check the database version
961
+     *
962
+     * @return array errors array
963
+     */
964
+    public static function checkDatabaseVersion() {
965
+        $l = \OC::$server->getL10N('lib');
966
+        $errors = [];
967
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
968
+        if ($dbType === 'pgsql') {
969
+            // check PostgreSQL version
970
+            try {
971
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
972
+                $data = $result->fetchRow();
973
+                if (isset($data['server_version'])) {
974
+                    $version = $data['server_version'];
975
+                    if (version_compare($version, '9.0.0', '<')) {
976
+                        $errors[] = [
977
+                            'error' => $l->t('PostgreSQL >= 9 required'),
978
+                            'hint' => $l->t('Please upgrade your database version')
979
+                        ];
980
+                    }
981
+                }
982
+            } catch (\Doctrine\DBAL\DBALException $e) {
983
+                $logger = \OC::$server->getLogger();
984
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
985
+                $logger->logException($e);
986
+            }
987
+        }
988
+        return $errors;
989
+    }
990
+
991
+    /**
992
+     * Check for correct file permissions of data directory
993
+     *
994
+     * @param string $dataDirectory
995
+     * @return array arrays with error messages and hints
996
+     */
997
+    public static function checkDataDirectoryPermissions($dataDirectory) {
998
+        if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
999
+            return  [];
1000
+        }
1001
+
1002
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1003
+        if (substr($perms, -1) !== '0') {
1004
+            chmod($dataDirectory, 0770);
1005
+            clearstatcache();
1006
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1007
+            if ($perms[2] !== '0') {
1008
+                $l = \OC::$server->getL10N('lib');
1009
+                return [
1010
+                    'error' => $l->t('Your data directory is readable by other users'),
1011
+                    'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1012
+                ];
1013
+            }
1014
+        }
1015
+        return [];
1016
+    }
1017
+
1018
+    /**
1019
+     * Check that the data directory exists and is valid by
1020
+     * checking the existence of the ".ocdata" file.
1021
+     *
1022
+     * @param string $dataDirectory data directory path
1023
+     * @return array errors found
1024
+     */
1025
+    public static function checkDataDirectoryValidity($dataDirectory) {
1026
+        $l = \OC::$server->getL10N('lib');
1027
+        $errors = [];
1028
+        if ($dataDirectory[0] !== '/') {
1029
+            $errors[] = [
1030
+                'error' => $l->t('Your data directory must be an absolute path'),
1031
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1032
+            ];
1033
+        }
1034
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1035
+            $errors[] = [
1036
+                'error' => $l->t('Your data directory is invalid'),
1037
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1038
+                    ' in the root of the data directory.')
1039
+            ];
1040
+        }
1041
+        return $errors;
1042
+    }
1043
+
1044
+    /**
1045
+     * Check if the user is logged in, redirects to home if not. With
1046
+     * redirect URL parameter to the request URI.
1047
+     *
1048
+     * @return void
1049
+     */
1050
+    public static function checkLoggedIn() {
1051
+        // Check if we are a user
1052
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1053
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1054
+                        'core.login.showLoginForm',
1055
+                        [
1056
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1057
+                        ]
1058
+                    )
1059
+            );
1060
+            exit();
1061
+        }
1062
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1063
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1064
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1065
+            exit();
1066
+        }
1067
+    }
1068
+
1069
+    /**
1070
+     * Check if the user is a admin, redirects to home if not
1071
+     *
1072
+     * @return void
1073
+     */
1074
+    public static function checkAdminUser() {
1075
+        OC_Util::checkLoggedIn();
1076
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1077
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1078
+            exit();
1079
+        }
1080
+    }
1081
+
1082
+    /**
1083
+     * Returns the URL of the default page
1084
+     * based on the system configuration and
1085
+     * the apps visible for the current user
1086
+     *
1087
+     * @return string URL
1088
+     * @suppress PhanDeprecatedFunction
1089
+     */
1090
+    public static function getDefaultPageUrl() {
1091
+        $urlGenerator = \OC::$server->getURLGenerator();
1092
+        // Deny the redirect if the URL contains a @
1093
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1094
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1095
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1096
+        } else {
1097
+            $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1098
+            if ($defaultPage) {
1099
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1100
+            } else {
1101
+                $appId = 'files';
1102
+                $config = \OC::$server->getConfig();
1103
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1104
+                // find the first app that is enabled for the current user
1105
+                foreach ($defaultApps as $defaultApp) {
1106
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1107
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1108
+                        $appId = $defaultApp;
1109
+                        break;
1110
+                    }
1111
+                }
1112
+
1113
+                if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1114
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1115
+                } else {
1116
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1117
+                }
1118
+            }
1119
+        }
1120
+        return $location;
1121
+    }
1122
+
1123
+    /**
1124
+     * Redirect to the user default page
1125
+     *
1126
+     * @return void
1127
+     */
1128
+    public static function redirectToDefaultPage() {
1129
+        $location = self::getDefaultPageUrl();
1130
+        header('Location: ' . $location);
1131
+        exit();
1132
+    }
1133
+
1134
+    /**
1135
+     * get an id unique for this instance
1136
+     *
1137
+     * @return string
1138
+     */
1139
+    public static function getInstanceId() {
1140
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1141
+        if (is_null($id)) {
1142
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1143
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1144
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1145
+        }
1146
+        return $id;
1147
+    }
1148
+
1149
+    /**
1150
+     * Public function to sanitize HTML
1151
+     *
1152
+     * This function is used to sanitize HTML and should be applied on any
1153
+     * string or array of strings before displaying it on a web page.
1154
+     *
1155
+     * @param string|array $value
1156
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1157
+     */
1158
+    public static function sanitizeHTML($value) {
1159
+        if (is_array($value)) {
1160
+            $value = array_map(function ($value) {
1161
+                return self::sanitizeHTML($value);
1162
+            }, $value);
1163
+        } else {
1164
+            // Specify encoding for PHP<5.4
1165
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1166
+        }
1167
+        return $value;
1168
+    }
1169
+
1170
+    /**
1171
+     * Public function to encode url parameters
1172
+     *
1173
+     * This function is used to encode path to file before output.
1174
+     * Encoding is done according to RFC 3986 with one exception:
1175
+     * Character '/' is preserved as is.
1176
+     *
1177
+     * @param string $component part of URI to encode
1178
+     * @return string
1179
+     */
1180
+    public static function encodePath($component) {
1181
+        $encoded = rawurlencode($component);
1182
+        $encoded = str_replace('%2F', '/', $encoded);
1183
+        return $encoded;
1184
+    }
1185
+
1186
+
1187
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1188
+        // php dev server does not support htaccess
1189
+        if (php_sapi_name() === 'cli-server') {
1190
+            return false;
1191
+        }
1192
+
1193
+        // testdata
1194
+        $fileName = '/htaccesstest.txt';
1195
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1196
+
1197
+        // creating a test file
1198
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1199
+
1200
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1201
+            return false;
1202
+        }
1203
+
1204
+        $fp = @fopen($testFile, 'w');
1205
+        if (!$fp) {
1206
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1207
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1208
+        }
1209
+        fwrite($fp, $testContent);
1210
+        fclose($fp);
1211
+
1212
+        return $testContent;
1213
+    }
1214
+
1215
+    /**
1216
+     * Check if the .htaccess file is working
1217
+     * @param \OCP\IConfig $config
1218
+     * @return bool
1219
+     * @throws Exception
1220
+     * @throws \OC\HintException If the test file can't get written.
1221
+     */
1222
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1223
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1224
+            return true;
1225
+        }
1226
+
1227
+        $testContent = $this->createHtaccessTestFile($config);
1228
+        if ($testContent === false) {
1229
+            return false;
1230
+        }
1231
+
1232
+        $fileName = '/htaccesstest.txt';
1233
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1234
+
1235
+        // accessing the file via http
1236
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1237
+        try {
1238
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1239
+        } catch (\Exception $e) {
1240
+            $content = false;
1241
+        }
1242
+
1243
+        if (strpos($url, 'https:') === 0) {
1244
+            $url = 'http:' . substr($url, 6);
1245
+        } else {
1246
+            $url = 'https:' . substr($url, 5);
1247
+        }
1248
+
1249
+        try {
1250
+            $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1251
+        } catch (\Exception $e) {
1252
+            $fallbackContent = false;
1253
+        }
1254
+
1255
+        // cleanup
1256
+        @unlink($testFile);
1257
+
1258
+        /*
1259 1259
 		 * If the content is not equal to test content our .htaccess
1260 1260
 		 * is working as required
1261 1261
 		 */
1262
-		return $content !== $testContent && $fallbackContent !== $testContent;
1263
-	}
1264
-
1265
-	/**
1266
-	 * Check if the setlocal call does not work. This can happen if the right
1267
-	 * local packages are not available on the server.
1268
-	 *
1269
-	 * @return bool
1270
-	 */
1271
-	public static function isSetLocaleWorking() {
1272
-		\Patchwork\Utf8\Bootup::initLocale();
1273
-		if ('' === basename('§')) {
1274
-			return false;
1275
-		}
1276
-		return true;
1277
-	}
1278
-
1279
-	/**
1280
-	 * Check if it's possible to get the inline annotations
1281
-	 *
1282
-	 * @return bool
1283
-	 */
1284
-	public static function isAnnotationsWorking() {
1285
-		$reflection = new \ReflectionMethod(__METHOD__);
1286
-		$docs = $reflection->getDocComment();
1287
-
1288
-		return (is_string($docs) && strlen($docs) > 50);
1289
-	}
1290
-
1291
-	/**
1292
-	 * Check if the PHP module fileinfo is loaded.
1293
-	 *
1294
-	 * @return bool
1295
-	 */
1296
-	public static function fileInfoLoaded() {
1297
-		return function_exists('finfo_open');
1298
-	}
1299
-
1300
-	/**
1301
-	 * clear all levels of output buffering
1302
-	 *
1303
-	 * @return void
1304
-	 */
1305
-	public static function obEnd() {
1306
-		while (ob_get_level()) {
1307
-			ob_end_clean();
1308
-		}
1309
-	}
1310
-
1311
-	/**
1312
-	 * Checks whether the server is running on Mac OS X
1313
-	 *
1314
-	 * @return bool true if running on Mac OS X, false otherwise
1315
-	 */
1316
-	public static function runningOnMac() {
1317
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1318
-	}
1319
-
1320
-	/**
1321
-	 * Handles the case that there may not be a theme, then check if a "default"
1322
-	 * theme exists and take that one
1323
-	 *
1324
-	 * @return string the theme
1325
-	 */
1326
-	public static function getTheme() {
1327
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1328
-
1329
-		if ($theme === '') {
1330
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1331
-				$theme = 'default';
1332
-			}
1333
-		}
1334
-
1335
-		return $theme;
1336
-	}
1337
-
1338
-	/**
1339
-	 * Normalize a unicode string
1340
-	 *
1341
-	 * @param string $value a not normalized string
1342
-	 * @return bool|string
1343
-	 */
1344
-	public static function normalizeUnicode($value) {
1345
-		if (Normalizer::isNormalized($value)) {
1346
-			return $value;
1347
-		}
1348
-
1349
-		$normalizedValue = Normalizer::normalize($value);
1350
-		if ($normalizedValue === null || $normalizedValue === false) {
1351
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1352
-			return $value;
1353
-		}
1354
-
1355
-		return $normalizedValue;
1356
-	}
1357
-
1358
-	/**
1359
-	 * A human readable string is generated based on version and build number
1360
-	 *
1361
-	 * @return string
1362
-	 */
1363
-	public static function getHumanVersion() {
1364
-		$version = OC_Util::getVersionString();
1365
-		$build = OC_Util::getBuild();
1366
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1367
-			$version .= ' Build:' . $build;
1368
-		}
1369
-		return $version;
1370
-	}
1371
-
1372
-	/**
1373
-	 * Returns whether the given file name is valid
1374
-	 *
1375
-	 * @param string $file file name to check
1376
-	 * @return bool true if the file name is valid, false otherwise
1377
-	 * @deprecated use \OC\Files\View::verifyPath()
1378
-	 */
1379
-	public static function isValidFileName($file) {
1380
-		$trimmed = trim($file);
1381
-		if ($trimmed === '') {
1382
-			return false;
1383
-		}
1384
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1385
-			return false;
1386
-		}
1387
-
1388
-		// detect part files
1389
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1390
-			return false;
1391
-		}
1392
-
1393
-		foreach (str_split($trimmed) as $char) {
1394
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1395
-				return false;
1396
-			}
1397
-		}
1398
-		return true;
1399
-	}
1400
-
1401
-	/**
1402
-	 * Check whether the instance needs to perform an upgrade,
1403
-	 * either when the core version is higher or any app requires
1404
-	 * an upgrade.
1405
-	 *
1406
-	 * @param \OC\SystemConfig $config
1407
-	 * @return bool whether the core or any app needs an upgrade
1408
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1409
-	 */
1410
-	public static function needUpgrade(\OC\SystemConfig $config) {
1411
-		if ($config->getValue('installed', false)) {
1412
-			$installedVersion = $config->getValue('version', '0.0.0');
1413
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1414
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1415
-			if ($versionDiff > 0) {
1416
-				return true;
1417
-			} elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1418
-				// downgrade with debug
1419
-				$installedMajor = explode('.', $installedVersion);
1420
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1421
-				$currentMajor = explode('.', $currentVersion);
1422
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1423
-				if ($installedMajor === $currentMajor) {
1424
-					// Same major, allow downgrade for developers
1425
-					return true;
1426
-				} else {
1427
-					// downgrade attempt, throw exception
1428
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1429
-				}
1430
-			} elseif ($versionDiff < 0) {
1431
-				// downgrade attempt, throw exception
1432
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1433
-			}
1434
-
1435
-			// also check for upgrades for apps (independently from the user)
1436
-			$apps = \OC_App::getEnabledApps(false, true);
1437
-			$shouldUpgrade = false;
1438
-			foreach ($apps as $app) {
1439
-				if (\OC_App::shouldUpgrade($app)) {
1440
-					$shouldUpgrade = true;
1441
-					break;
1442
-				}
1443
-			}
1444
-			return $shouldUpgrade;
1445
-		} else {
1446
-			return false;
1447
-		}
1448
-	}
1449
-
1450
-	/**
1451
-	 * is this Internet explorer ?
1452
-	 *
1453
-	 * @return boolean
1454
-	 */
1455
-	public static function isIe() {
1456
-		if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1457
-			return false;
1458
-		}
1459
-
1460
-		return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1461
-	}
1262
+        return $content !== $testContent && $fallbackContent !== $testContent;
1263
+    }
1264
+
1265
+    /**
1266
+     * Check if the setlocal call does not work. This can happen if the right
1267
+     * local packages are not available on the server.
1268
+     *
1269
+     * @return bool
1270
+     */
1271
+    public static function isSetLocaleWorking() {
1272
+        \Patchwork\Utf8\Bootup::initLocale();
1273
+        if ('' === basename('§')) {
1274
+            return false;
1275
+        }
1276
+        return true;
1277
+    }
1278
+
1279
+    /**
1280
+     * Check if it's possible to get the inline annotations
1281
+     *
1282
+     * @return bool
1283
+     */
1284
+    public static function isAnnotationsWorking() {
1285
+        $reflection = new \ReflectionMethod(__METHOD__);
1286
+        $docs = $reflection->getDocComment();
1287
+
1288
+        return (is_string($docs) && strlen($docs) > 50);
1289
+    }
1290
+
1291
+    /**
1292
+     * Check if the PHP module fileinfo is loaded.
1293
+     *
1294
+     * @return bool
1295
+     */
1296
+    public static function fileInfoLoaded() {
1297
+        return function_exists('finfo_open');
1298
+    }
1299
+
1300
+    /**
1301
+     * clear all levels of output buffering
1302
+     *
1303
+     * @return void
1304
+     */
1305
+    public static function obEnd() {
1306
+        while (ob_get_level()) {
1307
+            ob_end_clean();
1308
+        }
1309
+    }
1310
+
1311
+    /**
1312
+     * Checks whether the server is running on Mac OS X
1313
+     *
1314
+     * @return bool true if running on Mac OS X, false otherwise
1315
+     */
1316
+    public static function runningOnMac() {
1317
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1318
+    }
1319
+
1320
+    /**
1321
+     * Handles the case that there may not be a theme, then check if a "default"
1322
+     * theme exists and take that one
1323
+     *
1324
+     * @return string the theme
1325
+     */
1326
+    public static function getTheme() {
1327
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1328
+
1329
+        if ($theme === '') {
1330
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1331
+                $theme = 'default';
1332
+            }
1333
+        }
1334
+
1335
+        return $theme;
1336
+    }
1337
+
1338
+    /**
1339
+     * Normalize a unicode string
1340
+     *
1341
+     * @param string $value a not normalized string
1342
+     * @return bool|string
1343
+     */
1344
+    public static function normalizeUnicode($value) {
1345
+        if (Normalizer::isNormalized($value)) {
1346
+            return $value;
1347
+        }
1348
+
1349
+        $normalizedValue = Normalizer::normalize($value);
1350
+        if ($normalizedValue === null || $normalizedValue === false) {
1351
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1352
+            return $value;
1353
+        }
1354
+
1355
+        return $normalizedValue;
1356
+    }
1357
+
1358
+    /**
1359
+     * A human readable string is generated based on version and build number
1360
+     *
1361
+     * @return string
1362
+     */
1363
+    public static function getHumanVersion() {
1364
+        $version = OC_Util::getVersionString();
1365
+        $build = OC_Util::getBuild();
1366
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1367
+            $version .= ' Build:' . $build;
1368
+        }
1369
+        return $version;
1370
+    }
1371
+
1372
+    /**
1373
+     * Returns whether the given file name is valid
1374
+     *
1375
+     * @param string $file file name to check
1376
+     * @return bool true if the file name is valid, false otherwise
1377
+     * @deprecated use \OC\Files\View::verifyPath()
1378
+     */
1379
+    public static function isValidFileName($file) {
1380
+        $trimmed = trim($file);
1381
+        if ($trimmed === '') {
1382
+            return false;
1383
+        }
1384
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1385
+            return false;
1386
+        }
1387
+
1388
+        // detect part files
1389
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1390
+            return false;
1391
+        }
1392
+
1393
+        foreach (str_split($trimmed) as $char) {
1394
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1395
+                return false;
1396
+            }
1397
+        }
1398
+        return true;
1399
+    }
1400
+
1401
+    /**
1402
+     * Check whether the instance needs to perform an upgrade,
1403
+     * either when the core version is higher or any app requires
1404
+     * an upgrade.
1405
+     *
1406
+     * @param \OC\SystemConfig $config
1407
+     * @return bool whether the core or any app needs an upgrade
1408
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1409
+     */
1410
+    public static function needUpgrade(\OC\SystemConfig $config) {
1411
+        if ($config->getValue('installed', false)) {
1412
+            $installedVersion = $config->getValue('version', '0.0.0');
1413
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1414
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1415
+            if ($versionDiff > 0) {
1416
+                return true;
1417
+            } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1418
+                // downgrade with debug
1419
+                $installedMajor = explode('.', $installedVersion);
1420
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1421
+                $currentMajor = explode('.', $currentVersion);
1422
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1423
+                if ($installedMajor === $currentMajor) {
1424
+                    // Same major, allow downgrade for developers
1425
+                    return true;
1426
+                } else {
1427
+                    // downgrade attempt, throw exception
1428
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1429
+                }
1430
+            } elseif ($versionDiff < 0) {
1431
+                // downgrade attempt, throw exception
1432
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1433
+            }
1434
+
1435
+            // also check for upgrades for apps (independently from the user)
1436
+            $apps = \OC_App::getEnabledApps(false, true);
1437
+            $shouldUpgrade = false;
1438
+            foreach ($apps as $app) {
1439
+                if (\OC_App::shouldUpgrade($app)) {
1440
+                    $shouldUpgrade = true;
1441
+                    break;
1442
+                }
1443
+            }
1444
+            return $shouldUpgrade;
1445
+        } else {
1446
+            return false;
1447
+        }
1448
+    }
1449
+
1450
+    /**
1451
+     * is this Internet explorer ?
1452
+     *
1453
+     * @return boolean
1454
+     */
1455
+    public static function isIe() {
1456
+        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1457
+            return false;
1458
+        }
1459
+
1460
+        return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1461
+    }
1462 1462
 }
Please login to merge, or discard this patch.