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