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