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