Passed
Push — master ( f0dd71...c56a27 )
by Christoph
11:49 queued 12s
created
lib/private/App/CodeChecker/CodeChecker.php 2 patches
Indentation   +101 added lines, -101 removed lines patch added patch discarded remove patch
@@ -38,105 +38,105 @@
 block discarded – undo
38 38
 
39 39
 class CodeChecker extends BasicEmitter {
40 40
 
41
-	const CLASS_EXTENDS_NOT_ALLOWED = 1000;
42
-	const CLASS_IMPLEMENTS_NOT_ALLOWED = 1001;
43
-	const STATIC_CALL_NOT_ALLOWED = 1002;
44
-	const CLASS_CONST_FETCH_NOT_ALLOWED = 1003;
45
-	const CLASS_NEW_NOT_ALLOWED =  1004;
46
-	const OP_OPERATOR_USAGE_DISCOURAGED =  1005;
47
-	const CLASS_USE_NOT_ALLOWED =  1006;
48
-	const CLASS_METHOD_CALL_NOT_ALLOWED =  1007;
49
-
50
-	/** @var Parser */
51
-	private $parser;
52
-
53
-	/** @var ICheck */
54
-	protected $checkList;
55
-
56
-	/** @var bool */
57
-	protected $checkMigrationSchema;
58
-
59
-	public function __construct(ICheck $checkList, $checkMigrationSchema) {
60
-		$this->checkList = $checkList;
61
-		$this->checkMigrationSchema = $checkMigrationSchema;
62
-		$this->parser = (new ParserFactory)->create(ParserFactory::ONLY_PHP7);
63
-	}
64
-
65
-	/**
66
-	 * @param string $appId
67
-	 * @return array
68
-	 * @throws \RuntimeException if app with $appId is unknown
69
-	 */
70
-	public function analyse(string $appId): array {
71
-		$appPath = \OC_App::getAppPath($appId);
72
-		if ($appPath === false) {
73
-			throw new \RuntimeException("No app with given id <$appId> known.");
74
-		}
75
-
76
-		return $this->analyseFolder($appId, $appPath);
77
-	}
78
-
79
-	/**
80
-	 * @param string $appId
81
-	 * @param string $folder
82
-	 * @return array
83
-	 */
84
-	public function analyseFolder(string $appId, string $folder): array {
85
-		$errors = [];
86
-
87
-		$excludedDirectories = ['vendor', '3rdparty', '.git', 'l10n', 'tests', 'test', 'build'];
88
-		if ($appId === 'password_policy') {
89
-			$excludedDirectories[] = 'lists';
90
-		}
91
-
92
-		$excludes = array_map(function ($item) use ($folder) {
93
-			return $folder . '/' . $item;
94
-		}, $excludedDirectories);
95
-
96
-		$iterator = new RecursiveDirectoryIterator($folder, RecursiveDirectoryIterator::SKIP_DOTS);
97
-		$iterator = new RecursiveCallbackFilterIterator($iterator, function ($item) use ($excludes) {
98
-			/** @var SplFileInfo $item */
99
-			foreach($excludes as $exclude) {
100
-				if (substr($item->getPath(), 0, strlen($exclude)) === $exclude) {
101
-					return false;
102
-				}
103
-			}
104
-			return true;
105
-		});
106
-		$iterator = new RecursiveIteratorIterator($iterator);
107
-		$iterator = new RegexIterator($iterator, '/^.+\.php$/i');
108
-
109
-		foreach ($iterator as $file) {
110
-			/** @var SplFileInfo $file */
111
-			$this->emit('CodeChecker', 'analyseFileBegin', [$file->getPathname()]);
112
-			$fileErrors = $this->analyseFile($file->__toString());
113
-			$this->emit('CodeChecker', 'analyseFileFinished', [$file->getPathname(), $fileErrors]);
114
-			$errors = array_merge($fileErrors, $errors);
115
-		}
116
-
117
-		return $errors;
118
-	}
119
-
120
-
121
-	/**
122
-	 * @param string $file
123
-	 * @return array
124
-	 */
125
-	public function analyseFile(string $file): array {
126
-		$code = file_get_contents($file);
127
-		$statements = $this->parser->parse($code);
128
-
129
-		$visitor = new NodeVisitor($this->checkList);
130
-		$migrationVisitor = new MigrationSchemaChecker();
131
-		$traverser = new NodeTraverser;
132
-		$traverser->addVisitor($visitor);
133
-
134
-		if ($this->checkMigrationSchema && preg_match('#^.+\\/Migration\\/Version[^\\/]{1,255}\\.php$#i', $file)) {
135
-			$traverser->addVisitor($migrationVisitor);
136
-		}
137
-
138
-		$traverser->traverse($statements);
139
-
140
-		return array_merge($visitor->errors, $migrationVisitor->errors);
141
-	}
41
+    const CLASS_EXTENDS_NOT_ALLOWED = 1000;
42
+    const CLASS_IMPLEMENTS_NOT_ALLOWED = 1001;
43
+    const STATIC_CALL_NOT_ALLOWED = 1002;
44
+    const CLASS_CONST_FETCH_NOT_ALLOWED = 1003;
45
+    const CLASS_NEW_NOT_ALLOWED =  1004;
46
+    const OP_OPERATOR_USAGE_DISCOURAGED =  1005;
47
+    const CLASS_USE_NOT_ALLOWED =  1006;
48
+    const CLASS_METHOD_CALL_NOT_ALLOWED =  1007;
49
+
50
+    /** @var Parser */
51
+    private $parser;
52
+
53
+    /** @var ICheck */
54
+    protected $checkList;
55
+
56
+    /** @var bool */
57
+    protected $checkMigrationSchema;
58
+
59
+    public function __construct(ICheck $checkList, $checkMigrationSchema) {
60
+        $this->checkList = $checkList;
61
+        $this->checkMigrationSchema = $checkMigrationSchema;
62
+        $this->parser = (new ParserFactory)->create(ParserFactory::ONLY_PHP7);
63
+    }
64
+
65
+    /**
66
+     * @param string $appId
67
+     * @return array
68
+     * @throws \RuntimeException if app with $appId is unknown
69
+     */
70
+    public function analyse(string $appId): array {
71
+        $appPath = \OC_App::getAppPath($appId);
72
+        if ($appPath === false) {
73
+            throw new \RuntimeException("No app with given id <$appId> known.");
74
+        }
75
+
76
+        return $this->analyseFolder($appId, $appPath);
77
+    }
78
+
79
+    /**
80
+     * @param string $appId
81
+     * @param string $folder
82
+     * @return array
83
+     */
84
+    public function analyseFolder(string $appId, string $folder): array {
85
+        $errors = [];
86
+
87
+        $excludedDirectories = ['vendor', '3rdparty', '.git', 'l10n', 'tests', 'test', 'build'];
88
+        if ($appId === 'password_policy') {
89
+            $excludedDirectories[] = 'lists';
90
+        }
91
+
92
+        $excludes = array_map(function ($item) use ($folder) {
93
+            return $folder . '/' . $item;
94
+        }, $excludedDirectories);
95
+
96
+        $iterator = new RecursiveDirectoryIterator($folder, RecursiveDirectoryIterator::SKIP_DOTS);
97
+        $iterator = new RecursiveCallbackFilterIterator($iterator, function ($item) use ($excludes) {
98
+            /** @var SplFileInfo $item */
99
+            foreach($excludes as $exclude) {
100
+                if (substr($item->getPath(), 0, strlen($exclude)) === $exclude) {
101
+                    return false;
102
+                }
103
+            }
104
+            return true;
105
+        });
106
+        $iterator = new RecursiveIteratorIterator($iterator);
107
+        $iterator = new RegexIterator($iterator, '/^.+\.php$/i');
108
+
109
+        foreach ($iterator as $file) {
110
+            /** @var SplFileInfo $file */
111
+            $this->emit('CodeChecker', 'analyseFileBegin', [$file->getPathname()]);
112
+            $fileErrors = $this->analyseFile($file->__toString());
113
+            $this->emit('CodeChecker', 'analyseFileFinished', [$file->getPathname(), $fileErrors]);
114
+            $errors = array_merge($fileErrors, $errors);
115
+        }
116
+
117
+        return $errors;
118
+    }
119
+
120
+
121
+    /**
122
+     * @param string $file
123
+     * @return array
124
+     */
125
+    public function analyseFile(string $file): array {
126
+        $code = file_get_contents($file);
127
+        $statements = $this->parser->parse($code);
128
+
129
+        $visitor = new NodeVisitor($this->checkList);
130
+        $migrationVisitor = new MigrationSchemaChecker();
131
+        $traverser = new NodeTraverser;
132
+        $traverser->addVisitor($visitor);
133
+
134
+        if ($this->checkMigrationSchema && preg_match('#^.+\\/Migration\\/Version[^\\/]{1,255}\\.php$#i', $file)) {
135
+            $traverser->addVisitor($migrationVisitor);
136
+        }
137
+
138
+        $traverser->traverse($statements);
139
+
140
+        return array_merge($visitor->errors, $migrationVisitor->errors);
141
+    }
142 142
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -42,10 +42,10 @@  discard block
 block discarded – undo
42 42
 	const CLASS_IMPLEMENTS_NOT_ALLOWED = 1001;
43 43
 	const STATIC_CALL_NOT_ALLOWED = 1002;
44 44
 	const CLASS_CONST_FETCH_NOT_ALLOWED = 1003;
45
-	const CLASS_NEW_NOT_ALLOWED =  1004;
46
-	const OP_OPERATOR_USAGE_DISCOURAGED =  1005;
47
-	const CLASS_USE_NOT_ALLOWED =  1006;
48
-	const CLASS_METHOD_CALL_NOT_ALLOWED =  1007;
45
+	const CLASS_NEW_NOT_ALLOWED = 1004;
46
+	const OP_OPERATOR_USAGE_DISCOURAGED = 1005;
47
+	const CLASS_USE_NOT_ALLOWED = 1006;
48
+	const CLASS_METHOD_CALL_NOT_ALLOWED = 1007;
49 49
 
50 50
 	/** @var Parser */
51 51
 	private $parser;
@@ -89,14 +89,14 @@  discard block
 block discarded – undo
89 89
 			$excludedDirectories[] = 'lists';
90 90
 		}
91 91
 
92
-		$excludes = array_map(function ($item) use ($folder) {
93
-			return $folder . '/' . $item;
92
+		$excludes = array_map(function($item) use ($folder) {
93
+			return $folder.'/'.$item;
94 94
 		}, $excludedDirectories);
95 95
 
96 96
 		$iterator = new RecursiveDirectoryIterator($folder, RecursiveDirectoryIterator::SKIP_DOTS);
97
-		$iterator = new RecursiveCallbackFilterIterator($iterator, function ($item) use ($excludes) {
97
+		$iterator = new RecursiveCallbackFilterIterator($iterator, function($item) use ($excludes) {
98 98
 			/** @var SplFileInfo $item */
99
-			foreach($excludes as $exclude) {
99
+			foreach ($excludes as $exclude) {
100 100
 				if (substr($item->getPath(), 0, strlen($exclude)) === $exclude) {
101 101
 					return false;
102 102
 				}
Please login to merge, or discard this patch.
lib/private/Encryption/Util.php 2 patches
Indentation   +369 added lines, -369 removed lines patch added patch discarded remove patch
@@ -39,374 +39,374 @@
 block discarded – undo
39 39
 
40 40
 class Util {
41 41
 
42
-	const HEADER_START = 'HBEGIN';
43
-	const HEADER_END = 'HEND';
44
-	const HEADER_PADDING_CHAR = '-';
45
-
46
-	const HEADER_ENCRYPTION_MODULE_KEY = 'oc_encryption_module';
47
-
48
-	/**
49
-	 * block size will always be 8192 for a PHP stream
50
-	 * @see https://bugs.php.net/bug.php?id=21641
51
-	 * @var integer
52
-	 */
53
-	protected $headerSize = 8192;
54
-
55
-	/**
56
-	 * block size will always be 8192 for a PHP stream
57
-	 * @see https://bugs.php.net/bug.php?id=21641
58
-	 * @var integer
59
-	 */
60
-	protected $blockSize = 8192;
61
-
62
-	/** @var View */
63
-	protected $rootView;
64
-
65
-	/** @var array */
66
-	protected $ocHeaderKeys;
67
-
68
-	/** @var \OC\User\Manager */
69
-	protected $userManager;
70
-
71
-	/** @var IConfig */
72
-	protected $config;
73
-
74
-	/** @var array paths excluded from encryption */
75
-	protected $excludedPaths;
76
-
77
-	/** @var \OC\Group\Manager $manager */
78
-	protected $groupManager;
79
-
80
-	/**
81
-	 *
82
-	 * @param View $rootView
83
-	 * @param \OC\User\Manager $userManager
84
-	 * @param \OC\Group\Manager $groupManager
85
-	 * @param IConfig $config
86
-	 */
87
-	public function __construct(
88
-		View $rootView,
89
-		\OC\User\Manager $userManager,
90
-		\OC\Group\Manager $groupManager,
91
-		IConfig $config) {
92
-
93
-		$this->ocHeaderKeys = [
94
-			self::HEADER_ENCRYPTION_MODULE_KEY
95
-		];
96
-
97
-		$this->rootView = $rootView;
98
-		$this->userManager = $userManager;
99
-		$this->groupManager = $groupManager;
100
-		$this->config = $config;
101
-
102
-		$this->excludedPaths[] = 'files_encryption';
103
-		$this->excludedPaths[] = 'appdata_' . $config->getSystemValue('instanceid', null);
104
-		$this->excludedPaths[] = 'files_external';
105
-	}
106
-
107
-	/**
108
-	 * read encryption module ID from header
109
-	 *
110
-	 * @param array $header
111
-	 * @return string
112
-	 * @throws ModuleDoesNotExistsException
113
-	 */
114
-	public function getEncryptionModuleId(array $header = null) {
115
-		$id = '';
116
-		$encryptionModuleKey = self::HEADER_ENCRYPTION_MODULE_KEY;
117
-
118
-		if (isset($header[$encryptionModuleKey])) {
119
-			$id = $header[$encryptionModuleKey];
120
-		} elseif (isset($header['cipher'])) {
121
-			if (class_exists('\OCA\Encryption\Crypto\Encryption')) {
122
-				// fall back to default encryption if the user migrated from
123
-				// ownCloud <= 8.0 with the old encryption
124
-				$id = \OCA\Encryption\Crypto\Encryption::ID;
125
-			} else {
126
-				throw new ModuleDoesNotExistsException('Default encryption module missing');
127
-			}
128
-		}
129
-
130
-		return $id;
131
-	}
132
-
133
-	/**
134
-	 * create header for encrypted file
135
-	 *
136
-	 * @param array $headerData
137
-	 * @param IEncryptionModule $encryptionModule
138
-	 * @return string
139
-	 * @throws EncryptionHeaderToLargeException if header has to many arguments
140
-	 * @throws EncryptionHeaderKeyExistsException if header key is already in use
141
-	 */
142
-	public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
143
-		$header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
144
-		foreach ($headerData as $key => $value) {
145
-			if (in_array($key, $this->ocHeaderKeys)) {
146
-				throw new EncryptionHeaderKeyExistsException($key);
147
-			}
148
-			$header .= $key . ':' . $value . ':';
149
-		}
150
-		$header .= self::HEADER_END;
151
-
152
-		if (strlen($header) > $this->getHeaderSize()) {
153
-			throw new EncryptionHeaderToLargeException();
154
-		}
155
-
156
-		$paddedHeader = str_pad($header, $this->headerSize, self::HEADER_PADDING_CHAR, STR_PAD_RIGHT);
157
-
158
-		return $paddedHeader;
159
-	}
160
-
161
-	/**
162
-	 * go recursively through a dir and collect all files and sub files.
163
-	 *
164
-	 * @param string $dir relative to the users files folder
165
-	 * @return array with list of files relative to the users files folder
166
-	 */
167
-	public function getAllFiles($dir) {
168
-		$result = [];
169
-		$dirList = [$dir];
170
-
171
-		while ($dirList) {
172
-			$dir = array_pop($dirList);
173
-			$content = $this->rootView->getDirectoryContent($dir);
174
-
175
-			foreach ($content as $c) {
176
-				if ($c->getType() === 'dir') {
177
-					$dirList[] = $c->getPath();
178
-				} else {
179
-					$result[] =  $c->getPath();
180
-				}
181
-			}
182
-
183
-		}
184
-
185
-		return $result;
186
-	}
187
-
188
-	/**
189
-	 * check if it is a file uploaded by the user stored in data/user/files
190
-	 * or a metadata file
191
-	 *
192
-	 * @param string $path relative to the data/ folder
193
-	 * @return boolean
194
-	 */
195
-	public function isFile($path) {
196
-		$parts = explode('/', Filesystem::normalizePath($path), 4);
197
-		if (isset($parts[2]) && $parts[2] === 'files') {
198
-			return true;
199
-		}
200
-		return false;
201
-	}
202
-
203
-	/**
204
-	 * return size of encryption header
205
-	 *
206
-	 * @return integer
207
-	 */
208
-	public function getHeaderSize() {
209
-		return $this->headerSize;
210
-	}
211
-
212
-	/**
213
-	 * return size of block read by a PHP stream
214
-	 *
215
-	 * @return integer
216
-	 */
217
-	public function getBlockSize() {
218
-		return $this->blockSize;
219
-	}
220
-
221
-	/**
222
-	 * get the owner and the path for the file relative to the owners files folder
223
-	 *
224
-	 * @param string $path
225
-	 * @return array
226
-	 * @throws \BadMethodCallException
227
-	 */
228
-	public function getUidAndFilename($path) {
229
-
230
-		$parts = explode('/', $path);
231
-		$uid = '';
232
-		if (count($parts) > 2) {
233
-			$uid = $parts[1];
234
-		}
235
-		if (!$this->userManager->userExists($uid)) {
236
-			throw new \BadMethodCallException(
237
-				'path needs to be relative to the system wide data folder and point to a user specific file'
238
-			);
239
-		}
240
-
241
-		$ownerPath = implode('/', array_slice($parts, 2));
242
-
243
-		return [$uid, Filesystem::normalizePath($ownerPath)];
244
-
245
-	}
246
-
247
-	/**
248
-	 * Remove .path extension from a file path
249
-	 * @param string $path Path that may identify a .part file
250
-	 * @return string File path without .part extension
251
-	 * @note this is needed for reusing keys
252
-	 */
253
-	public function stripPartialFileExtension($path) {
254
-		$extension = pathinfo($path, PATHINFO_EXTENSION);
255
-
256
-		if ( $extension === 'part') {
257
-
258
-			$newLength = strlen($path) - 5; // 5 = strlen(".part")
259
-			$fPath = substr($path, 0, $newLength);
260
-
261
-			// if path also contains a transaction id, we remove it too
262
-			$extension = pathinfo($fPath, PATHINFO_EXTENSION);
263
-			if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
264
-				$newLength = strlen($fPath) - strlen($extension) -1;
265
-				$fPath = substr($fPath, 0, $newLength);
266
-			}
267
-			return $fPath;
268
-
269
-		} else {
270
-			return $path;
271
-		}
272
-	}
273
-
274
-	public function getUserWithAccessToMountPoint($users, $groups) {
275
-		$result = [];
276
-		if (in_array('all', $users)) {
277
-			$users = $this->userManager->search('', null, null);
278
-			$result = array_map(function (IUser $user) {
279
-				return $user->getUID();
280
-			}, $users);
281
-		} else {
282
-			$result = array_merge($result, $users);
283
-
284
-			$groupManager = \OC::$server->getGroupManager();
285
-			foreach ($groups as $group) {
286
-				$groupObject = $groupManager->get($group);
287
-				if ($groupObject) {
288
-					$foundUsers = $groupObject->searchUsers('', -1, 0);
289
-					$userIds = [];
290
-					foreach ($foundUsers as $user) {
291
-						$userIds[] = $user->getUID();
292
-					}
293
-					$result = array_merge($result, $userIds);
294
-				}
295
-			}
296
-		}
297
-
298
-		return $result;
299
-	}
300
-
301
-	/**
302
-	 * check if the file is stored on a system wide mount point
303
-	 * @param string $path relative to /data/user with leading '/'
304
-	 * @param string $uid
305
-	 * @return boolean
306
-	 */
307
-	public function isSystemWideMountPoint($path, $uid) {
308
-		if (\OCP\App::isEnabled("files_external")) {
309
-			$mounts = \OC_Mount_Config::getSystemMountPoints();
310
-			foreach ($mounts as $mount) {
311
-				if (strpos($path, '/files/' . $mount['mountpoint']) === 0) {
312
-					if ($this->isMountPointApplicableToUser($mount, $uid)) {
313
-						return true;
314
-					}
315
-				}
316
-			}
317
-		}
318
-		return false;
319
-	}
320
-
321
-	/**
322
-	 * check if mount point is applicable to user
323
-	 *
324
-	 * @param array $mount contains $mount['applicable']['users'], $mount['applicable']['groups']
325
-	 * @param string $uid
326
-	 * @return boolean
327
-	 */
328
-	private function isMountPointApplicableToUser($mount, $uid) {
329
-		$acceptedUids = ['all', $uid];
330
-		// check if mount point is applicable for the user
331
-		$intersection = array_intersect($acceptedUids, $mount['applicable']['users']);
332
-		if (!empty($intersection)) {
333
-			return true;
334
-		}
335
-		// check if mount point is applicable for group where the user is a member
336
-		foreach ($mount['applicable']['groups'] as $gid) {
337
-			if ($this->groupManager->isInGroup($uid, $gid)) {
338
-				return true;
339
-			}
340
-		}
341
-		return false;
342
-	}
343
-
344
-	/**
345
-	 * check if it is a path which is excluded by ownCloud from encryption
346
-	 *
347
-	 * @param string $path
348
-	 * @return boolean
349
-	 */
350
-	public function isExcluded($path) {
351
-		$normalizedPath = Filesystem::normalizePath($path);
352
-		$root = explode('/', $normalizedPath, 4);
353
-		if (count($root) > 1) {
354
-
355
-			// detect alternative key storage root
356
-			$rootDir = $this->getKeyStorageRoot();
357
-			if ($rootDir !== '' &&
358
-				0 === strpos(
359
-					Filesystem::normalizePath($path),
360
-					Filesystem::normalizePath($rootDir)
361
-				)
362
-			) {
363
-				return true;
364
-			}
365
-
366
-
367
-			//detect system wide folders
368
-			if (in_array($root[1], $this->excludedPaths)) {
369
-				return true;
370
-			}
371
-
372
-			// detect user specific folders
373
-			if ($this->userManager->userExists($root[1])
374
-				&& in_array($root[2], $this->excludedPaths)) {
375
-
376
-				return true;
377
-			}
378
-		}
379
-		return false;
380
-	}
381
-
382
-	/**
383
-	 * check if recovery key is enabled for user
384
-	 *
385
-	 * @param string $uid
386
-	 * @return boolean
387
-	 */
388
-	public function recoveryEnabled($uid) {
389
-		$enabled = $this->config->getUserValue($uid, 'encryption', 'recovery_enabled', '0');
390
-
391
-		return $enabled === '1';
392
-	}
393
-
394
-	/**
395
-	 * set new key storage root
396
-	 *
397
-	 * @param string $root new key store root relative to the data folder
398
-	 */
399
-	public function setKeyStorageRoot($root) {
400
-		$this->config->setAppValue('core', 'encryption_key_storage_root', $root);
401
-	}
402
-
403
-	/**
404
-	 * get key storage root
405
-	 *
406
-	 * @return string key storage root
407
-	 */
408
-	public function getKeyStorageRoot() {
409
-		return $this->config->getAppValue('core', 'encryption_key_storage_root', '');
410
-	}
42
+    const HEADER_START = 'HBEGIN';
43
+    const HEADER_END = 'HEND';
44
+    const HEADER_PADDING_CHAR = '-';
45
+
46
+    const HEADER_ENCRYPTION_MODULE_KEY = 'oc_encryption_module';
47
+
48
+    /**
49
+     * block size will always be 8192 for a PHP stream
50
+     * @see https://bugs.php.net/bug.php?id=21641
51
+     * @var integer
52
+     */
53
+    protected $headerSize = 8192;
54
+
55
+    /**
56
+     * block size will always be 8192 for a PHP stream
57
+     * @see https://bugs.php.net/bug.php?id=21641
58
+     * @var integer
59
+     */
60
+    protected $blockSize = 8192;
61
+
62
+    /** @var View */
63
+    protected $rootView;
64
+
65
+    /** @var array */
66
+    protected $ocHeaderKeys;
67
+
68
+    /** @var \OC\User\Manager */
69
+    protected $userManager;
70
+
71
+    /** @var IConfig */
72
+    protected $config;
73
+
74
+    /** @var array paths excluded from encryption */
75
+    protected $excludedPaths;
76
+
77
+    /** @var \OC\Group\Manager $manager */
78
+    protected $groupManager;
79
+
80
+    /**
81
+     *
82
+     * @param View $rootView
83
+     * @param \OC\User\Manager $userManager
84
+     * @param \OC\Group\Manager $groupManager
85
+     * @param IConfig $config
86
+     */
87
+    public function __construct(
88
+        View $rootView,
89
+        \OC\User\Manager $userManager,
90
+        \OC\Group\Manager $groupManager,
91
+        IConfig $config) {
92
+
93
+        $this->ocHeaderKeys = [
94
+            self::HEADER_ENCRYPTION_MODULE_KEY
95
+        ];
96
+
97
+        $this->rootView = $rootView;
98
+        $this->userManager = $userManager;
99
+        $this->groupManager = $groupManager;
100
+        $this->config = $config;
101
+
102
+        $this->excludedPaths[] = 'files_encryption';
103
+        $this->excludedPaths[] = 'appdata_' . $config->getSystemValue('instanceid', null);
104
+        $this->excludedPaths[] = 'files_external';
105
+    }
106
+
107
+    /**
108
+     * read encryption module ID from header
109
+     *
110
+     * @param array $header
111
+     * @return string
112
+     * @throws ModuleDoesNotExistsException
113
+     */
114
+    public function getEncryptionModuleId(array $header = null) {
115
+        $id = '';
116
+        $encryptionModuleKey = self::HEADER_ENCRYPTION_MODULE_KEY;
117
+
118
+        if (isset($header[$encryptionModuleKey])) {
119
+            $id = $header[$encryptionModuleKey];
120
+        } elseif (isset($header['cipher'])) {
121
+            if (class_exists('\OCA\Encryption\Crypto\Encryption')) {
122
+                // fall back to default encryption if the user migrated from
123
+                // ownCloud <= 8.0 with the old encryption
124
+                $id = \OCA\Encryption\Crypto\Encryption::ID;
125
+            } else {
126
+                throw new ModuleDoesNotExistsException('Default encryption module missing');
127
+            }
128
+        }
129
+
130
+        return $id;
131
+    }
132
+
133
+    /**
134
+     * create header for encrypted file
135
+     *
136
+     * @param array $headerData
137
+     * @param IEncryptionModule $encryptionModule
138
+     * @return string
139
+     * @throws EncryptionHeaderToLargeException if header has to many arguments
140
+     * @throws EncryptionHeaderKeyExistsException if header key is already in use
141
+     */
142
+    public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
143
+        $header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
144
+        foreach ($headerData as $key => $value) {
145
+            if (in_array($key, $this->ocHeaderKeys)) {
146
+                throw new EncryptionHeaderKeyExistsException($key);
147
+            }
148
+            $header .= $key . ':' . $value . ':';
149
+        }
150
+        $header .= self::HEADER_END;
151
+
152
+        if (strlen($header) > $this->getHeaderSize()) {
153
+            throw new EncryptionHeaderToLargeException();
154
+        }
155
+
156
+        $paddedHeader = str_pad($header, $this->headerSize, self::HEADER_PADDING_CHAR, STR_PAD_RIGHT);
157
+
158
+        return $paddedHeader;
159
+    }
160
+
161
+    /**
162
+     * go recursively through a dir and collect all files and sub files.
163
+     *
164
+     * @param string $dir relative to the users files folder
165
+     * @return array with list of files relative to the users files folder
166
+     */
167
+    public function getAllFiles($dir) {
168
+        $result = [];
169
+        $dirList = [$dir];
170
+
171
+        while ($dirList) {
172
+            $dir = array_pop($dirList);
173
+            $content = $this->rootView->getDirectoryContent($dir);
174
+
175
+            foreach ($content as $c) {
176
+                if ($c->getType() === 'dir') {
177
+                    $dirList[] = $c->getPath();
178
+                } else {
179
+                    $result[] =  $c->getPath();
180
+                }
181
+            }
182
+
183
+        }
184
+
185
+        return $result;
186
+    }
187
+
188
+    /**
189
+     * check if it is a file uploaded by the user stored in data/user/files
190
+     * or a metadata file
191
+     *
192
+     * @param string $path relative to the data/ folder
193
+     * @return boolean
194
+     */
195
+    public function isFile($path) {
196
+        $parts = explode('/', Filesystem::normalizePath($path), 4);
197
+        if (isset($parts[2]) && $parts[2] === 'files') {
198
+            return true;
199
+        }
200
+        return false;
201
+    }
202
+
203
+    /**
204
+     * return size of encryption header
205
+     *
206
+     * @return integer
207
+     */
208
+    public function getHeaderSize() {
209
+        return $this->headerSize;
210
+    }
211
+
212
+    /**
213
+     * return size of block read by a PHP stream
214
+     *
215
+     * @return integer
216
+     */
217
+    public function getBlockSize() {
218
+        return $this->blockSize;
219
+    }
220
+
221
+    /**
222
+     * get the owner and the path for the file relative to the owners files folder
223
+     *
224
+     * @param string $path
225
+     * @return array
226
+     * @throws \BadMethodCallException
227
+     */
228
+    public function getUidAndFilename($path) {
229
+
230
+        $parts = explode('/', $path);
231
+        $uid = '';
232
+        if (count($parts) > 2) {
233
+            $uid = $parts[1];
234
+        }
235
+        if (!$this->userManager->userExists($uid)) {
236
+            throw new \BadMethodCallException(
237
+                'path needs to be relative to the system wide data folder and point to a user specific file'
238
+            );
239
+        }
240
+
241
+        $ownerPath = implode('/', array_slice($parts, 2));
242
+
243
+        return [$uid, Filesystem::normalizePath($ownerPath)];
244
+
245
+    }
246
+
247
+    /**
248
+     * Remove .path extension from a file path
249
+     * @param string $path Path that may identify a .part file
250
+     * @return string File path without .part extension
251
+     * @note this is needed for reusing keys
252
+     */
253
+    public function stripPartialFileExtension($path) {
254
+        $extension = pathinfo($path, PATHINFO_EXTENSION);
255
+
256
+        if ( $extension === 'part') {
257
+
258
+            $newLength = strlen($path) - 5; // 5 = strlen(".part")
259
+            $fPath = substr($path, 0, $newLength);
260
+
261
+            // if path also contains a transaction id, we remove it too
262
+            $extension = pathinfo($fPath, PATHINFO_EXTENSION);
263
+            if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
264
+                $newLength = strlen($fPath) - strlen($extension) -1;
265
+                $fPath = substr($fPath, 0, $newLength);
266
+            }
267
+            return $fPath;
268
+
269
+        } else {
270
+            return $path;
271
+        }
272
+    }
273
+
274
+    public function getUserWithAccessToMountPoint($users, $groups) {
275
+        $result = [];
276
+        if (in_array('all', $users)) {
277
+            $users = $this->userManager->search('', null, null);
278
+            $result = array_map(function (IUser $user) {
279
+                return $user->getUID();
280
+            }, $users);
281
+        } else {
282
+            $result = array_merge($result, $users);
283
+
284
+            $groupManager = \OC::$server->getGroupManager();
285
+            foreach ($groups as $group) {
286
+                $groupObject = $groupManager->get($group);
287
+                if ($groupObject) {
288
+                    $foundUsers = $groupObject->searchUsers('', -1, 0);
289
+                    $userIds = [];
290
+                    foreach ($foundUsers as $user) {
291
+                        $userIds[] = $user->getUID();
292
+                    }
293
+                    $result = array_merge($result, $userIds);
294
+                }
295
+            }
296
+        }
297
+
298
+        return $result;
299
+    }
300
+
301
+    /**
302
+     * check if the file is stored on a system wide mount point
303
+     * @param string $path relative to /data/user with leading '/'
304
+     * @param string $uid
305
+     * @return boolean
306
+     */
307
+    public function isSystemWideMountPoint($path, $uid) {
308
+        if (\OCP\App::isEnabled("files_external")) {
309
+            $mounts = \OC_Mount_Config::getSystemMountPoints();
310
+            foreach ($mounts as $mount) {
311
+                if (strpos($path, '/files/' . $mount['mountpoint']) === 0) {
312
+                    if ($this->isMountPointApplicableToUser($mount, $uid)) {
313
+                        return true;
314
+                    }
315
+                }
316
+            }
317
+        }
318
+        return false;
319
+    }
320
+
321
+    /**
322
+     * check if mount point is applicable to user
323
+     *
324
+     * @param array $mount contains $mount['applicable']['users'], $mount['applicable']['groups']
325
+     * @param string $uid
326
+     * @return boolean
327
+     */
328
+    private function isMountPointApplicableToUser($mount, $uid) {
329
+        $acceptedUids = ['all', $uid];
330
+        // check if mount point is applicable for the user
331
+        $intersection = array_intersect($acceptedUids, $mount['applicable']['users']);
332
+        if (!empty($intersection)) {
333
+            return true;
334
+        }
335
+        // check if mount point is applicable for group where the user is a member
336
+        foreach ($mount['applicable']['groups'] as $gid) {
337
+            if ($this->groupManager->isInGroup($uid, $gid)) {
338
+                return true;
339
+            }
340
+        }
341
+        return false;
342
+    }
343
+
344
+    /**
345
+     * check if it is a path which is excluded by ownCloud from encryption
346
+     *
347
+     * @param string $path
348
+     * @return boolean
349
+     */
350
+    public function isExcluded($path) {
351
+        $normalizedPath = Filesystem::normalizePath($path);
352
+        $root = explode('/', $normalizedPath, 4);
353
+        if (count($root) > 1) {
354
+
355
+            // detect alternative key storage root
356
+            $rootDir = $this->getKeyStorageRoot();
357
+            if ($rootDir !== '' &&
358
+                0 === strpos(
359
+                    Filesystem::normalizePath($path),
360
+                    Filesystem::normalizePath($rootDir)
361
+                )
362
+            ) {
363
+                return true;
364
+            }
365
+
366
+
367
+            //detect system wide folders
368
+            if (in_array($root[1], $this->excludedPaths)) {
369
+                return true;
370
+            }
371
+
372
+            // detect user specific folders
373
+            if ($this->userManager->userExists($root[1])
374
+                && in_array($root[2], $this->excludedPaths)) {
375
+
376
+                return true;
377
+            }
378
+        }
379
+        return false;
380
+    }
381
+
382
+    /**
383
+     * check if recovery key is enabled for user
384
+     *
385
+     * @param string $uid
386
+     * @return boolean
387
+     */
388
+    public function recoveryEnabled($uid) {
389
+        $enabled = $this->config->getUserValue($uid, 'encryption', 'recovery_enabled', '0');
390
+
391
+        return $enabled === '1';
392
+    }
393
+
394
+    /**
395
+     * set new key storage root
396
+     *
397
+     * @param string $root new key store root relative to the data folder
398
+     */
399
+    public function setKeyStorageRoot($root) {
400
+        $this->config->setAppValue('core', 'encryption_key_storage_root', $root);
401
+    }
402
+
403
+    /**
404
+     * get key storage root
405
+     *
406
+     * @return string key storage root
407
+     */
408
+    public function getKeyStorageRoot() {
409
+        return $this->config->getAppValue('core', 'encryption_key_storage_root', '');
410
+    }
411 411
 
412 412
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 		$this->config = $config;
101 101
 
102 102
 		$this->excludedPaths[] = 'files_encryption';
103
-		$this->excludedPaths[] = 'appdata_' . $config->getSystemValue('instanceid', null);
103
+		$this->excludedPaths[] = 'appdata_'.$config->getSystemValue('instanceid', null);
104 104
 		$this->excludedPaths[] = 'files_external';
105 105
 	}
106 106
 
@@ -140,12 +140,12 @@  discard block
 block discarded – undo
140 140
 	 * @throws EncryptionHeaderKeyExistsException if header key is already in use
141 141
 	 */
142 142
 	public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
143
-		$header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
143
+		$header = self::HEADER_START.':'.self::HEADER_ENCRYPTION_MODULE_KEY.':'.$encryptionModule->getId().':';
144 144
 		foreach ($headerData as $key => $value) {
145 145
 			if (in_array($key, $this->ocHeaderKeys)) {
146 146
 				throw new EncryptionHeaderKeyExistsException($key);
147 147
 			}
148
-			$header .= $key . ':' . $value . ':';
148
+			$header .= $key.':'.$value.':';
149 149
 		}
150 150
 		$header .= self::HEADER_END;
151 151
 
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 				if ($c->getType() === 'dir') {
177 177
 					$dirList[] = $c->getPath();
178 178
 				} else {
179
-					$result[] =  $c->getPath();
179
+					$result[] = $c->getPath();
180 180
 				}
181 181
 			}
182 182
 
@@ -253,15 +253,15 @@  discard block
 block discarded – undo
253 253
 	public function stripPartialFileExtension($path) {
254 254
 		$extension = pathinfo($path, PATHINFO_EXTENSION);
255 255
 
256
-		if ( $extension === 'part') {
256
+		if ($extension === 'part') {
257 257
 
258 258
 			$newLength = strlen($path) - 5; // 5 = strlen(".part")
259 259
 			$fPath = substr($path, 0, $newLength);
260 260
 
261 261
 			// if path also contains a transaction id, we remove it too
262 262
 			$extension = pathinfo($fPath, PATHINFO_EXTENSION);
263
-			if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
264
-				$newLength = strlen($fPath) - strlen($extension) -1;
263
+			if (substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
264
+				$newLength = strlen($fPath) - strlen($extension) - 1;
265 265
 				$fPath = substr($fPath, 0, $newLength);
266 266
 			}
267 267
 			return $fPath;
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 		$result = [];
276 276
 		if (in_array('all', $users)) {
277 277
 			$users = $this->userManager->search('', null, null);
278
-			$result = array_map(function (IUser $user) {
278
+			$result = array_map(function(IUser $user) {
279 279
 				return $user->getUID();
280 280
 			}, $users);
281 281
 		} else {
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
 		if (\OCP\App::isEnabled("files_external")) {
309 309
 			$mounts = \OC_Mount_Config::getSystemMountPoints();
310 310
 			foreach ($mounts as $mount) {
311
-				if (strpos($path, '/files/' . $mount['mountpoint']) === 0) {
311
+				if (strpos($path, '/files/'.$mount['mountpoint']) === 0) {
312 312
 					if ($this->isMountPointApplicableToUser($mount, $uid)) {
313 313
 						return true;
314 314
 					}
Please login to merge, or discard this patch.
lib/private/legacy/OC_DB_StatementWrapper.php 2 patches
Indentation   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -38,83 +38,83 @@
 block discarded – undo
38 38
  * @method array fetchAll(integer $fetchMode = null);
39 39
  */
40 40
 class OC_DB_StatementWrapper {
41
-	/**
42
-	 * @var \Doctrine\DBAL\Driver\Statement
43
-	 */
44
-	private $statement = null;
45
-	private $isManipulation = false;
46
-	private $lastArguments = [];
41
+    /**
42
+     * @var \Doctrine\DBAL\Driver\Statement
43
+     */
44
+    private $statement = null;
45
+    private $isManipulation = false;
46
+    private $lastArguments = [];
47 47
 
48
-	/**
49
-	 * @param boolean $isManipulation
50
-	 */
51
-	public function __construct($statement, $isManipulation) {
52
-		$this->statement = $statement;
53
-		$this->isManipulation = $isManipulation;
54
-	}
48
+    /**
49
+     * @param boolean $isManipulation
50
+     */
51
+    public function __construct($statement, $isManipulation) {
52
+        $this->statement = $statement;
53
+        $this->isManipulation = $isManipulation;
54
+    }
55 55
 
56
-	/**
57
-	 * pass all other function directly to the \Doctrine\DBAL\Driver\Statement
58
-	 */
59
-	public function __call($name,$arguments) {
60
-		return call_user_func_array([$this->statement,$name], $arguments);
61
-	}
56
+    /**
57
+     * pass all other function directly to the \Doctrine\DBAL\Driver\Statement
58
+     */
59
+    public function __call($name,$arguments) {
60
+        return call_user_func_array([$this->statement,$name], $arguments);
61
+    }
62 62
 
63
-	/**
64
-	 * make execute return the result instead of a bool
65
-	 *
66
-	 * @param array $input
67
-	 * @return \OC_DB_StatementWrapper|int|bool
68
-	 */
69
-	public function execute($input= []) {
70
-		$this->lastArguments = $input;
71
-		if (count($input) > 0) {
72
-			$result = $this->statement->execute($input);
73
-		} else {
74
-			$result = $this->statement->execute();
75
-		}
63
+    /**
64
+     * make execute return the result instead of a bool
65
+     *
66
+     * @param array $input
67
+     * @return \OC_DB_StatementWrapper|int|bool
68
+     */
69
+    public function execute($input= []) {
70
+        $this->lastArguments = $input;
71
+        if (count($input) > 0) {
72
+            $result = $this->statement->execute($input);
73
+        } else {
74
+            $result = $this->statement->execute();
75
+        }
76 76
 
77
-		if ($result === false) {
78
-			return false;
79
-		}
80
-		if ($this->isManipulation) {
81
-			return $this->statement->rowCount();
82
-		} else {
83
-			return $this;
84
-		}
85
-	}
77
+        if ($result === false) {
78
+            return false;
79
+        }
80
+        if ($this->isManipulation) {
81
+            return $this->statement->rowCount();
82
+        } else {
83
+            return $this;
84
+        }
85
+    }
86 86
 
87
-	/**
88
-	 * provide an alias for fetch
89
-	 *
90
-	 * @return mixed
91
-	 */
92
-	public function fetchRow() {
93
-		return $this->statement->fetch();
94
-	}
87
+    /**
88
+     * provide an alias for fetch
89
+     *
90
+     * @return mixed
91
+     */
92
+    public function fetchRow() {
93
+        return $this->statement->fetch();
94
+    }
95 95
 
96
-	/**
97
-	 * Provide a simple fetchOne.
98
-	 *
99
-	 * fetch single column from the next row
100
-	 * @param int $column the column number to fetch
101
-	 * @return string
102
-	 */
103
-	public function fetchOne($column = 0) {
104
-		return $this->statement->fetchColumn($column);
105
-	}
96
+    /**
97
+     * Provide a simple fetchOne.
98
+     *
99
+     * fetch single column from the next row
100
+     * @param int $column the column number to fetch
101
+     * @return string
102
+     */
103
+    public function fetchOne($column = 0) {
104
+        return $this->statement->fetchColumn($column);
105
+    }
106 106
 
107
-	/**
108
-	 * Binds a PHP variable to a corresponding named or question mark placeholder in the
109
-	 * SQL statement that was use to prepare the statement.
110
-	 *
111
-	 * @param mixed $column Either the placeholder name or the 1-indexed placeholder index
112
-	 * @param mixed $variable The variable to bind
113
-	 * @param integer|null $type one of the  PDO::PARAM_* constants
114
-	 * @param integer|null $length max length when using an OUT bind
115
-	 * @return boolean
116
-	 */
117
-	public function bindParam($column, &$variable, $type = null, $length = null) {
118
-		return $this->statement->bindParam($column, $variable, $type, $length);
119
-	}
107
+    /**
108
+     * Binds a PHP variable to a corresponding named or question mark placeholder in the
109
+     * SQL statement that was use to prepare the statement.
110
+     *
111
+     * @param mixed $column Either the placeholder name or the 1-indexed placeholder index
112
+     * @param mixed $variable The variable to bind
113
+     * @param integer|null $type one of the  PDO::PARAM_* constants
114
+     * @param integer|null $length max length when using an OUT bind
115
+     * @return boolean
116
+     */
117
+    public function bindParam($column, &$variable, $type = null, $length = null) {
118
+        return $this->statement->bindParam($column, $variable, $type, $length);
119
+    }
120 120
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -56,8 +56,8 @@  discard block
 block discarded – undo
56 56
 	/**
57 57
 	 * pass all other function directly to the \Doctrine\DBAL\Driver\Statement
58 58
 	 */
59
-	public function __call($name,$arguments) {
60
-		return call_user_func_array([$this->statement,$name], $arguments);
59
+	public function __call($name, $arguments) {
60
+		return call_user_func_array([$this->statement, $name], $arguments);
61 61
 	}
62 62
 
63 63
 	/**
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 	 * @param array $input
67 67
 	 * @return \OC_DB_StatementWrapper|int|bool
68 68
 	 */
69
-	public function execute($input= []) {
69
+	public function execute($input = []) {
70 70
 		$this->lastArguments = $input;
71 71
 		if (count($input) > 0) {
72 72
 			$result = $this->statement->execute($input);
Please login to merge, or discard this patch.
lib/private/legacy/OC_Util.php 2 patches
Indentation   +1392 added lines, -1392 removed lines patch added patch discarded remove patch
@@ -69,1402 +69,1402 @@
 block discarded – undo
69 69
 use OCP\IUser;
70 70
 
71 71
 class OC_Util {
72
-	public static $scripts = [];
73
-	public static $styles = [];
74
-	public static $headers = [];
75
-	private static $rootMounted = false;
76
-	private static $fsSetup = false;
77
-
78
-	/** @var array Local cache of version.php */
79
-	private static $versionCache = null;
80
-
81
-	protected static function getAppManager() {
82
-		return \OC::$server->getAppManager();
83
-	}
84
-
85
-	private static function initLocalStorageRootFS() {
86
-		// mount local file backend as root
87
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
88
-		//first set up the local "root" storage
89
-		\OC\Files\Filesystem::initMountManager();
90
-		if (!self::$rootMounted) {
91
-			\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', ['datadir' => $configDataDirectory], '/');
92
-			self::$rootMounted = true;
93
-		}
94
-	}
95
-
96
-	/**
97
-	 * mounting an object storage as the root fs will in essence remove the
98
-	 * necessity of a data folder being present.
99
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
100
-	 *
101
-	 * @param array $config containing 'class' and optional 'arguments'
102
-	 * @suppress PhanDeprecatedFunction
103
-	 */
104
-	private static function initObjectStoreRootFS($config) {
105
-		// check misconfiguration
106
-		if (empty($config['class'])) {
107
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
108
-		}
109
-		if (!isset($config['arguments'])) {
110
-			$config['arguments'] = [];
111
-		}
112
-
113
-		// instantiate object store implementation
114
-		$name = $config['class'];
115
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
116
-			$segments = explode('\\', $name);
117
-			OC_App::loadApp(strtolower($segments[1]));
118
-		}
119
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
120
-		// mount with plain / root object store implementation
121
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
122
-
123
-		// mount object storage as root
124
-		\OC\Files\Filesystem::initMountManager();
125
-		if (!self::$rootMounted) {
126
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
127
-			self::$rootMounted = true;
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * mounting an object storage as the root fs will in essence remove the
133
-	 * necessity of a data folder being present.
134
-	 *
135
-	 * @param array $config containing 'class' and optional 'arguments'
136
-	 * @suppress PhanDeprecatedFunction
137
-	 */
138
-	private static function initObjectStoreMultibucketRootFS($config) {
139
-		// check misconfiguration
140
-		if (empty($config['class'])) {
141
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
142
-		}
143
-		if (!isset($config['arguments'])) {
144
-			$config['arguments'] = [];
145
-		}
146
-
147
-		// instantiate object store implementation
148
-		$name = $config['class'];
149
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
150
-			$segments = explode('\\', $name);
151
-			OC_App::loadApp(strtolower($segments[1]));
152
-		}
153
-
154
-		if (!isset($config['arguments']['bucket'])) {
155
-			$config['arguments']['bucket'] = '';
156
-		}
157
-		// put the root FS always in first bucket for multibucket configuration
158
-		$config['arguments']['bucket'] .= '0';
159
-
160
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
161
-		// mount with plain / root object store implementation
162
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
163
-
164
-		// mount object storage as root
165
-		\OC\Files\Filesystem::initMountManager();
166
-		if (!self::$rootMounted) {
167
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
168
-			self::$rootMounted = true;
169
-		}
170
-	}
171
-
172
-	/**
173
-	 * Can be set up
174
-	 *
175
-	 * @param string $user
176
-	 * @return boolean
177
-	 * @description configure the initial filesystem based on the configuration
178
-	 * @suppress PhanDeprecatedFunction
179
-	 * @suppress PhanAccessMethodInternal
180
-	 */
181
-	public static function setupFS($user = '') {
182
-		//setting up the filesystem twice can only lead to trouble
183
-		if (self::$fsSetup) {
184
-			return false;
185
-		}
186
-
187
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
188
-
189
-		// If we are not forced to load a specific user we load the one that is logged in
190
-		if ($user === null) {
191
-			$user = '';
192
-		} else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
193
-			$user = OC_User::getUser();
194
-		}
195
-
196
-		// load all filesystem apps before, so no setup-hook gets lost
197
-		OC_App::loadApps(['filesystem']);
198
-
199
-		// the filesystem will finish when $user is not empty,
200
-		// mark fs setup here to avoid doing the setup from loading
201
-		// OC_Filesystem
202
-		if ($user != '') {
203
-			self::$fsSetup = true;
204
-		}
205
-
206
-		\OC\Files\Filesystem::initMountManager();
207
-
208
-		$prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
209
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
210
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
211
-				/** @var \OC\Files\Storage\Common $storage */
212
-				$storage->setMountOptions($mount->getOptions());
213
-			}
214
-			return $storage;
215
-		});
216
-
217
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
218
-			if (!$mount->getOption('enable_sharing', true)) {
219
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
220
-					'storage' => $storage,
221
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
222
-				]);
223
-			}
224
-			return $storage;
225
-		});
226
-
227
-		// install storage availability wrapper, before most other wrappers
228
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
229
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
230
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
231
-			}
232
-			return $storage;
233
-		});
234
-
235
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
236
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
237
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
238
-			}
239
-			return $storage;
240
-		});
241
-
242
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
243
-			// set up quota for home storages, even for other users
244
-			// which can happen when using sharing
245
-
246
-			/**
247
-			 * @var \OC\Files\Storage\Storage $storage
248
-			 */
249
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
250
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
251
-			) {
252
-				/** @var \OC\Files\Storage\Home $storage */
253
-				if (is_object($storage->getUser())) {
254
-					$quota = OC_Util::getUserQuota($storage->getUser());
255
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
256
-						return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
257
-					}
258
-				}
259
-			}
260
-
261
-			return $storage;
262
-		});
263
-
264
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
265
-			/*
72
+    public static $scripts = [];
73
+    public static $styles = [];
74
+    public static $headers = [];
75
+    private static $rootMounted = false;
76
+    private static $fsSetup = false;
77
+
78
+    /** @var array Local cache of version.php */
79
+    private static $versionCache = null;
80
+
81
+    protected static function getAppManager() {
82
+        return \OC::$server->getAppManager();
83
+    }
84
+
85
+    private static function initLocalStorageRootFS() {
86
+        // mount local file backend as root
87
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
88
+        //first set up the local "root" storage
89
+        \OC\Files\Filesystem::initMountManager();
90
+        if (!self::$rootMounted) {
91
+            \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', ['datadir' => $configDataDirectory], '/');
92
+            self::$rootMounted = true;
93
+        }
94
+    }
95
+
96
+    /**
97
+     * mounting an object storage as the root fs will in essence remove the
98
+     * necessity of a data folder being present.
99
+     * TODO make home storage aware of this and use the object storage instead of local disk access
100
+     *
101
+     * @param array $config containing 'class' and optional 'arguments'
102
+     * @suppress PhanDeprecatedFunction
103
+     */
104
+    private static function initObjectStoreRootFS($config) {
105
+        // check misconfiguration
106
+        if (empty($config['class'])) {
107
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
108
+        }
109
+        if (!isset($config['arguments'])) {
110
+            $config['arguments'] = [];
111
+        }
112
+
113
+        // instantiate object store implementation
114
+        $name = $config['class'];
115
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
116
+            $segments = explode('\\', $name);
117
+            OC_App::loadApp(strtolower($segments[1]));
118
+        }
119
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
120
+        // mount with plain / root object store implementation
121
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
122
+
123
+        // mount object storage as root
124
+        \OC\Files\Filesystem::initMountManager();
125
+        if (!self::$rootMounted) {
126
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
127
+            self::$rootMounted = true;
128
+        }
129
+    }
130
+
131
+    /**
132
+     * mounting an object storage as the root fs will in essence remove the
133
+     * necessity of a data folder being present.
134
+     *
135
+     * @param array $config containing 'class' and optional 'arguments'
136
+     * @suppress PhanDeprecatedFunction
137
+     */
138
+    private static function initObjectStoreMultibucketRootFS($config) {
139
+        // check misconfiguration
140
+        if (empty($config['class'])) {
141
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
142
+        }
143
+        if (!isset($config['arguments'])) {
144
+            $config['arguments'] = [];
145
+        }
146
+
147
+        // instantiate object store implementation
148
+        $name = $config['class'];
149
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
150
+            $segments = explode('\\', $name);
151
+            OC_App::loadApp(strtolower($segments[1]));
152
+        }
153
+
154
+        if (!isset($config['arguments']['bucket'])) {
155
+            $config['arguments']['bucket'] = '';
156
+        }
157
+        // put the root FS always in first bucket for multibucket configuration
158
+        $config['arguments']['bucket'] .= '0';
159
+
160
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
161
+        // mount with plain / root object store implementation
162
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
163
+
164
+        // mount object storage as root
165
+        \OC\Files\Filesystem::initMountManager();
166
+        if (!self::$rootMounted) {
167
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
168
+            self::$rootMounted = true;
169
+        }
170
+    }
171
+
172
+    /**
173
+     * Can be set up
174
+     *
175
+     * @param string $user
176
+     * @return boolean
177
+     * @description configure the initial filesystem based on the configuration
178
+     * @suppress PhanDeprecatedFunction
179
+     * @suppress PhanAccessMethodInternal
180
+     */
181
+    public static function setupFS($user = '') {
182
+        //setting up the filesystem twice can only lead to trouble
183
+        if (self::$fsSetup) {
184
+            return false;
185
+        }
186
+
187
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
188
+
189
+        // If we are not forced to load a specific user we load the one that is logged in
190
+        if ($user === null) {
191
+            $user = '';
192
+        } else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
193
+            $user = OC_User::getUser();
194
+        }
195
+
196
+        // load all filesystem apps before, so no setup-hook gets lost
197
+        OC_App::loadApps(['filesystem']);
198
+
199
+        // the filesystem will finish when $user is not empty,
200
+        // mark fs setup here to avoid doing the setup from loading
201
+        // OC_Filesystem
202
+        if ($user != '') {
203
+            self::$fsSetup = true;
204
+        }
205
+
206
+        \OC\Files\Filesystem::initMountManager();
207
+
208
+        $prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
209
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
210
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
211
+                /** @var \OC\Files\Storage\Common $storage */
212
+                $storage->setMountOptions($mount->getOptions());
213
+            }
214
+            return $storage;
215
+        });
216
+
217
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
218
+            if (!$mount->getOption('enable_sharing', true)) {
219
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
220
+                    'storage' => $storage,
221
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
222
+                ]);
223
+            }
224
+            return $storage;
225
+        });
226
+
227
+        // install storage availability wrapper, before most other wrappers
228
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
229
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
230
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
231
+            }
232
+            return $storage;
233
+        });
234
+
235
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
236
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
237
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
238
+            }
239
+            return $storage;
240
+        });
241
+
242
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
243
+            // set up quota for home storages, even for other users
244
+            // which can happen when using sharing
245
+
246
+            /**
247
+             * @var \OC\Files\Storage\Storage $storage
248
+             */
249
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
250
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
251
+            ) {
252
+                /** @var \OC\Files\Storage\Home $storage */
253
+                if (is_object($storage->getUser())) {
254
+                    $quota = OC_Util::getUserQuota($storage->getUser());
255
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
256
+                        return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
257
+                    }
258
+                }
259
+            }
260
+
261
+            return $storage;
262
+        });
263
+
264
+        \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
265
+            /*
266 266
 			 * Do not allow any operations that modify the storage
267 267
 			 */
268
-			if ($mount->getOption('readonly', false)) {
269
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
270
-					'storage' => $storage,
271
-					'mask' => \OCP\Constants::PERMISSION_ALL & ~(
272
-						\OCP\Constants::PERMISSION_UPDATE |
273
-						\OCP\Constants::PERMISSION_CREATE |
274
-						\OCP\Constants::PERMISSION_DELETE
275
-					),
276
-				]);
277
-			}
278
-			return $storage;
279
-		});
280
-
281
-		OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
282
-
283
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
284
-
285
-		//check if we are using an object storage
286
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
287
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
288
-
289
-		// use the same order as in ObjectHomeMountProvider
290
-		if (isset($objectStoreMultibucket)) {
291
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
292
-		} elseif (isset($objectStore)) {
293
-			self::initObjectStoreRootFS($objectStore);
294
-		} else {
295
-			self::initLocalStorageRootFS();
296
-		}
297
-
298
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
299
-			\OC::$server->getEventLogger()->end('setup_fs');
300
-			return false;
301
-		}
302
-
303
-		//if we aren't logged in, there is no use to set up the filesystem
304
-		if ($user != "") {
305
-
306
-			$userDir = '/' . $user . '/files';
307
-
308
-			//jail the user into his "home" directory
309
-			\OC\Files\Filesystem::init($user, $userDir);
310
-
311
-			OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
312
-		}
313
-		\OC::$server->getEventLogger()->end('setup_fs');
314
-		return true;
315
-	}
316
-
317
-	/**
318
-	 * check if a password is required for each public link
319
-	 *
320
-	 * @return boolean
321
-	 * @suppress PhanDeprecatedFunction
322
-	 */
323
-	public static function isPublicLinkPasswordRequired() {
324
-		$enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
325
-		return $enforcePassword === 'yes';
326
-	}
327
-
328
-	/**
329
-	 * check if sharing is disabled for the current user
330
-	 * @param IConfig $config
331
-	 * @param IGroupManager $groupManager
332
-	 * @param IUser|null $user
333
-	 * @return bool
334
-	 */
335
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
336
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
337
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
338
-			$excludedGroups = json_decode($groupsList);
339
-			if (is_null($excludedGroups)) {
340
-				$excludedGroups = explode(',', $groupsList);
341
-				$newValue = json_encode($excludedGroups);
342
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
343
-			}
344
-			$usersGroups = $groupManager->getUserGroupIds($user);
345
-			if (!empty($usersGroups)) {
346
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
347
-				// if the user is only in groups which are disabled for sharing then
348
-				// sharing is also disabled for the user
349
-				if (empty($remainingGroups)) {
350
-					return true;
351
-				}
352
-			}
353
-		}
354
-		return false;
355
-	}
356
-
357
-	/**
358
-	 * check if share API enforces a default expire date
359
-	 *
360
-	 * @return boolean
361
-	 * @suppress PhanDeprecatedFunction
362
-	 */
363
-	public static function isDefaultExpireDateEnforced() {
364
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
365
-		$enforceDefaultExpireDate = false;
366
-		if ($isDefaultExpireDateEnabled === 'yes') {
367
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
368
-			$enforceDefaultExpireDate = $value === 'yes';
369
-		}
370
-
371
-		return $enforceDefaultExpireDate;
372
-	}
373
-
374
-	/**
375
-	 * Get the quota of a user
376
-	 *
377
-	 * @param IUser|null $user
378
-	 * @return float Quota bytes
379
-	 */
380
-	public static function getUserQuota(?IUser $user) {
381
-		if (is_null($user)) {
382
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
383
-		}
384
-		$userQuota = $user->getQuota();
385
-		if($userQuota === 'none') {
386
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
387
-		}
388
-		return OC_Helper::computerFileSize($userQuota);
389
-	}
390
-
391
-	/**
392
-	 * copies the skeleton to the users /files
393
-	 *
394
-	 * @param string $userId
395
-	 * @param \OCP\Files\Folder $userDirectory
396
-	 * @throws \OCP\Files\NotFoundException
397
-	 * @throws \OCP\Files\NotPermittedException
398
-	 * @suppress PhanDeprecatedFunction
399
-	 */
400
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
401
-
402
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
403
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
404
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
405
-
406
-		if (!file_exists($skeletonDirectory)) {
407
-			$dialectStart = strpos($userLang, '_');
408
-			if ($dialectStart !== false) {
409
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
410
-			}
411
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
412
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
413
-			}
414
-			if (!file_exists($skeletonDirectory)) {
415
-				$skeletonDirectory = '';
416
-			}
417
-		}
418
-
419
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
420
-
421
-		if ($instanceId === null) {
422
-			throw new \RuntimeException('no instance id!');
423
-		}
424
-		$appdata = 'appdata_' . $instanceId;
425
-		if ($userId === $appdata) {
426
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
427
-		}
428
-
429
-		if (!empty($skeletonDirectory)) {
430
-			\OCP\Util::writeLog(
431
-				'files_skeleton',
432
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
433
-				ILogger::DEBUG
434
-			);
435
-			self::copyr($skeletonDirectory, $userDirectory);
436
-			// update the file cache
437
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
438
-		}
439
-	}
440
-
441
-	/**
442
-	 * copies a directory recursively by using streams
443
-	 *
444
-	 * @param string $source
445
-	 * @param \OCP\Files\Folder $target
446
-	 * @return void
447
-	 */
448
-	public static function copyr($source, \OCP\Files\Folder $target) {
449
-		$logger = \OC::$server->getLogger();
450
-
451
-		// Verify if folder exists
452
-		$dir = opendir($source);
453
-		if($dir === false) {
454
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
455
-			return;
456
-		}
457
-
458
-		// Copy the files
459
-		while (false !== ($file = readdir($dir))) {
460
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
461
-				if (is_dir($source . '/' . $file)) {
462
-					$child = $target->newFolder($file);
463
-					self::copyr($source . '/' . $file, $child);
464
-				} else {
465
-					$child = $target->newFile($file);
466
-					$sourceStream = fopen($source . '/' . $file, 'r');
467
-					if($sourceStream === false) {
468
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
469
-						closedir($dir);
470
-						return;
471
-					}
472
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
473
-				}
474
-			}
475
-		}
476
-		closedir($dir);
477
-	}
478
-
479
-	/**
480
-	 * @return void
481
-	 * @suppress PhanUndeclaredMethod
482
-	 */
483
-	public static function tearDownFS() {
484
-		\OC\Files\Filesystem::tearDown();
485
-		\OC::$server->getRootFolder()->clearCache();
486
-		self::$fsSetup = false;
487
-		self::$rootMounted = false;
488
-	}
489
-
490
-	/**
491
-	 * get the current installed version of ownCloud
492
-	 *
493
-	 * @return array
494
-	 */
495
-	public static function getVersion() {
496
-		OC_Util::loadVersion();
497
-		return self::$versionCache['OC_Version'];
498
-	}
499
-
500
-	/**
501
-	 * get the current installed version string of ownCloud
502
-	 *
503
-	 * @return string
504
-	 */
505
-	public static function getVersionString() {
506
-		OC_Util::loadVersion();
507
-		return self::$versionCache['OC_VersionString'];
508
-	}
509
-
510
-	/**
511
-	 * @deprecated the value is of no use anymore
512
-	 * @return string
513
-	 */
514
-	public static function getEditionString() {
515
-		return '';
516
-	}
517
-
518
-	/**
519
-	 * @description get the update channel of the current installed of ownCloud.
520
-	 * @return string
521
-	 */
522
-	public static function getChannel() {
523
-		OC_Util::loadVersion();
524
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
525
-	}
526
-
527
-	/**
528
-	 * @description get the build number of the current installed of ownCloud.
529
-	 * @return string
530
-	 */
531
-	public static function getBuild() {
532
-		OC_Util::loadVersion();
533
-		return self::$versionCache['OC_Build'];
534
-	}
535
-
536
-	/**
537
-	 * @description load the version.php into the session as cache
538
-	 * @suppress PhanUndeclaredVariable
539
-	 */
540
-	private static function loadVersion() {
541
-		if (self::$versionCache !== null) {
542
-			return;
543
-		}
544
-
545
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
546
-		require OC::$SERVERROOT . '/version.php';
547
-		/** @var $timestamp int */
548
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
549
-		/** @var $OC_Version string */
550
-		self::$versionCache['OC_Version'] = $OC_Version;
551
-		/** @var $OC_VersionString string */
552
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
553
-		/** @var $OC_Build string */
554
-		self::$versionCache['OC_Build'] = $OC_Build;
555
-
556
-		/** @var $OC_Channel string */
557
-		self::$versionCache['OC_Channel'] = $OC_Channel;
558
-	}
559
-
560
-	/**
561
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
562
-	 *
563
-	 * @param string $application application to get the files from
564
-	 * @param string $directory directory within this application (css, js, vendor, etc)
565
-	 * @param string $file the file inside of the above folder
566
-	 * @return string the path
567
-	 */
568
-	private static function generatePath($application, $directory, $file) {
569
-		if (is_null($file)) {
570
-			$file = $application;
571
-			$application = "";
572
-		}
573
-		if (!empty($application)) {
574
-			return "$application/$directory/$file";
575
-		} else {
576
-			return "$directory/$file";
577
-		}
578
-	}
579
-
580
-	/**
581
-	 * add a javascript file
582
-	 *
583
-	 * @param string $application application id
584
-	 * @param string|null $file filename
585
-	 * @param bool $prepend prepend the Script to the beginning of the list
586
-	 * @return void
587
-	 */
588
-	public static function addScript($application, $file = null, $prepend = false) {
589
-		$path = OC_Util::generatePath($application, 'js', $file);
590
-
591
-		// core js files need separate handling
592
-		if ($application !== 'core' && $file !== null) {
593
-			self::addTranslations ( $application );
594
-		}
595
-		self::addExternalResource($application, $prepend, $path, "script");
596
-	}
597
-
598
-	/**
599
-	 * add a javascript file from the vendor sub folder
600
-	 *
601
-	 * @param string $application application id
602
-	 * @param string|null $file filename
603
-	 * @param bool $prepend prepend the Script to the beginning of the list
604
-	 * @return void
605
-	 */
606
-	public static function addVendorScript($application, $file = null, $prepend = false) {
607
-		$path = OC_Util::generatePath($application, 'vendor', $file);
608
-		self::addExternalResource($application, $prepend, $path, "script");
609
-	}
610
-
611
-	/**
612
-	 * add a translation JS file
613
-	 *
614
-	 * @param string $application application id
615
-	 * @param string|null $languageCode language code, defaults to the current language
616
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
617
-	 */
618
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
619
-		if (is_null($languageCode)) {
620
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
621
-		}
622
-		if (!empty($application)) {
623
-			$path = "$application/l10n/$languageCode";
624
-		} else {
625
-			$path = "l10n/$languageCode";
626
-		}
627
-		self::addExternalResource($application, $prepend, $path, "script");
628
-	}
629
-
630
-	/**
631
-	 * add a css file
632
-	 *
633
-	 * @param string $application application id
634
-	 * @param string|null $file filename
635
-	 * @param bool $prepend prepend the Style to the beginning of the list
636
-	 * @return void
637
-	 */
638
-	public static function addStyle($application, $file = null, $prepend = false) {
639
-		$path = OC_Util::generatePath($application, 'css', $file);
640
-		self::addExternalResource($application, $prepend, $path, "style");
641
-	}
642
-
643
-	/**
644
-	 * add a css file from the vendor sub folder
645
-	 *
646
-	 * @param string $application application id
647
-	 * @param string|null $file filename
648
-	 * @param bool $prepend prepend the Style to the beginning of the list
649
-	 * @return void
650
-	 */
651
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
652
-		$path = OC_Util::generatePath($application, 'vendor', $file);
653
-		self::addExternalResource($application, $prepend, $path, "style");
654
-	}
655
-
656
-	/**
657
-	 * add an external resource css/js file
658
-	 *
659
-	 * @param string $application application id
660
-	 * @param bool $prepend prepend the file to the beginning of the list
661
-	 * @param string $path
662
-	 * @param string $type (script or style)
663
-	 * @return void
664
-	 */
665
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
666
-
667
-		if ($type === "style") {
668
-			if (!in_array($path, self::$styles)) {
669
-				if ($prepend === true) {
670
-					array_unshift ( self::$styles, $path );
671
-				} else {
672
-					self::$styles[] = $path;
673
-				}
674
-			}
675
-		} elseif ($type === "script") {
676
-			if (!in_array($path, self::$scripts)) {
677
-				if ($prepend === true) {
678
-					array_unshift ( self::$scripts, $path );
679
-				} else {
680
-					self::$scripts [] = $path;
681
-				}
682
-			}
683
-		}
684
-	}
685
-
686
-	/**
687
-	 * Add a custom element to the header
688
-	 * If $text is null then the element will be written as empty element.
689
-	 * So use "" to get a closing tag.
690
-	 * @param string $tag tag name of the element
691
-	 * @param array $attributes array of attributes for the element
692
-	 * @param string $text the text content for the element
693
-	 * @param bool $prepend prepend the header to the beginning of the list
694
-	 */
695
-	public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
696
-		$header = [
697
-			'tag' => $tag,
698
-			'attributes' => $attributes,
699
-			'text' => $text
700
-		];
701
-		if ($prepend === true) {
702
-			array_unshift (self::$headers, $header);
703
-
704
-		} else {
705
-			self::$headers[] = $header;
706
-		}
707
-	}
708
-
709
-	/**
710
-	 * check if the current server configuration is suitable for ownCloud
711
-	 *
712
-	 * @param \OC\SystemConfig $config
713
-	 * @return array arrays with error messages and hints
714
-	 */
715
-	public static function checkServer(\OC\SystemConfig $config) {
716
-		$l = \OC::$server->getL10N('lib');
717
-		$errors = [];
718
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
719
-
720
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
721
-			// this check needs to be done every time
722
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
723
-		}
724
-
725
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
726
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
727
-			return $errors;
728
-		}
729
-
730
-		$webServerRestart = false;
731
-		$setup = new \OC\Setup(
732
-			$config,
733
-			\OC::$server->getIniWrapper(),
734
-			\OC::$server->getL10N('lib'),
735
-			\OC::$server->query(\OCP\Defaults::class),
736
-			\OC::$server->getLogger(),
737
-			\OC::$server->getSecureRandom(),
738
-			\OC::$server->query(\OC\Installer::class)
739
-		);
740
-
741
-		$urlGenerator = \OC::$server->getURLGenerator();
742
-
743
-		$availableDatabases = $setup->getSupportedDatabases();
744
-		if (empty($availableDatabases)) {
745
-			$errors[] = [
746
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
747
-				'hint' => '' //TODO: sane hint
748
-			];
749
-			$webServerRestart = true;
750
-		}
751
-
752
-		// Check if config folder is writable.
753
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
754
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
755
-				$errors[] = [
756
-					'error' => $l->t('Cannot write into "config" directory'),
757
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
758
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
759
-						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
760
-						[ $urlGenerator->linkToDocs('admin-config') ] )
761
-				];
762
-			}
763
-		}
764
-
765
-		// Check if there is a writable install folder.
766
-		if ($config->getValue('appstoreenabled', true)) {
767
-			if (OC_App::getInstallPath() === null
768
-				|| !is_writable(OC_App::getInstallPath())
769
-				|| !is_readable(OC_App::getInstallPath())
770
-			) {
771
-				$errors[] = [
772
-					'error' => $l->t('Cannot write into "apps" directory'),
773
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
774
-						. ' or disabling the appstore in the config file.')
775
-				];
776
-			}
777
-		}
778
-		// Create root dir.
779
-		if ($config->getValue('installed', false)) {
780
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
781
-				$success = @mkdir($CONFIG_DATADIRECTORY);
782
-				if ($success) {
783
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
784
-				} else {
785
-					$errors[] = [
786
-						'error' => $l->t('Cannot create "data" directory'),
787
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
788
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
789
-					];
790
-				}
791
-			} else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
792
-				// is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
793
-				$testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
794
-				$handle = fopen($testFile, 'w');
795
-				if (!$handle || fwrite($handle, 'Test write operation') === false) {
796
-					$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
797
-						[$urlGenerator->linkToDocs('admin-dir_permissions')]);
798
-					$errors[] = [
799
-						'error' => 'Your data directory is not writable',
800
-						'hint' => $permissionsHint
801
-					];
802
-				} else {
803
-					fclose($handle);
804
-					unlink($testFile);
805
-				}
806
-			} else {
807
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
808
-			}
809
-		}
810
-
811
-		if (!OC_Util::isSetLocaleWorking()) {
812
-			$errors[] = [
813
-				'error' => $l->t('Setting locale to %s failed',
814
-					['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
815
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
816
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
817
-			];
818
-		}
819
-
820
-		// Contains the dependencies that should be checked against
821
-		// classes = class_exists
822
-		// functions = function_exists
823
-		// defined = defined
824
-		// ini = ini_get
825
-		// If the dependency is not found the missing module name is shown to the EndUser
826
-		// When adding new checks always verify that they pass on Travis as well
827
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
828
-		$dependencies = [
829
-			'classes' => [
830
-				'ZipArchive' => 'zip',
831
-				'DOMDocument' => 'dom',
832
-				'XMLWriter' => 'XMLWriter',
833
-				'XMLReader' => 'XMLReader',
834
-			],
835
-			'functions' => [
836
-				'xml_parser_create' => 'libxml',
837
-				'mb_strcut' => 'mbstring',
838
-				'ctype_digit' => 'ctype',
839
-				'json_encode' => 'JSON',
840
-				'gd_info' => 'GD',
841
-				'gzencode' => 'zlib',
842
-				'iconv' => 'iconv',
843
-				'simplexml_load_string' => 'SimpleXML',
844
-				'hash' => 'HASH Message Digest Framework',
845
-				'curl_init' => 'cURL',
846
-				'openssl_verify' => 'OpenSSL',
847
-			],
848
-			'defined' => [
849
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
850
-			],
851
-			'ini' => [
852
-				'default_charset' => 'UTF-8',
853
-			],
854
-		];
855
-		$missingDependencies = [];
856
-		$invalidIniSettings = [];
857
-		$moduleHint = $l->t('Please ask your server administrator to install the module.');
858
-
859
-		$iniWrapper = \OC::$server->getIniWrapper();
860
-		foreach ($dependencies['classes'] as $class => $module) {
861
-			if (!class_exists($class)) {
862
-				$missingDependencies[] = $module;
863
-			}
864
-		}
865
-		foreach ($dependencies['functions'] as $function => $module) {
866
-			if (!function_exists($function)) {
867
-				$missingDependencies[] = $module;
868
-			}
869
-		}
870
-		foreach ($dependencies['defined'] as $defined => $module) {
871
-			if (!defined($defined)) {
872
-				$missingDependencies[] = $module;
873
-			}
874
-		}
875
-		foreach ($dependencies['ini'] as $setting => $expected) {
876
-			if (is_bool($expected)) {
877
-				if ($iniWrapper->getBool($setting) !== $expected) {
878
-					$invalidIniSettings[] = [$setting, $expected];
879
-				}
880
-			}
881
-			if (is_int($expected)) {
882
-				if ($iniWrapper->getNumeric($setting) !== $expected) {
883
-					$invalidIniSettings[] = [$setting, $expected];
884
-				}
885
-			}
886
-			if (is_string($expected)) {
887
-				if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
888
-					$invalidIniSettings[] = [$setting, $expected];
889
-				}
890
-			}
891
-		}
892
-
893
-		foreach($missingDependencies as $missingDependency) {
894
-			$errors[] = [
895
-				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
896
-				'hint' => $moduleHint
897
-			];
898
-			$webServerRestart = true;
899
-		}
900
-		foreach($invalidIniSettings as $setting) {
901
-			if(is_bool($setting[1])) {
902
-				$setting[1] = $setting[1] ? 'on' : 'off';
903
-			}
904
-			$errors[] = [
905
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
906
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
907
-			];
908
-			$webServerRestart = true;
909
-		}
910
-
911
-		/**
912
-		 * The mbstring.func_overload check can only be performed if the mbstring
913
-		 * module is installed as it will return null if the checking setting is
914
-		 * not available and thus a check on the boolean value fails.
915
-		 *
916
-		 * TODO: Should probably be implemented in the above generic dependency
917
-		 *       check somehow in the long-term.
918
-		 */
919
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
920
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
921
-			$errors[] = [
922
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
923
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
924
-			];
925
-		}
926
-
927
-		if(function_exists('xml_parser_create') &&
928
-			LIBXML_LOADED_VERSION < 20700 ) {
929
-			$version = LIBXML_LOADED_VERSION;
930
-			$major = floor($version/10000);
931
-			$version -= ($major * 10000);
932
-			$minor = floor($version/100);
933
-			$version -= ($minor * 100);
934
-			$patch = $version;
935
-			$errors[] = [
936
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
937
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
938
-			];
939
-		}
940
-
941
-		if (!self::isAnnotationsWorking()) {
942
-			$errors[] = [
943
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
944
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
945
-			];
946
-		}
947
-
948
-		if (!\OC::$CLI && $webServerRestart) {
949
-			$errors[] = [
950
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
951
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
952
-			];
953
-		}
954
-
955
-		$errors = array_merge($errors, self::checkDatabaseVersion());
956
-
957
-		// Cache the result of this function
958
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
959
-
960
-		return $errors;
961
-	}
962
-
963
-	/**
964
-	 * Check the database version
965
-	 *
966
-	 * @return array errors array
967
-	 */
968
-	public static function checkDatabaseVersion() {
969
-		$l = \OC::$server->getL10N('lib');
970
-		$errors = [];
971
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
972
-		if ($dbType === 'pgsql') {
973
-			// check PostgreSQL version
974
-			try {
975
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
976
-				$data = $result->fetchRow();
977
-				if (isset($data['server_version'])) {
978
-					$version = $data['server_version'];
979
-					if (version_compare($version, '9.0.0', '<')) {
980
-						$errors[] = [
981
-							'error' => $l->t('PostgreSQL >= 9 required'),
982
-							'hint' => $l->t('Please upgrade your database version')
983
-						];
984
-					}
985
-				}
986
-			} catch (\Doctrine\DBAL\DBALException $e) {
987
-				$logger = \OC::$server->getLogger();
988
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
989
-				$logger->logException($e);
990
-			}
991
-		}
992
-		return $errors;
993
-	}
994
-
995
-	/**
996
-	 * Check for correct file permissions of data directory
997
-	 *
998
-	 * @param string $dataDirectory
999
-	 * @return array arrays with error messages and hints
1000
-	 */
1001
-	public static function checkDataDirectoryPermissions($dataDirectory) {
1002
-		if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1003
-			return  [];
1004
-		}
1005
-		$l = \OC::$server->getL10N('lib');
1006
-		$errors = [];
1007
-		$permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
1008
-			. ' cannot be listed by other users.');
1009
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1010
-		if (substr($perms, -1) !== '0') {
1011
-			chmod($dataDirectory, 0770);
1012
-			clearstatcache();
1013
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1014
-			if ($perms[2] !== '0') {
1015
-				$errors[] = [
1016
-					'error' => $l->t('Your data directory is readable by other users'),
1017
-					'hint' => $permissionsModHint
1018
-				];
1019
-			}
1020
-		}
1021
-		return $errors;
1022
-	}
1023
-
1024
-	/**
1025
-	 * Check that the data directory exists and is valid by
1026
-	 * checking the existence of the ".ocdata" file.
1027
-	 *
1028
-	 * @param string $dataDirectory data directory path
1029
-	 * @return array errors found
1030
-	 */
1031
-	public static function checkDataDirectoryValidity($dataDirectory) {
1032
-		$l = \OC::$server->getL10N('lib');
1033
-		$errors = [];
1034
-		if ($dataDirectory[0] !== '/') {
1035
-			$errors[] = [
1036
-				'error' => $l->t('Your data directory must be an absolute path'),
1037
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1038
-			];
1039
-		}
1040
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1041
-			$errors[] = [
1042
-				'error' => $l->t('Your data directory is invalid'),
1043
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1044
-					' in the root of the data directory.')
1045
-			];
1046
-		}
1047
-		return $errors;
1048
-	}
1049
-
1050
-	/**
1051
-	 * Check if the user is logged in, redirects to home if not. With
1052
-	 * redirect URL parameter to the request URI.
1053
-	 *
1054
-	 * @return void
1055
-	 */
1056
-	public static function checkLoggedIn() {
1057
-		// Check if we are a user
1058
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1059
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1060
-						'core.login.showLoginForm',
1061
-						[
1062
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1063
-						]
1064
-					)
1065
-			);
1066
-			exit();
1067
-		}
1068
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1069
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1070
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1071
-			exit();
1072
-		}
1073
-	}
1074
-
1075
-	/**
1076
-	 * Check if the user is a admin, redirects to home if not
1077
-	 *
1078
-	 * @return void
1079
-	 */
1080
-	public static function checkAdminUser() {
1081
-		OC_Util::checkLoggedIn();
1082
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1083
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1084
-			exit();
1085
-		}
1086
-	}
1087
-
1088
-	/**
1089
-	 * Returns the URL of the default page
1090
-	 * based on the system configuration and
1091
-	 * the apps visible for the current user
1092
-	 *
1093
-	 * @return string URL
1094
-	 * @suppress PhanDeprecatedFunction
1095
-	 */
1096
-	public static function getDefaultPageUrl() {
1097
-		$urlGenerator = \OC::$server->getURLGenerator();
1098
-		// Deny the redirect if the URL contains a @
1099
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1100
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1101
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1102
-		} else {
1103
-			$defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1104
-			if ($defaultPage) {
1105
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1106
-			} else {
1107
-				$appId = 'files';
1108
-				$config = \OC::$server->getConfig();
1109
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1110
-				// find the first app that is enabled for the current user
1111
-				foreach ($defaultApps as $defaultApp) {
1112
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1113
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1114
-						$appId = $defaultApp;
1115
-						break;
1116
-					}
1117
-				}
1118
-
1119
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1120
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1121
-				} else {
1122
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1123
-				}
1124
-			}
1125
-		}
1126
-		return $location;
1127
-	}
1128
-
1129
-	/**
1130
-	 * Redirect to the user default page
1131
-	 *
1132
-	 * @return void
1133
-	 */
1134
-	public static function redirectToDefaultPage() {
1135
-		$location = self::getDefaultPageUrl();
1136
-		header('Location: ' . $location);
1137
-		exit();
1138
-	}
1139
-
1140
-	/**
1141
-	 * get an id unique for this instance
1142
-	 *
1143
-	 * @return string
1144
-	 */
1145
-	public static function getInstanceId() {
1146
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1147
-		if (is_null($id)) {
1148
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1149
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1150
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1151
-		}
1152
-		return $id;
1153
-	}
1154
-
1155
-	/**
1156
-	 * Public function to sanitize HTML
1157
-	 *
1158
-	 * This function is used to sanitize HTML and should be applied on any
1159
-	 * string or array of strings before displaying it on a web page.
1160
-	 *
1161
-	 * @param string|array $value
1162
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1163
-	 */
1164
-	public static function sanitizeHTML($value) {
1165
-		if (is_array($value)) {
1166
-			$value = array_map(function ($value) {
1167
-				return self::sanitizeHTML($value);
1168
-			}, $value);
1169
-		} else {
1170
-			// Specify encoding for PHP<5.4
1171
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1172
-		}
1173
-		return $value;
1174
-	}
1175
-
1176
-	/**
1177
-	 * Public function to encode url parameters
1178
-	 *
1179
-	 * This function is used to encode path to file before output.
1180
-	 * Encoding is done according to RFC 3986 with one exception:
1181
-	 * Character '/' is preserved as is.
1182
-	 *
1183
-	 * @param string $component part of URI to encode
1184
-	 * @return string
1185
-	 */
1186
-	public static function encodePath($component) {
1187
-		$encoded = rawurlencode($component);
1188
-		$encoded = str_replace('%2F', '/', $encoded);
1189
-		return $encoded;
1190
-	}
1191
-
1192
-
1193
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1194
-		// php dev server does not support htaccess
1195
-		if (php_sapi_name() === 'cli-server') {
1196
-			return false;
1197
-		}
1198
-
1199
-		// testdata
1200
-		$fileName = '/htaccesstest.txt';
1201
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1202
-
1203
-		// creating a test file
1204
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1205
-
1206
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1207
-			return false;
1208
-		}
1209
-
1210
-		$fp = @fopen($testFile, 'w');
1211
-		if (!$fp) {
1212
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1213
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1214
-		}
1215
-		fwrite($fp, $testContent);
1216
-		fclose($fp);
1217
-
1218
-		return $testContent;
1219
-	}
1220
-
1221
-	/**
1222
-	 * Check if the .htaccess file is working
1223
-	 * @param \OCP\IConfig $config
1224
-	 * @return bool
1225
-	 * @throws Exception
1226
-	 * @throws \OC\HintException If the test file can't get written.
1227
-	 */
1228
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1229
-
1230
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1231
-			return true;
1232
-		}
1233
-
1234
-		$testContent = $this->createHtaccessTestFile($config);
1235
-		if ($testContent === false) {
1236
-			return false;
1237
-		}
1238
-
1239
-		$fileName = '/htaccesstest.txt';
1240
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1241
-
1242
-		// accessing the file via http
1243
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1244
-		try {
1245
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1246
-		} catch (\Exception $e) {
1247
-			$content = false;
1248
-		}
1249
-
1250
-		if (strpos($url, 'https:') === 0) {
1251
-			$url = 'http:' . substr($url, 6);
1252
-		} else {
1253
-			$url = 'https:' . substr($url, 5);
1254
-		}
1255
-
1256
-		try {
1257
-			$fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1258
-		} catch (\Exception $e) {
1259
-			$fallbackContent = false;
1260
-		}
1261
-
1262
-		// cleanup
1263
-		@unlink($testFile);
1264
-
1265
-		/*
268
+            if ($mount->getOption('readonly', false)) {
269
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
270
+                    'storage' => $storage,
271
+                    'mask' => \OCP\Constants::PERMISSION_ALL & ~(
272
+                        \OCP\Constants::PERMISSION_UPDATE |
273
+                        \OCP\Constants::PERMISSION_CREATE |
274
+                        \OCP\Constants::PERMISSION_DELETE
275
+                    ),
276
+                ]);
277
+            }
278
+            return $storage;
279
+        });
280
+
281
+        OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
282
+
283
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
284
+
285
+        //check if we are using an object storage
286
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
287
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
288
+
289
+        // use the same order as in ObjectHomeMountProvider
290
+        if (isset($objectStoreMultibucket)) {
291
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
292
+        } elseif (isset($objectStore)) {
293
+            self::initObjectStoreRootFS($objectStore);
294
+        } else {
295
+            self::initLocalStorageRootFS();
296
+        }
297
+
298
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
299
+            \OC::$server->getEventLogger()->end('setup_fs');
300
+            return false;
301
+        }
302
+
303
+        //if we aren't logged in, there is no use to set up the filesystem
304
+        if ($user != "") {
305
+
306
+            $userDir = '/' . $user . '/files';
307
+
308
+            //jail the user into his "home" directory
309
+            \OC\Files\Filesystem::init($user, $userDir);
310
+
311
+            OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
312
+        }
313
+        \OC::$server->getEventLogger()->end('setup_fs');
314
+        return true;
315
+    }
316
+
317
+    /**
318
+     * check if a password is required for each public link
319
+     *
320
+     * @return boolean
321
+     * @suppress PhanDeprecatedFunction
322
+     */
323
+    public static function isPublicLinkPasswordRequired() {
324
+        $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
325
+        return $enforcePassword === 'yes';
326
+    }
327
+
328
+    /**
329
+     * check if sharing is disabled for the current user
330
+     * @param IConfig $config
331
+     * @param IGroupManager $groupManager
332
+     * @param IUser|null $user
333
+     * @return bool
334
+     */
335
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
336
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
337
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
338
+            $excludedGroups = json_decode($groupsList);
339
+            if (is_null($excludedGroups)) {
340
+                $excludedGroups = explode(',', $groupsList);
341
+                $newValue = json_encode($excludedGroups);
342
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
343
+            }
344
+            $usersGroups = $groupManager->getUserGroupIds($user);
345
+            if (!empty($usersGroups)) {
346
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
347
+                // if the user is only in groups which are disabled for sharing then
348
+                // sharing is also disabled for the user
349
+                if (empty($remainingGroups)) {
350
+                    return true;
351
+                }
352
+            }
353
+        }
354
+        return false;
355
+    }
356
+
357
+    /**
358
+     * check if share API enforces a default expire date
359
+     *
360
+     * @return boolean
361
+     * @suppress PhanDeprecatedFunction
362
+     */
363
+    public static function isDefaultExpireDateEnforced() {
364
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
365
+        $enforceDefaultExpireDate = false;
366
+        if ($isDefaultExpireDateEnabled === 'yes') {
367
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
368
+            $enforceDefaultExpireDate = $value === 'yes';
369
+        }
370
+
371
+        return $enforceDefaultExpireDate;
372
+    }
373
+
374
+    /**
375
+     * Get the quota of a user
376
+     *
377
+     * @param IUser|null $user
378
+     * @return float Quota bytes
379
+     */
380
+    public static function getUserQuota(?IUser $user) {
381
+        if (is_null($user)) {
382
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
383
+        }
384
+        $userQuota = $user->getQuota();
385
+        if($userQuota === 'none') {
386
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
387
+        }
388
+        return OC_Helper::computerFileSize($userQuota);
389
+    }
390
+
391
+    /**
392
+     * copies the skeleton to the users /files
393
+     *
394
+     * @param string $userId
395
+     * @param \OCP\Files\Folder $userDirectory
396
+     * @throws \OCP\Files\NotFoundException
397
+     * @throws \OCP\Files\NotPermittedException
398
+     * @suppress PhanDeprecatedFunction
399
+     */
400
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
401
+
402
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
403
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
404
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
405
+
406
+        if (!file_exists($skeletonDirectory)) {
407
+            $dialectStart = strpos($userLang, '_');
408
+            if ($dialectStart !== false) {
409
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
410
+            }
411
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
412
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
413
+            }
414
+            if (!file_exists($skeletonDirectory)) {
415
+                $skeletonDirectory = '';
416
+            }
417
+        }
418
+
419
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
420
+
421
+        if ($instanceId === null) {
422
+            throw new \RuntimeException('no instance id!');
423
+        }
424
+        $appdata = 'appdata_' . $instanceId;
425
+        if ($userId === $appdata) {
426
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
427
+        }
428
+
429
+        if (!empty($skeletonDirectory)) {
430
+            \OCP\Util::writeLog(
431
+                'files_skeleton',
432
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
433
+                ILogger::DEBUG
434
+            );
435
+            self::copyr($skeletonDirectory, $userDirectory);
436
+            // update the file cache
437
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
438
+        }
439
+    }
440
+
441
+    /**
442
+     * copies a directory recursively by using streams
443
+     *
444
+     * @param string $source
445
+     * @param \OCP\Files\Folder $target
446
+     * @return void
447
+     */
448
+    public static function copyr($source, \OCP\Files\Folder $target) {
449
+        $logger = \OC::$server->getLogger();
450
+
451
+        // Verify if folder exists
452
+        $dir = opendir($source);
453
+        if($dir === false) {
454
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
455
+            return;
456
+        }
457
+
458
+        // Copy the files
459
+        while (false !== ($file = readdir($dir))) {
460
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
461
+                if (is_dir($source . '/' . $file)) {
462
+                    $child = $target->newFolder($file);
463
+                    self::copyr($source . '/' . $file, $child);
464
+                } else {
465
+                    $child = $target->newFile($file);
466
+                    $sourceStream = fopen($source . '/' . $file, 'r');
467
+                    if($sourceStream === false) {
468
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
469
+                        closedir($dir);
470
+                        return;
471
+                    }
472
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
473
+                }
474
+            }
475
+        }
476
+        closedir($dir);
477
+    }
478
+
479
+    /**
480
+     * @return void
481
+     * @suppress PhanUndeclaredMethod
482
+     */
483
+    public static function tearDownFS() {
484
+        \OC\Files\Filesystem::tearDown();
485
+        \OC::$server->getRootFolder()->clearCache();
486
+        self::$fsSetup = false;
487
+        self::$rootMounted = false;
488
+    }
489
+
490
+    /**
491
+     * get the current installed version of ownCloud
492
+     *
493
+     * @return array
494
+     */
495
+    public static function getVersion() {
496
+        OC_Util::loadVersion();
497
+        return self::$versionCache['OC_Version'];
498
+    }
499
+
500
+    /**
501
+     * get the current installed version string of ownCloud
502
+     *
503
+     * @return string
504
+     */
505
+    public static function getVersionString() {
506
+        OC_Util::loadVersion();
507
+        return self::$versionCache['OC_VersionString'];
508
+    }
509
+
510
+    /**
511
+     * @deprecated the value is of no use anymore
512
+     * @return string
513
+     */
514
+    public static function getEditionString() {
515
+        return '';
516
+    }
517
+
518
+    /**
519
+     * @description get the update channel of the current installed of ownCloud.
520
+     * @return string
521
+     */
522
+    public static function getChannel() {
523
+        OC_Util::loadVersion();
524
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
525
+    }
526
+
527
+    /**
528
+     * @description get the build number of the current installed of ownCloud.
529
+     * @return string
530
+     */
531
+    public static function getBuild() {
532
+        OC_Util::loadVersion();
533
+        return self::$versionCache['OC_Build'];
534
+    }
535
+
536
+    /**
537
+     * @description load the version.php into the session as cache
538
+     * @suppress PhanUndeclaredVariable
539
+     */
540
+    private static function loadVersion() {
541
+        if (self::$versionCache !== null) {
542
+            return;
543
+        }
544
+
545
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
546
+        require OC::$SERVERROOT . '/version.php';
547
+        /** @var $timestamp int */
548
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
549
+        /** @var $OC_Version string */
550
+        self::$versionCache['OC_Version'] = $OC_Version;
551
+        /** @var $OC_VersionString string */
552
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
553
+        /** @var $OC_Build string */
554
+        self::$versionCache['OC_Build'] = $OC_Build;
555
+
556
+        /** @var $OC_Channel string */
557
+        self::$versionCache['OC_Channel'] = $OC_Channel;
558
+    }
559
+
560
+    /**
561
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
562
+     *
563
+     * @param string $application application to get the files from
564
+     * @param string $directory directory within this application (css, js, vendor, etc)
565
+     * @param string $file the file inside of the above folder
566
+     * @return string the path
567
+     */
568
+    private static function generatePath($application, $directory, $file) {
569
+        if (is_null($file)) {
570
+            $file = $application;
571
+            $application = "";
572
+        }
573
+        if (!empty($application)) {
574
+            return "$application/$directory/$file";
575
+        } else {
576
+            return "$directory/$file";
577
+        }
578
+    }
579
+
580
+    /**
581
+     * add a javascript file
582
+     *
583
+     * @param string $application application id
584
+     * @param string|null $file filename
585
+     * @param bool $prepend prepend the Script to the beginning of the list
586
+     * @return void
587
+     */
588
+    public static function addScript($application, $file = null, $prepend = false) {
589
+        $path = OC_Util::generatePath($application, 'js', $file);
590
+
591
+        // core js files need separate handling
592
+        if ($application !== 'core' && $file !== null) {
593
+            self::addTranslations ( $application );
594
+        }
595
+        self::addExternalResource($application, $prepend, $path, "script");
596
+    }
597
+
598
+    /**
599
+     * add a javascript file from the vendor sub folder
600
+     *
601
+     * @param string $application application id
602
+     * @param string|null $file filename
603
+     * @param bool $prepend prepend the Script to the beginning of the list
604
+     * @return void
605
+     */
606
+    public static function addVendorScript($application, $file = null, $prepend = false) {
607
+        $path = OC_Util::generatePath($application, 'vendor', $file);
608
+        self::addExternalResource($application, $prepend, $path, "script");
609
+    }
610
+
611
+    /**
612
+     * add a translation JS file
613
+     *
614
+     * @param string $application application id
615
+     * @param string|null $languageCode language code, defaults to the current language
616
+     * @param bool|null $prepend prepend the Script to the beginning of the list
617
+     */
618
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
619
+        if (is_null($languageCode)) {
620
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
621
+        }
622
+        if (!empty($application)) {
623
+            $path = "$application/l10n/$languageCode";
624
+        } else {
625
+            $path = "l10n/$languageCode";
626
+        }
627
+        self::addExternalResource($application, $prepend, $path, "script");
628
+    }
629
+
630
+    /**
631
+     * add a css file
632
+     *
633
+     * @param string $application application id
634
+     * @param string|null $file filename
635
+     * @param bool $prepend prepend the Style to the beginning of the list
636
+     * @return void
637
+     */
638
+    public static function addStyle($application, $file = null, $prepend = false) {
639
+        $path = OC_Util::generatePath($application, 'css', $file);
640
+        self::addExternalResource($application, $prepend, $path, "style");
641
+    }
642
+
643
+    /**
644
+     * add a css file from the vendor sub folder
645
+     *
646
+     * @param string $application application id
647
+     * @param string|null $file filename
648
+     * @param bool $prepend prepend the Style to the beginning of the list
649
+     * @return void
650
+     */
651
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
652
+        $path = OC_Util::generatePath($application, 'vendor', $file);
653
+        self::addExternalResource($application, $prepend, $path, "style");
654
+    }
655
+
656
+    /**
657
+     * add an external resource css/js file
658
+     *
659
+     * @param string $application application id
660
+     * @param bool $prepend prepend the file to the beginning of the list
661
+     * @param string $path
662
+     * @param string $type (script or style)
663
+     * @return void
664
+     */
665
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
666
+
667
+        if ($type === "style") {
668
+            if (!in_array($path, self::$styles)) {
669
+                if ($prepend === true) {
670
+                    array_unshift ( self::$styles, $path );
671
+                } else {
672
+                    self::$styles[] = $path;
673
+                }
674
+            }
675
+        } elseif ($type === "script") {
676
+            if (!in_array($path, self::$scripts)) {
677
+                if ($prepend === true) {
678
+                    array_unshift ( self::$scripts, $path );
679
+                } else {
680
+                    self::$scripts [] = $path;
681
+                }
682
+            }
683
+        }
684
+    }
685
+
686
+    /**
687
+     * Add a custom element to the header
688
+     * If $text is null then the element will be written as empty element.
689
+     * So use "" to get a closing tag.
690
+     * @param string $tag tag name of the element
691
+     * @param array $attributes array of attributes for the element
692
+     * @param string $text the text content for the element
693
+     * @param bool $prepend prepend the header to the beginning of the list
694
+     */
695
+    public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
696
+        $header = [
697
+            'tag' => $tag,
698
+            'attributes' => $attributes,
699
+            'text' => $text
700
+        ];
701
+        if ($prepend === true) {
702
+            array_unshift (self::$headers, $header);
703
+
704
+        } else {
705
+            self::$headers[] = $header;
706
+        }
707
+    }
708
+
709
+    /**
710
+     * check if the current server configuration is suitable for ownCloud
711
+     *
712
+     * @param \OC\SystemConfig $config
713
+     * @return array arrays with error messages and hints
714
+     */
715
+    public static function checkServer(\OC\SystemConfig $config) {
716
+        $l = \OC::$server->getL10N('lib');
717
+        $errors = [];
718
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
719
+
720
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
721
+            // this check needs to be done every time
722
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
723
+        }
724
+
725
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
726
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
727
+            return $errors;
728
+        }
729
+
730
+        $webServerRestart = false;
731
+        $setup = new \OC\Setup(
732
+            $config,
733
+            \OC::$server->getIniWrapper(),
734
+            \OC::$server->getL10N('lib'),
735
+            \OC::$server->query(\OCP\Defaults::class),
736
+            \OC::$server->getLogger(),
737
+            \OC::$server->getSecureRandom(),
738
+            \OC::$server->query(\OC\Installer::class)
739
+        );
740
+
741
+        $urlGenerator = \OC::$server->getURLGenerator();
742
+
743
+        $availableDatabases = $setup->getSupportedDatabases();
744
+        if (empty($availableDatabases)) {
745
+            $errors[] = [
746
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
747
+                'hint' => '' //TODO: sane hint
748
+            ];
749
+            $webServerRestart = true;
750
+        }
751
+
752
+        // Check if config folder is writable.
753
+        if(!OC_Helper::isReadOnlyConfigEnabled()) {
754
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
755
+                $errors[] = [
756
+                    'error' => $l->t('Cannot write into "config" directory'),
757
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
758
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
759
+                        . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
760
+                        [ $urlGenerator->linkToDocs('admin-config') ] )
761
+                ];
762
+            }
763
+        }
764
+
765
+        // Check if there is a writable install folder.
766
+        if ($config->getValue('appstoreenabled', true)) {
767
+            if (OC_App::getInstallPath() === null
768
+                || !is_writable(OC_App::getInstallPath())
769
+                || !is_readable(OC_App::getInstallPath())
770
+            ) {
771
+                $errors[] = [
772
+                    'error' => $l->t('Cannot write into "apps" directory'),
773
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
774
+                        . ' or disabling the appstore in the config file.')
775
+                ];
776
+            }
777
+        }
778
+        // Create root dir.
779
+        if ($config->getValue('installed', false)) {
780
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
781
+                $success = @mkdir($CONFIG_DATADIRECTORY);
782
+                if ($success) {
783
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
784
+                } else {
785
+                    $errors[] = [
786
+                        'error' => $l->t('Cannot create "data" directory'),
787
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
788
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
789
+                    ];
790
+                }
791
+            } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
792
+                // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
793
+                $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
794
+                $handle = fopen($testFile, 'w');
795
+                if (!$handle || fwrite($handle, 'Test write operation') === false) {
796
+                    $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
797
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')]);
798
+                    $errors[] = [
799
+                        'error' => 'Your data directory is not writable',
800
+                        'hint' => $permissionsHint
801
+                    ];
802
+                } else {
803
+                    fclose($handle);
804
+                    unlink($testFile);
805
+                }
806
+            } else {
807
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
808
+            }
809
+        }
810
+
811
+        if (!OC_Util::isSetLocaleWorking()) {
812
+            $errors[] = [
813
+                'error' => $l->t('Setting locale to %s failed',
814
+                    ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
815
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
816
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
817
+            ];
818
+        }
819
+
820
+        // Contains the dependencies that should be checked against
821
+        // classes = class_exists
822
+        // functions = function_exists
823
+        // defined = defined
824
+        // ini = ini_get
825
+        // If the dependency is not found the missing module name is shown to the EndUser
826
+        // When adding new checks always verify that they pass on Travis as well
827
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
828
+        $dependencies = [
829
+            'classes' => [
830
+                'ZipArchive' => 'zip',
831
+                'DOMDocument' => 'dom',
832
+                'XMLWriter' => 'XMLWriter',
833
+                'XMLReader' => 'XMLReader',
834
+            ],
835
+            'functions' => [
836
+                'xml_parser_create' => 'libxml',
837
+                'mb_strcut' => 'mbstring',
838
+                'ctype_digit' => 'ctype',
839
+                'json_encode' => 'JSON',
840
+                'gd_info' => 'GD',
841
+                'gzencode' => 'zlib',
842
+                'iconv' => 'iconv',
843
+                'simplexml_load_string' => 'SimpleXML',
844
+                'hash' => 'HASH Message Digest Framework',
845
+                'curl_init' => 'cURL',
846
+                'openssl_verify' => 'OpenSSL',
847
+            ],
848
+            'defined' => [
849
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
850
+            ],
851
+            'ini' => [
852
+                'default_charset' => 'UTF-8',
853
+            ],
854
+        ];
855
+        $missingDependencies = [];
856
+        $invalidIniSettings = [];
857
+        $moduleHint = $l->t('Please ask your server administrator to install the module.');
858
+
859
+        $iniWrapper = \OC::$server->getIniWrapper();
860
+        foreach ($dependencies['classes'] as $class => $module) {
861
+            if (!class_exists($class)) {
862
+                $missingDependencies[] = $module;
863
+            }
864
+        }
865
+        foreach ($dependencies['functions'] as $function => $module) {
866
+            if (!function_exists($function)) {
867
+                $missingDependencies[] = $module;
868
+            }
869
+        }
870
+        foreach ($dependencies['defined'] as $defined => $module) {
871
+            if (!defined($defined)) {
872
+                $missingDependencies[] = $module;
873
+            }
874
+        }
875
+        foreach ($dependencies['ini'] as $setting => $expected) {
876
+            if (is_bool($expected)) {
877
+                if ($iniWrapper->getBool($setting) !== $expected) {
878
+                    $invalidIniSettings[] = [$setting, $expected];
879
+                }
880
+            }
881
+            if (is_int($expected)) {
882
+                if ($iniWrapper->getNumeric($setting) !== $expected) {
883
+                    $invalidIniSettings[] = [$setting, $expected];
884
+                }
885
+            }
886
+            if (is_string($expected)) {
887
+                if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
888
+                    $invalidIniSettings[] = [$setting, $expected];
889
+                }
890
+            }
891
+        }
892
+
893
+        foreach($missingDependencies as $missingDependency) {
894
+            $errors[] = [
895
+                'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
896
+                'hint' => $moduleHint
897
+            ];
898
+            $webServerRestart = true;
899
+        }
900
+        foreach($invalidIniSettings as $setting) {
901
+            if(is_bool($setting[1])) {
902
+                $setting[1] = $setting[1] ? 'on' : 'off';
903
+            }
904
+            $errors[] = [
905
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
906
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
907
+            ];
908
+            $webServerRestart = true;
909
+        }
910
+
911
+        /**
912
+         * The mbstring.func_overload check can only be performed if the mbstring
913
+         * module is installed as it will return null if the checking setting is
914
+         * not available and thus a check on the boolean value fails.
915
+         *
916
+         * TODO: Should probably be implemented in the above generic dependency
917
+         *       check somehow in the long-term.
918
+         */
919
+        if($iniWrapper->getBool('mbstring.func_overload') !== null &&
920
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
921
+            $errors[] = [
922
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
923
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
924
+            ];
925
+        }
926
+
927
+        if(function_exists('xml_parser_create') &&
928
+            LIBXML_LOADED_VERSION < 20700 ) {
929
+            $version = LIBXML_LOADED_VERSION;
930
+            $major = floor($version/10000);
931
+            $version -= ($major * 10000);
932
+            $minor = floor($version/100);
933
+            $version -= ($minor * 100);
934
+            $patch = $version;
935
+            $errors[] = [
936
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
937
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
938
+            ];
939
+        }
940
+
941
+        if (!self::isAnnotationsWorking()) {
942
+            $errors[] = [
943
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
944
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
945
+            ];
946
+        }
947
+
948
+        if (!\OC::$CLI && $webServerRestart) {
949
+            $errors[] = [
950
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
951
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
952
+            ];
953
+        }
954
+
955
+        $errors = array_merge($errors, self::checkDatabaseVersion());
956
+
957
+        // Cache the result of this function
958
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
959
+
960
+        return $errors;
961
+    }
962
+
963
+    /**
964
+     * Check the database version
965
+     *
966
+     * @return array errors array
967
+     */
968
+    public static function checkDatabaseVersion() {
969
+        $l = \OC::$server->getL10N('lib');
970
+        $errors = [];
971
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
972
+        if ($dbType === 'pgsql') {
973
+            // check PostgreSQL version
974
+            try {
975
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
976
+                $data = $result->fetchRow();
977
+                if (isset($data['server_version'])) {
978
+                    $version = $data['server_version'];
979
+                    if (version_compare($version, '9.0.0', '<')) {
980
+                        $errors[] = [
981
+                            'error' => $l->t('PostgreSQL >= 9 required'),
982
+                            'hint' => $l->t('Please upgrade your database version')
983
+                        ];
984
+                    }
985
+                }
986
+            } catch (\Doctrine\DBAL\DBALException $e) {
987
+                $logger = \OC::$server->getLogger();
988
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
989
+                $logger->logException($e);
990
+            }
991
+        }
992
+        return $errors;
993
+    }
994
+
995
+    /**
996
+     * Check for correct file permissions of data directory
997
+     *
998
+     * @param string $dataDirectory
999
+     * @return array arrays with error messages and hints
1000
+     */
1001
+    public static function checkDataDirectoryPermissions($dataDirectory) {
1002
+        if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1003
+            return  [];
1004
+        }
1005
+        $l = \OC::$server->getL10N('lib');
1006
+        $errors = [];
1007
+        $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
1008
+            . ' cannot be listed by other users.');
1009
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1010
+        if (substr($perms, -1) !== '0') {
1011
+            chmod($dataDirectory, 0770);
1012
+            clearstatcache();
1013
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1014
+            if ($perms[2] !== '0') {
1015
+                $errors[] = [
1016
+                    'error' => $l->t('Your data directory is readable by other users'),
1017
+                    'hint' => $permissionsModHint
1018
+                ];
1019
+            }
1020
+        }
1021
+        return $errors;
1022
+    }
1023
+
1024
+    /**
1025
+     * Check that the data directory exists and is valid by
1026
+     * checking the existence of the ".ocdata" file.
1027
+     *
1028
+     * @param string $dataDirectory data directory path
1029
+     * @return array errors found
1030
+     */
1031
+    public static function checkDataDirectoryValidity($dataDirectory) {
1032
+        $l = \OC::$server->getL10N('lib');
1033
+        $errors = [];
1034
+        if ($dataDirectory[0] !== '/') {
1035
+            $errors[] = [
1036
+                'error' => $l->t('Your data directory must be an absolute path'),
1037
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1038
+            ];
1039
+        }
1040
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1041
+            $errors[] = [
1042
+                'error' => $l->t('Your data directory is invalid'),
1043
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1044
+                    ' in the root of the data directory.')
1045
+            ];
1046
+        }
1047
+        return $errors;
1048
+    }
1049
+
1050
+    /**
1051
+     * Check if the user is logged in, redirects to home if not. With
1052
+     * redirect URL parameter to the request URI.
1053
+     *
1054
+     * @return void
1055
+     */
1056
+    public static function checkLoggedIn() {
1057
+        // Check if we are a user
1058
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1059
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1060
+                        'core.login.showLoginForm',
1061
+                        [
1062
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1063
+                        ]
1064
+                    )
1065
+            );
1066
+            exit();
1067
+        }
1068
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1069
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1070
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1071
+            exit();
1072
+        }
1073
+    }
1074
+
1075
+    /**
1076
+     * Check if the user is a admin, redirects to home if not
1077
+     *
1078
+     * @return void
1079
+     */
1080
+    public static function checkAdminUser() {
1081
+        OC_Util::checkLoggedIn();
1082
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1083
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1084
+            exit();
1085
+        }
1086
+    }
1087
+
1088
+    /**
1089
+     * Returns the URL of the default page
1090
+     * based on the system configuration and
1091
+     * the apps visible for the current user
1092
+     *
1093
+     * @return string URL
1094
+     * @suppress PhanDeprecatedFunction
1095
+     */
1096
+    public static function getDefaultPageUrl() {
1097
+        $urlGenerator = \OC::$server->getURLGenerator();
1098
+        // Deny the redirect if the URL contains a @
1099
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1100
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1101
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1102
+        } else {
1103
+            $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1104
+            if ($defaultPage) {
1105
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1106
+            } else {
1107
+                $appId = 'files';
1108
+                $config = \OC::$server->getConfig();
1109
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1110
+                // find the first app that is enabled for the current user
1111
+                foreach ($defaultApps as $defaultApp) {
1112
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1113
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1114
+                        $appId = $defaultApp;
1115
+                        break;
1116
+                    }
1117
+                }
1118
+
1119
+                if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1120
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1121
+                } else {
1122
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1123
+                }
1124
+            }
1125
+        }
1126
+        return $location;
1127
+    }
1128
+
1129
+    /**
1130
+     * Redirect to the user default page
1131
+     *
1132
+     * @return void
1133
+     */
1134
+    public static function redirectToDefaultPage() {
1135
+        $location = self::getDefaultPageUrl();
1136
+        header('Location: ' . $location);
1137
+        exit();
1138
+    }
1139
+
1140
+    /**
1141
+     * get an id unique for this instance
1142
+     *
1143
+     * @return string
1144
+     */
1145
+    public static function getInstanceId() {
1146
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1147
+        if (is_null($id)) {
1148
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1149
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1150
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1151
+        }
1152
+        return $id;
1153
+    }
1154
+
1155
+    /**
1156
+     * Public function to sanitize HTML
1157
+     *
1158
+     * This function is used to sanitize HTML and should be applied on any
1159
+     * string or array of strings before displaying it on a web page.
1160
+     *
1161
+     * @param string|array $value
1162
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1163
+     */
1164
+    public static function sanitizeHTML($value) {
1165
+        if (is_array($value)) {
1166
+            $value = array_map(function ($value) {
1167
+                return self::sanitizeHTML($value);
1168
+            }, $value);
1169
+        } else {
1170
+            // Specify encoding for PHP<5.4
1171
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1172
+        }
1173
+        return $value;
1174
+    }
1175
+
1176
+    /**
1177
+     * Public function to encode url parameters
1178
+     *
1179
+     * This function is used to encode path to file before output.
1180
+     * Encoding is done according to RFC 3986 with one exception:
1181
+     * Character '/' is preserved as is.
1182
+     *
1183
+     * @param string $component part of URI to encode
1184
+     * @return string
1185
+     */
1186
+    public static function encodePath($component) {
1187
+        $encoded = rawurlencode($component);
1188
+        $encoded = str_replace('%2F', '/', $encoded);
1189
+        return $encoded;
1190
+    }
1191
+
1192
+
1193
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1194
+        // php dev server does not support htaccess
1195
+        if (php_sapi_name() === 'cli-server') {
1196
+            return false;
1197
+        }
1198
+
1199
+        // testdata
1200
+        $fileName = '/htaccesstest.txt';
1201
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1202
+
1203
+        // creating a test file
1204
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1205
+
1206
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1207
+            return false;
1208
+        }
1209
+
1210
+        $fp = @fopen($testFile, 'w');
1211
+        if (!$fp) {
1212
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1213
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1214
+        }
1215
+        fwrite($fp, $testContent);
1216
+        fclose($fp);
1217
+
1218
+        return $testContent;
1219
+    }
1220
+
1221
+    /**
1222
+     * Check if the .htaccess file is working
1223
+     * @param \OCP\IConfig $config
1224
+     * @return bool
1225
+     * @throws Exception
1226
+     * @throws \OC\HintException If the test file can't get written.
1227
+     */
1228
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1229
+
1230
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1231
+            return true;
1232
+        }
1233
+
1234
+        $testContent = $this->createHtaccessTestFile($config);
1235
+        if ($testContent === false) {
1236
+            return false;
1237
+        }
1238
+
1239
+        $fileName = '/htaccesstest.txt';
1240
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1241
+
1242
+        // accessing the file via http
1243
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1244
+        try {
1245
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1246
+        } catch (\Exception $e) {
1247
+            $content = false;
1248
+        }
1249
+
1250
+        if (strpos($url, 'https:') === 0) {
1251
+            $url = 'http:' . substr($url, 6);
1252
+        } else {
1253
+            $url = 'https:' . substr($url, 5);
1254
+        }
1255
+
1256
+        try {
1257
+            $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1258
+        } catch (\Exception $e) {
1259
+            $fallbackContent = false;
1260
+        }
1261
+
1262
+        // cleanup
1263
+        @unlink($testFile);
1264
+
1265
+        /*
1266 1266
 		 * If the content is not equal to test content our .htaccess
1267 1267
 		 * is working as required
1268 1268
 		 */
1269
-		return $content !== $testContent && $fallbackContent !== $testContent;
1270
-	}
1271
-
1272
-	/**
1273
-	 * Check if the setlocal call does not work. This can happen if the right
1274
-	 * local packages are not available on the server.
1275
-	 *
1276
-	 * @return bool
1277
-	 */
1278
-	public static function isSetLocaleWorking() {
1279
-		\Patchwork\Utf8\Bootup::initLocale();
1280
-		if ('' === basename('§')) {
1281
-			return false;
1282
-		}
1283
-		return true;
1284
-	}
1285
-
1286
-	/**
1287
-	 * Check if it's possible to get the inline annotations
1288
-	 *
1289
-	 * @return bool
1290
-	 */
1291
-	public static function isAnnotationsWorking() {
1292
-		$reflection = new \ReflectionMethod(__METHOD__);
1293
-		$docs = $reflection->getDocComment();
1294
-
1295
-		return (is_string($docs) && strlen($docs) > 50);
1296
-	}
1297
-
1298
-	/**
1299
-	 * Check if the PHP module fileinfo is loaded.
1300
-	 *
1301
-	 * @return bool
1302
-	 */
1303
-	public static function fileInfoLoaded() {
1304
-		return function_exists('finfo_open');
1305
-	}
1306
-
1307
-	/**
1308
-	 * clear all levels of output buffering
1309
-	 *
1310
-	 * @return void
1311
-	 */
1312
-	public static function obEnd() {
1313
-		while (ob_get_level()) {
1314
-			ob_end_clean();
1315
-		}
1316
-	}
1317
-
1318
-	/**
1319
-	 * Checks whether the server is running on Mac OS X
1320
-	 *
1321
-	 * @return bool true if running on Mac OS X, false otherwise
1322
-	 */
1323
-	public static function runningOnMac() {
1324
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1325
-	}
1326
-
1327
-	/**
1328
-	 * Handles the case that there may not be a theme, then check if a "default"
1329
-	 * theme exists and take that one
1330
-	 *
1331
-	 * @return string the theme
1332
-	 */
1333
-	public static function getTheme() {
1334
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1335
-
1336
-		if ($theme === '') {
1337
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1338
-				$theme = 'default';
1339
-			}
1340
-		}
1341
-
1342
-		return $theme;
1343
-	}
1344
-
1345
-	/**
1346
-	 * Normalize a unicode string
1347
-	 *
1348
-	 * @param string $value a not normalized string
1349
-	 * @return bool|string
1350
-	 */
1351
-	public static function normalizeUnicode($value) {
1352
-		if(Normalizer::isNormalized($value)) {
1353
-			return $value;
1354
-		}
1355
-
1356
-		$normalizedValue = Normalizer::normalize($value);
1357
-		if ($normalizedValue === null || $normalizedValue === false) {
1358
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1359
-			return $value;
1360
-		}
1361
-
1362
-		return $normalizedValue;
1363
-	}
1364
-
1365
-	/**
1366
-	 * A human readable string is generated based on version and build number
1367
-	 *
1368
-	 * @return string
1369
-	 */
1370
-	public static function getHumanVersion() {
1371
-		$version = OC_Util::getVersionString();
1372
-		$build = OC_Util::getBuild();
1373
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1374
-			$version .= ' Build:' . $build;
1375
-		}
1376
-		return $version;
1377
-	}
1378
-
1379
-	/**
1380
-	 * Returns whether the given file name is valid
1381
-	 *
1382
-	 * @param string $file file name to check
1383
-	 * @return bool true if the file name is valid, false otherwise
1384
-	 * @deprecated use \OC\Files\View::verifyPath()
1385
-	 */
1386
-	public static function isValidFileName($file) {
1387
-		$trimmed = trim($file);
1388
-		if ($trimmed === '') {
1389
-			return false;
1390
-		}
1391
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1392
-			return false;
1393
-		}
1394
-
1395
-		// detect part files
1396
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1397
-			return false;
1398
-		}
1399
-
1400
-		foreach (str_split($trimmed) as $char) {
1401
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1402
-				return false;
1403
-			}
1404
-		}
1405
-		return true;
1406
-	}
1407
-
1408
-	/**
1409
-	 * Check whether the instance needs to perform an upgrade,
1410
-	 * either when the core version is higher or any app requires
1411
-	 * an upgrade.
1412
-	 *
1413
-	 * @param \OC\SystemConfig $config
1414
-	 * @return bool whether the core or any app needs an upgrade
1415
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1416
-	 */
1417
-	public static function needUpgrade(\OC\SystemConfig $config) {
1418
-		if ($config->getValue('installed', false)) {
1419
-			$installedVersion = $config->getValue('version', '0.0.0');
1420
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1421
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1422
-			if ($versionDiff > 0) {
1423
-				return true;
1424
-			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1425
-				// downgrade with debug
1426
-				$installedMajor = explode('.', $installedVersion);
1427
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1428
-				$currentMajor = explode('.', $currentVersion);
1429
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1430
-				if ($installedMajor === $currentMajor) {
1431
-					// Same major, allow downgrade for developers
1432
-					return true;
1433
-				} else {
1434
-					// downgrade attempt, throw exception
1435
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1436
-				}
1437
-			} else if ($versionDiff < 0) {
1438
-				// downgrade attempt, throw exception
1439
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1440
-			}
1441
-
1442
-			// also check for upgrades for apps (independently from the user)
1443
-			$apps = \OC_App::getEnabledApps(false, true);
1444
-			$shouldUpgrade = false;
1445
-			foreach ($apps as $app) {
1446
-				if (\OC_App::shouldUpgrade($app)) {
1447
-					$shouldUpgrade = true;
1448
-					break;
1449
-				}
1450
-			}
1451
-			return $shouldUpgrade;
1452
-		} else {
1453
-			return false;
1454
-		}
1455
-	}
1456
-
1457
-	/**
1458
-	 * is this Internet explorer ?
1459
-	 *
1460
-	 * @return boolean
1461
-	 */
1462
-	public static function isIe() {
1463
-		if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1464
-			return false;
1465
-		}
1466
-
1467
-		return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1468
-	}
1269
+        return $content !== $testContent && $fallbackContent !== $testContent;
1270
+    }
1271
+
1272
+    /**
1273
+     * Check if the setlocal call does not work. This can happen if the right
1274
+     * local packages are not available on the server.
1275
+     *
1276
+     * @return bool
1277
+     */
1278
+    public static function isSetLocaleWorking() {
1279
+        \Patchwork\Utf8\Bootup::initLocale();
1280
+        if ('' === basename('§')) {
1281
+            return false;
1282
+        }
1283
+        return true;
1284
+    }
1285
+
1286
+    /**
1287
+     * Check if it's possible to get the inline annotations
1288
+     *
1289
+     * @return bool
1290
+     */
1291
+    public static function isAnnotationsWorking() {
1292
+        $reflection = new \ReflectionMethod(__METHOD__);
1293
+        $docs = $reflection->getDocComment();
1294
+
1295
+        return (is_string($docs) && strlen($docs) > 50);
1296
+    }
1297
+
1298
+    /**
1299
+     * Check if the PHP module fileinfo is loaded.
1300
+     *
1301
+     * @return bool
1302
+     */
1303
+    public static function fileInfoLoaded() {
1304
+        return function_exists('finfo_open');
1305
+    }
1306
+
1307
+    /**
1308
+     * clear all levels of output buffering
1309
+     *
1310
+     * @return void
1311
+     */
1312
+    public static function obEnd() {
1313
+        while (ob_get_level()) {
1314
+            ob_end_clean();
1315
+        }
1316
+    }
1317
+
1318
+    /**
1319
+     * Checks whether the server is running on Mac OS X
1320
+     *
1321
+     * @return bool true if running on Mac OS X, false otherwise
1322
+     */
1323
+    public static function runningOnMac() {
1324
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1325
+    }
1326
+
1327
+    /**
1328
+     * Handles the case that there may not be a theme, then check if a "default"
1329
+     * theme exists and take that one
1330
+     *
1331
+     * @return string the theme
1332
+     */
1333
+    public static function getTheme() {
1334
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1335
+
1336
+        if ($theme === '') {
1337
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1338
+                $theme = 'default';
1339
+            }
1340
+        }
1341
+
1342
+        return $theme;
1343
+    }
1344
+
1345
+    /**
1346
+     * Normalize a unicode string
1347
+     *
1348
+     * @param string $value a not normalized string
1349
+     * @return bool|string
1350
+     */
1351
+    public static function normalizeUnicode($value) {
1352
+        if(Normalizer::isNormalized($value)) {
1353
+            return $value;
1354
+        }
1355
+
1356
+        $normalizedValue = Normalizer::normalize($value);
1357
+        if ($normalizedValue === null || $normalizedValue === false) {
1358
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1359
+            return $value;
1360
+        }
1361
+
1362
+        return $normalizedValue;
1363
+    }
1364
+
1365
+    /**
1366
+     * A human readable string is generated based on version and build number
1367
+     *
1368
+     * @return string
1369
+     */
1370
+    public static function getHumanVersion() {
1371
+        $version = OC_Util::getVersionString();
1372
+        $build = OC_Util::getBuild();
1373
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1374
+            $version .= ' Build:' . $build;
1375
+        }
1376
+        return $version;
1377
+    }
1378
+
1379
+    /**
1380
+     * Returns whether the given file name is valid
1381
+     *
1382
+     * @param string $file file name to check
1383
+     * @return bool true if the file name is valid, false otherwise
1384
+     * @deprecated use \OC\Files\View::verifyPath()
1385
+     */
1386
+    public static function isValidFileName($file) {
1387
+        $trimmed = trim($file);
1388
+        if ($trimmed === '') {
1389
+            return false;
1390
+        }
1391
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1392
+            return false;
1393
+        }
1394
+
1395
+        // detect part files
1396
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1397
+            return false;
1398
+        }
1399
+
1400
+        foreach (str_split($trimmed) as $char) {
1401
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1402
+                return false;
1403
+            }
1404
+        }
1405
+        return true;
1406
+    }
1407
+
1408
+    /**
1409
+     * Check whether the instance needs to perform an upgrade,
1410
+     * either when the core version is higher or any app requires
1411
+     * an upgrade.
1412
+     *
1413
+     * @param \OC\SystemConfig $config
1414
+     * @return bool whether the core or any app needs an upgrade
1415
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1416
+     */
1417
+    public static function needUpgrade(\OC\SystemConfig $config) {
1418
+        if ($config->getValue('installed', false)) {
1419
+            $installedVersion = $config->getValue('version', '0.0.0');
1420
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1421
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1422
+            if ($versionDiff > 0) {
1423
+                return true;
1424
+            } else if ($config->getValue('debug', false) && $versionDiff < 0) {
1425
+                // downgrade with debug
1426
+                $installedMajor = explode('.', $installedVersion);
1427
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1428
+                $currentMajor = explode('.', $currentVersion);
1429
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1430
+                if ($installedMajor === $currentMajor) {
1431
+                    // Same major, allow downgrade for developers
1432
+                    return true;
1433
+                } else {
1434
+                    // downgrade attempt, throw exception
1435
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1436
+                }
1437
+            } else if ($versionDiff < 0) {
1438
+                // downgrade attempt, throw exception
1439
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1440
+            }
1441
+
1442
+            // also check for upgrades for apps (independently from the user)
1443
+            $apps = \OC_App::getEnabledApps(false, true);
1444
+            $shouldUpgrade = false;
1445
+            foreach ($apps as $app) {
1446
+                if (\OC_App::shouldUpgrade($app)) {
1447
+                    $shouldUpgrade = true;
1448
+                    break;
1449
+                }
1450
+            }
1451
+            return $shouldUpgrade;
1452
+        } else {
1453
+            return false;
1454
+        }
1455
+    }
1456
+
1457
+    /**
1458
+     * is this Internet explorer ?
1459
+     *
1460
+     * @return boolean
1461
+     */
1462
+    public static function isIe() {
1463
+        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1464
+            return false;
1465
+        }
1466
+
1467
+        return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1468
+    }
1469 1469
 
1470 1470
 }
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 
85 85
 	private static function initLocalStorageRootFS() {
86 86
 		// mount local file backend as root
87
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
87
+		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT."/data");
88 88
 		//first set up the local "root" storage
89 89
 		\OC\Files\Filesystem::initMountManager();
90 90
 		if (!self::$rootMounted) {
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
 		\OC\Files\Filesystem::initMountManager();
207 207
 
208 208
 		$prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
209
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
209
+		\OC\Files\Filesystem::addStorageWrapper('mount_options', function($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
210 210
 			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
211 211
 				/** @var \OC\Files\Storage\Common $storage */
212 212
 				$storage->setMountOptions($mount->getOptions());
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
 			return $storage;
215 215
 		});
216 216
 
217
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
217
+		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
218 218
 			if (!$mount->getOption('enable_sharing', true)) {
219 219
 				return new \OC\Files\Storage\Wrapper\PermissionsMask([
220 220
 					'storage' => $storage,
@@ -225,21 +225,21 @@  discard block
 block discarded – undo
225 225
 		});
226 226
 
227 227
 		// install storage availability wrapper, before most other wrappers
228
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
228
+		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function($mountPoint, \OCP\Files\Storage\IStorage $storage) {
229 229
 			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
230 230
 				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
231 231
 			}
232 232
 			return $storage;
233 233
 		});
234 234
 
235
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
235
+		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
236 236
 			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
237 237
 				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
238 238
 			}
239 239
 			return $storage;
240 240
 		});
241 241
 
242
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
242
+		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function($mountPoint, $storage) {
243 243
 			// set up quota for home storages, even for other users
244 244
 			// which can happen when using sharing
245 245
 
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 			return $storage;
262 262
 		});
263 263
 
264
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
264
+		\OC\Files\Filesystem::addStorageWrapper('readonly', function($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
265 265
 			/*
266 266
 			 * Do not allow any operations that modify the storage
267 267
 			 */
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
 		//if we aren't logged in, there is no use to set up the filesystem
304 304
 		if ($user != "") {
305 305
 
306
-			$userDir = '/' . $user . '/files';
306
+			$userDir = '/'.$user.'/files';
307 307
 
308 308
 			//jail the user into his "home" directory
309 309
 			\OC\Files\Filesystem::init($user, $userDir);
@@ -382,7 +382,7 @@  discard block
 block discarded – undo
382 382
 			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
383 383
 		}
384 384
 		$userQuota = $user->getQuota();
385
-		if($userQuota === 'none') {
385
+		if ($userQuota === 'none') {
386 386
 			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
387 387
 		}
388 388
 		return OC_Helper::computerFileSize($userQuota);
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
 	 */
400 400
 	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
401 401
 
402
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
402
+		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT.'/core/skeleton');
403 403
 		$userLang = \OC::$server->getL10NFactory()->findLanguage();
404 404
 		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
405 405
 
@@ -421,9 +421,9 @@  discard block
 block discarded – undo
421 421
 		if ($instanceId === null) {
422 422
 			throw new \RuntimeException('no instance id!');
423 423
 		}
424
-		$appdata = 'appdata_' . $instanceId;
424
+		$appdata = 'appdata_'.$instanceId;
425 425
 		if ($userId === $appdata) {
426
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
426
+			throw new \RuntimeException('username is reserved name: '.$appdata);
427 427
 		}
428 428
 
429 429
 		if (!empty($skeletonDirectory)) {
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
 
451 451
 		// Verify if folder exists
452 452
 		$dir = opendir($source);
453
-		if($dir === false) {
453
+		if ($dir === false) {
454 454
 			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
455 455
 			return;
456 456
 		}
@@ -458,14 +458,14 @@  discard block
 block discarded – undo
458 458
 		// Copy the files
459 459
 		while (false !== ($file = readdir($dir))) {
460 460
 			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
461
-				if (is_dir($source . '/' . $file)) {
461
+				if (is_dir($source.'/'.$file)) {
462 462
 					$child = $target->newFolder($file);
463
-					self::copyr($source . '/' . $file, $child);
463
+					self::copyr($source.'/'.$file, $child);
464 464
 				} else {
465 465
 					$child = $target->newFile($file);
466
-					$sourceStream = fopen($source . '/' . $file, 'r');
467
-					if($sourceStream === false) {
468
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
466
+					$sourceStream = fopen($source.'/'.$file, 'r');
467
+					if ($sourceStream === false) {
468
+						$logger->error(sprintf('Could not fopen "%s"', $source.'/'.$file), ['app' => 'core']);
469 469
 						closedir($dir);
470 470
 						return;
471 471
 					}
@@ -542,8 +542,8 @@  discard block
 block discarded – undo
542 542
 			return;
543 543
 		}
544 544
 
545
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
546
-		require OC::$SERVERROOT . '/version.php';
545
+		$timestamp = filemtime(OC::$SERVERROOT.'/version.php');
546
+		require OC::$SERVERROOT.'/version.php';
547 547
 		/** @var $timestamp int */
548 548
 		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
549 549
 		/** @var $OC_Version string */
@@ -590,7 +590,7 @@  discard block
 block discarded – undo
590 590
 
591 591
 		// core js files need separate handling
592 592
 		if ($application !== 'core' && $file !== null) {
593
-			self::addTranslations ( $application );
593
+			self::addTranslations($application);
594 594
 		}
595 595
 		self::addExternalResource($application, $prepend, $path, "script");
596 596
 	}
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
 		if ($type === "style") {
668 668
 			if (!in_array($path, self::$styles)) {
669 669
 				if ($prepend === true) {
670
-					array_unshift ( self::$styles, $path );
670
+					array_unshift(self::$styles, $path);
671 671
 				} else {
672 672
 					self::$styles[] = $path;
673 673
 				}
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
 		} elseif ($type === "script") {
676 676
 			if (!in_array($path, self::$scripts)) {
677 677
 				if ($prepend === true) {
678
-					array_unshift ( self::$scripts, $path );
678
+					array_unshift(self::$scripts, $path);
679 679
 				} else {
680 680
 					self::$scripts [] = $path;
681 681
 				}
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 			'text' => $text
700 700
 		];
701 701
 		if ($prepend === true) {
702
-			array_unshift (self::$headers, $header);
702
+			array_unshift(self::$headers, $header);
703 703
 
704 704
 		} else {
705 705
 			self::$headers[] = $header;
@@ -715,7 +715,7 @@  discard block
 block discarded – undo
715 715
 	public static function checkServer(\OC\SystemConfig $config) {
716 716
 		$l = \OC::$server->getL10N('lib');
717 717
 		$errors = [];
718
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
718
+		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT.'/data');
719 719
 
720 720
 		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
721 721
 			// this check needs to be done every time
@@ -750,14 +750,14 @@  discard block
 block discarded – undo
750 750
 		}
751 751
 
752 752
 		// Check if config folder is writable.
753
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
753
+		if (!OC_Helper::isReadOnlyConfigEnabled()) {
754 754
 			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
755 755
 				$errors[] = [
756 756
 					'error' => $l->t('Cannot write into "config" directory'),
757 757
 					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
758
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
758
+						[$urlGenerator->linkToDocs('admin-dir_permissions')]).'. '
759 759
 						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
760
-						[ $urlGenerator->linkToDocs('admin-config') ] )
760
+						[$urlGenerator->linkToDocs('admin-config')])
761 761
 				];
762 762
 			}
763 763
 		}
@@ -890,15 +890,15 @@  discard block
 block discarded – undo
890 890
 			}
891 891
 		}
892 892
 
893
-		foreach($missingDependencies as $missingDependency) {
893
+		foreach ($missingDependencies as $missingDependency) {
894 894
 			$errors[] = [
895 895
 				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
896 896
 				'hint' => $moduleHint
897 897
 			];
898 898
 			$webServerRestart = true;
899 899
 		}
900
-		foreach($invalidIniSettings as $setting) {
901
-			if(is_bool($setting[1])) {
900
+		foreach ($invalidIniSettings as $setting) {
901
+			if (is_bool($setting[1])) {
902 902
 				$setting[1] = $setting[1] ? 'on' : 'off';
903 903
 			}
904 904
 			$errors[] = [
@@ -916,7 +916,7 @@  discard block
 block discarded – undo
916 916
 		 * TODO: Should probably be implemented in the above generic dependency
917 917
 		 *       check somehow in the long-term.
918 918
 		 */
919
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
919
+		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
920 920
 			$iniWrapper->getBool('mbstring.func_overload') === true) {
921 921
 			$errors[] = [
922 922
 				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
@@ -924,16 +924,16 @@  discard block
 block discarded – undo
924 924
 			];
925 925
 		}
926 926
 
927
-		if(function_exists('xml_parser_create') &&
928
-			LIBXML_LOADED_VERSION < 20700 ) {
927
+		if (function_exists('xml_parser_create') &&
928
+			LIBXML_LOADED_VERSION < 20700) {
929 929
 			$version = LIBXML_LOADED_VERSION;
930
-			$major = floor($version/10000);
930
+			$major = floor($version / 10000);
931 931
 			$version -= ($major * 10000);
932
-			$minor = floor($version/100);
932
+			$minor = floor($version / 100);
933 933
 			$version -= ($minor * 100);
934 934
 			$patch = $version;
935 935
 			$errors[] = [
936
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
936
+				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major.'.'.$minor.'.'.$patch]),
937 937
 				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
938 938
 			];
939 939
 		}
@@ -999,7 +999,7 @@  discard block
 block discarded – undo
999 999
 	 * @return array arrays with error messages and hints
1000 1000
 	 */
1001 1001
 	public static function checkDataDirectoryPermissions($dataDirectory) {
1002
-		if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1002
+		if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1003 1003
 			return  [];
1004 1004
 		}
1005 1005
 		$l = \OC::$server->getL10N('lib');
@@ -1037,10 +1037,10 @@  discard block
 block discarded – undo
1037 1037
 				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1038 1038
 			];
1039 1039
 		}
1040
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1040
+		if (!file_exists($dataDirectory.'/.ocdata')) {
1041 1041
 			$errors[] = [
1042 1042
 				'error' => $l->t('Your data directory is invalid'),
1043
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1043
+				'hint' => $l->t('Ensure there is a file called ".ocdata"'.
1044 1044
 					' in the root of the data directory.')
1045 1045
 			];
1046 1046
 		}
@@ -1056,7 +1056,7 @@  discard block
 block discarded – undo
1056 1056
 	public static function checkLoggedIn() {
1057 1057
 		// Check if we are a user
1058 1058
 		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1059
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1059
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute(
1060 1060
 						'core.login.showLoginForm',
1061 1061
 						[
1062 1062
 							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
@@ -1067,7 +1067,7 @@  discard block
 block discarded – undo
1067 1067
 		}
1068 1068
 		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1069 1069
 		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1070
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1070
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1071 1071
 			exit();
1072 1072
 		}
1073 1073
 	}
@@ -1080,7 +1080,7 @@  discard block
 block discarded – undo
1080 1080
 	public static function checkAdminUser() {
1081 1081
 		OC_Util::checkLoggedIn();
1082 1082
 		if (!OC_User::isAdminUser(OC_User::getUser())) {
1083
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1083
+			header('Location: '.\OCP\Util::linkToAbsolute('', 'index.php'));
1084 1084
 			exit();
1085 1085
 		}
1086 1086
 	}
@@ -1116,10 +1116,10 @@  discard block
 block discarded – undo
1116 1116
 					}
1117 1117
 				}
1118 1118
 
1119
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1120
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1119
+				if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1120
+					$location = $urlGenerator->getAbsoluteURL('/apps/'.$appId.'/');
1121 1121
 				} else {
1122
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1122
+					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/'.$appId.'/');
1123 1123
 				}
1124 1124
 			}
1125 1125
 		}
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
 	 */
1134 1134
 	public static function redirectToDefaultPage() {
1135 1135
 		$location = self::getDefaultPageUrl();
1136
-		header('Location: ' . $location);
1136
+		header('Location: '.$location);
1137 1137
 		exit();
1138 1138
 	}
1139 1139
 
@@ -1146,7 +1146,7 @@  discard block
 block discarded – undo
1146 1146
 		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1147 1147
 		if (is_null($id)) {
1148 1148
 			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1149
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1149
+			$id = 'oc'.\OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1150 1150
 			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1151 1151
 		}
1152 1152
 		return $id;
@@ -1163,12 +1163,12 @@  discard block
 block discarded – undo
1163 1163
 	 */
1164 1164
 	public static function sanitizeHTML($value) {
1165 1165
 		if (is_array($value)) {
1166
-			$value = array_map(function ($value) {
1166
+			$value = array_map(function($value) {
1167 1167
 				return self::sanitizeHTML($value);
1168 1168
 			}, $value);
1169 1169
 		} else {
1170 1170
 			// Specify encoding for PHP<5.4
1171
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1171
+			$value = htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
1172 1172
 		}
1173 1173
 		return $value;
1174 1174
 	}
@@ -1201,7 +1201,7 @@  discard block
 block discarded – undo
1201 1201
 		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1202 1202
 
1203 1203
 		// creating a test file
1204
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1204
+		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$fileName;
1205 1205
 
1206 1206
 		if (file_exists($testFile)) {// already running this test, possible recursive call
1207 1207
 			return false;
@@ -1210,7 +1210,7 @@  discard block
 block discarded – undo
1210 1210
 		$fp = @fopen($testFile, 'w');
1211 1211
 		if (!$fp) {
1212 1212
 			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1213
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1213
+				'Make sure it is possible for the webserver to write to '.$testFile);
1214 1214
 		}
1215 1215
 		fwrite($fp, $testContent);
1216 1216
 		fclose($fp);
@@ -1237,10 +1237,10 @@  discard block
 block discarded – undo
1237 1237
 		}
1238 1238
 
1239 1239
 		$fileName = '/htaccesstest.txt';
1240
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1240
+		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$fileName;
1241 1241
 
1242 1242
 		// accessing the file via http
1243
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1243
+		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT.'/data'.$fileName);
1244 1244
 		try {
1245 1245
 			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1246 1246
 		} catch (\Exception $e) {
@@ -1248,9 +1248,9 @@  discard block
 block discarded – undo
1248 1248
 		}
1249 1249
 
1250 1250
 		if (strpos($url, 'https:') === 0) {
1251
-			$url = 'http:' . substr($url, 6);
1251
+			$url = 'http:'.substr($url, 6);
1252 1252
 		} else {
1253
-			$url = 'https:' . substr($url, 5);
1253
+			$url = 'https:'.substr($url, 5);
1254 1254
 		}
1255 1255
 
1256 1256
 		try {
@@ -1334,7 +1334,7 @@  discard block
 block discarded – undo
1334 1334
 		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1335 1335
 
1336 1336
 		if ($theme === '') {
1337
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1337
+			if (is_dir(OC::$SERVERROOT.'/themes/default')) {
1338 1338
 				$theme = 'default';
1339 1339
 			}
1340 1340
 		}
@@ -1349,13 +1349,13 @@  discard block
 block discarded – undo
1349 1349
 	 * @return bool|string
1350 1350
 	 */
1351 1351
 	public static function normalizeUnicode($value) {
1352
-		if(Normalizer::isNormalized($value)) {
1352
+		if (Normalizer::isNormalized($value)) {
1353 1353
 			return $value;
1354 1354
 		}
1355 1355
 
1356 1356
 		$normalizedValue = Normalizer::normalize($value);
1357 1357
 		if ($normalizedValue === null || $normalizedValue === false) {
1358
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1358
+			\OC::$server->getLogger()->warning('normalizing failed for "'.$value.'"', ['app' => 'core']);
1359 1359
 			return $value;
1360 1360
 		}
1361 1361
 
@@ -1371,7 +1371,7 @@  discard block
 block discarded – undo
1371 1371
 		$version = OC_Util::getVersionString();
1372 1372
 		$build = OC_Util::getBuild();
1373 1373
 		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1374
-			$version .= ' Build:' . $build;
1374
+			$version .= ' Build:'.$build;
1375 1375
 		}
1376 1376
 		return $version;
1377 1377
 	}
@@ -1393,7 +1393,7 @@  discard block
 block discarded – undo
1393 1393
 		}
1394 1394
 
1395 1395
 		// detect part files
1396
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1396
+		if (preg_match('/'.\OCP\Files\FileInfo::BLACKLIST_FILES_REGEX.'/', $trimmed) !== 0) {
1397 1397
 			return false;
1398 1398
 		}
1399 1399
 
@@ -1424,19 +1424,19 @@  discard block
 block discarded – undo
1424 1424
 			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1425 1425
 				// downgrade with debug
1426 1426
 				$installedMajor = explode('.', $installedVersion);
1427
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1427
+				$installedMajor = $installedMajor[0].'.'.$installedMajor[1];
1428 1428
 				$currentMajor = explode('.', $currentVersion);
1429
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1429
+				$currentMajor = $currentMajor[0].'.'.$currentMajor[1];
1430 1430
 				if ($installedMajor === $currentMajor) {
1431 1431
 					// Same major, allow downgrade for developers
1432 1432
 					return true;
1433 1433
 				} else {
1434 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 . ')');
1435
+					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
1436 1436
 				}
1437 1437
 			} else if ($versionDiff < 0) {
1438 1438
 				// downgrade attempt, throw exception
1439
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1439
+				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
1440 1440
 			}
1441 1441
 
1442 1442
 			// also check for upgrades for apps (independently from the user)
Please login to merge, or discard this patch.
lib/private/legacy/OC_Template.php 2 patches
Indentation   +311 added lines, -311 removed lines patch added patch discarded remove patch
@@ -47,315 +47,315 @@
 block discarded – undo
47 47
  */
48 48
 class OC_Template extends \OC\Template\Base {
49 49
 
50
-	/** @var string */
51
-	private $renderAs; // Create a full page?
52
-
53
-	/** @var string */
54
-	private $path; // The path to the template
55
-
56
-	/** @var array */
57
-	private $headers = []; //custom headers
58
-
59
-	/** @var string */
60
-	protected $app; // app id
61
-
62
-	protected static $initTemplateEngineFirstRun = true;
63
-
64
-	/**
65
-	 * Constructor
66
-	 *
67
-	 * @param string $app app providing the template
68
-	 * @param string $name of the template file (without suffix)
69
-	 * @param string $renderAs If $renderAs is set, OC_Template will try to
70
-	 *                         produce a full page in the according layout. For
71
-	 *                         now, $renderAs can be set to "guest", "user" or
72
-	 *                         "admin".
73
-	 * @param bool $registerCall = true
74
-	 */
75
-	public function __construct($app, $name, $renderAs = "", $registerCall = true) {
76
-		// Read the selected theme from the config file
77
-		self::initTemplateEngine($renderAs);
78
-
79
-		$theme = OC_Util::getTheme();
80
-
81
-		$requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
82
-
83
-		$parts = explode('/', $app); // fix translation when app is something like core/lostpassword
84
-		$l10n = \OC::$server->getL10N($parts[0]);
85
-		/** @var \OCP\Defaults $themeDefaults */
86
-		$themeDefaults = \OC::$server->query(\OCP\Defaults::class);
87
-
88
-		list($path, $template) = $this->findTemplate($theme, $app, $name);
89
-
90
-		// Set the private data
91
-		$this->renderAs = $renderAs;
92
-		$this->path = $path;
93
-		$this->app = $app;
94
-
95
-		parent::__construct($template, $requestToken, $l10n, $themeDefaults);
96
-	}
97
-
98
-	/**
99
-	 * @param string $renderAs
100
-	 */
101
-	public static function initTemplateEngine($renderAs) {
102
-		if (self::$initTemplateEngineFirstRun){
103
-
104
-			//apps that started before the template initialization can load their own scripts/styles
105
-			//so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
106
-			//meaning the last script/style in this list will be loaded first
107
-			if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
108
-				if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
109
-					OC_Util::addScript ( 'backgroundjobs', null, true );
110
-				}
111
-			}
112
-			OC_Util::addStyle('css-variables', null, true);
113
-			OC_Util::addStyle('server', null, true);
114
-			OC_Util::addTranslations('core', null, true);
115
-
116
-			if (\OC::$server->getSystemConfig()->getValue ('installed', false)) {
117
-				OC_Util::addStyle('search', 'results');
118
-				OC_Util::addScript('search', 'search', true);
119
-				OC_Util::addScript('search', 'searchprovider');
120
-				OC_Util::addScript('merged-template-prepend', null, true);
121
-				OC_Util::addScript('files/fileinfo');
122
-				OC_Util::addScript('files/client');
123
-			}
124
-			OC_Util::addScript('core', 'dist/main', true);
125
-
126
-			if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
127
-				// shim for the davclient.js library
128
-				\OCP\Util::addScript('files/iedavclient');
129
-			}
130
-
131
-			self::$initTemplateEngineFirstRun = false;
132
-		}
133
-
134
-	}
135
-
136
-
137
-	/**
138
-	 * find the template with the given name
139
-	 * @param string $name of the template file (without suffix)
140
-	 *
141
-	 * Will select the template file for the selected theme.
142
-	 * Checking all the possible locations.
143
-	 * @param string $theme
144
-	 * @param string $app
145
-	 * @return string[]
146
-	 */
147
-	protected function findTemplate($theme, $app, $name) {
148
-		// Check if it is a app template or not.
149
-		if( $app !== '' ) {
150
-			$dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
151
-		} else {
152
-			$dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
153
-		}
154
-		$locator = new \OC\Template\TemplateFileLocator( $dirs );
155
-		$template = $locator->find($name);
156
-		$path = $locator->getPath();
157
-		return [$path, $template];
158
-	}
159
-
160
-	/**
161
-	 * Add a custom element to the header
162
-	 * @param string $tag tag name of the element
163
-	 * @param array $attributes array of attributes for the element
164
-	 * @param string $text the text content for the element. If $text is null then the
165
-	 * element will be written as empty element. So use "" to get a closing tag.
166
-	 */
167
-	public function addHeader($tag, $attributes, $text=null) {
168
-		$this->headers[]= [
169
-			'tag' => $tag,
170
-			'attributes' => $attributes,
171
-			'text' => $text
172
-		];
173
-	}
174
-
175
-	/**
176
-	 * Process the template
177
-	 * @return boolean|string
178
-	 *
179
-	 * This function process the template. If $this->renderAs is set, it
180
-	 * will produce a full page.
181
-	 */
182
-	public function fetchPage($additionalParams = null) {
183
-		$data = parent::fetchPage($additionalParams);
184
-
185
-		if( $this->renderAs ) {
186
-			$page = new TemplateLayout($this->renderAs, $this->app);
187
-
188
-			if(is_array($additionalParams)) {
189
-				foreach ($additionalParams as $key => $value) {
190
-					$page->assign($key, $value);
191
-				}
192
-			}
193
-
194
-			// Add custom headers
195
-			$headers = '';
196
-			foreach(OC_Util::$headers as $header) {
197
-				$headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
198
-				if ( strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes']))) ) {
199
-					$headers .= ' defer';
200
-				}
201
-				foreach($header['attributes'] as $name=>$value) {
202
-					$headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
203
-				}
204
-				if ($header['text'] !== null) {
205
-					$headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
206
-				} else {
207
-					$headers .= '/>';
208
-				}
209
-			}
210
-
211
-			$page->assign('headers', $headers);
212
-
213
-			$page->assign('content', $data);
214
-			return $page->fetchPage($additionalParams);
215
-		}
216
-
217
-		return $data;
218
-	}
219
-
220
-	/**
221
-	 * Include template
222
-	 *
223
-	 * @param string $file
224
-	 * @param array|null $additionalParams
225
-	 * @return string returns content of included template
226
-	 *
227
-	 * Includes another template. use <?php echo $this->inc('template'); ?> to
228
-	 * do this.
229
-	 */
230
-	public function inc($file, $additionalParams = null) {
231
-		return $this->load($this->path.$file.'.php', $additionalParams);
232
-	}
233
-
234
-	/**
235
-	 * Shortcut to print a simple page for users
236
-	 * @param string $application The application we render the template for
237
-	 * @param string $name Name of the template
238
-	 * @param array $parameters Parameters for the template
239
-	 * @return boolean|null
240
-	 */
241
-	public static function printUserPage($application, $name, $parameters = []) {
242
-		$content = new OC_Template( $application, $name, "user" );
243
-		foreach( $parameters as $key => $value ) {
244
-			$content->assign( $key, $value );
245
-		}
246
-		print $content->printPage();
247
-	}
248
-
249
-	/**
250
-	 * Shortcut to print a simple page for admins
251
-	 * @param string $application The application we render the template for
252
-	 * @param string $name Name of the template
253
-	 * @param array $parameters Parameters for the template
254
-	 * @return bool
255
-	 */
256
-	public static function printAdminPage($application, $name, $parameters = []) {
257
-		$content = new OC_Template( $application, $name, "admin" );
258
-		foreach( $parameters as $key => $value ) {
259
-			$content->assign( $key, $value );
260
-		}
261
-		return $content->printPage();
262
-	}
263
-
264
-	/**
265
-	 * Shortcut to print a simple page for guests
266
-	 * @param string $application The application we render the template for
267
-	 * @param string $name Name of the template
268
-	 * @param array|string $parameters Parameters for the template
269
-	 * @return bool
270
-	 */
271
-	public static function printGuestPage($application, $name, $parameters = []) {
272
-		$content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest');
273
-		foreach( $parameters as $key => $value ) {
274
-			$content->assign( $key, $value );
275
-		}
276
-		return $content->printPage();
277
-	}
278
-
279
-	/**
280
-	 * Print a fatal error page and terminates the script
281
-	 * @param string $error_msg The error message to show
282
-	 * @param string $hint An optional hint message - needs to be properly escape
283
-	 * @param int $statusCode
284
-	 * @suppress PhanAccessMethodInternal
285
-	 */
286
-	public static function printErrorPage($error_msg, $hint = '', $statusCode = 500) {
287
-		if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) {
288
-			\OC_App::loadApp('theming');
289
-		}
290
-
291
-
292
-		if ($error_msg === $hint) {
293
-			// If the hint is the same as the message there is no need to display it twice.
294
-			$hint = '';
295
-		}
296
-
297
-		http_response_code($statusCode);
298
-		try {
299
-			$content = new \OC_Template( '', 'error', 'error', false );
300
-			$errors = [['error' => $error_msg, 'hint' => $hint]];
301
-			$content->assign( 'errors', $errors );
302
-			$content->printPage();
303
-		} catch (\Exception $e) {
304
-			$logger = \OC::$server->getLogger();
305
-			$logger->error("$error_msg $hint", ['app' => 'core']);
306
-			$logger->logException($e, ['app' => 'core']);
307
-
308
-			header('Content-Type: text/plain; charset=utf-8');
309
-			print("$error_msg $hint");
310
-		}
311
-		die();
312
-	}
313
-
314
-	/**
315
-	 * print error page using Exception details
316
-	 * @param Exception|Throwable $exception
317
-	 * @param int $statusCode
318
-	 * @return bool|string
319
-	 * @suppress PhanAccessMethodInternal
320
-	 */
321
-	public static function printExceptionErrorPage($exception, $statusCode = 503) {
322
-		http_response_code($statusCode);
323
-		try {
324
-			$request = \OC::$server->getRequest();
325
-			$content = new \OC_Template('', 'exception', 'error', false);
326
-			$content->assign('errorClass', get_class($exception));
327
-			$content->assign('errorMsg', $exception->getMessage());
328
-			$content->assign('errorCode', $exception->getCode());
329
-			$content->assign('file', $exception->getFile());
330
-			$content->assign('line', $exception->getLine());
331
-			$content->assign('trace', $exception->getTraceAsString());
332
-			$content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false));
333
-			$content->assign('remoteAddr', $request->getRemoteAddress());
334
-			$content->assign('requestID', $request->getId());
335
-			$content->printPage();
336
-		} catch (\Exception $e) {
337
-			try {
338
-				$logger = \OC::$server->getLogger();
339
-				$logger->logException($exception, ['app' => 'core']);
340
-				$logger->logException($e, ['app' => 'core']);
341
-			} catch (Throwable $e) {
342
-				// no way to log it properly - but to avoid a white page of death we send some output
343
-				header('Content-Type: text/plain; charset=utf-8');
344
-				print("Internal Server Error\n\n");
345
-				print("The server encountered an internal error and was unable to complete your request.\n");
346
-				print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
347
-				print("More details can be found in the server log.\n");
348
-
349
-				// and then throw it again to log it at least to the web server error log
350
-				throw $e;
351
-			}
352
-
353
-			header('Content-Type: text/plain; charset=utf-8');
354
-			print("Internal Server Error\n\n");
355
-			print("The server encountered an internal error and was unable to complete your request.\n");
356
-			print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
357
-			print("More details can be found in the server log.\n");
358
-		}
359
-		die();
360
-	}
50
+    /** @var string */
51
+    private $renderAs; // Create a full page?
52
+
53
+    /** @var string */
54
+    private $path; // The path to the template
55
+
56
+    /** @var array */
57
+    private $headers = []; //custom headers
58
+
59
+    /** @var string */
60
+    protected $app; // app id
61
+
62
+    protected static $initTemplateEngineFirstRun = true;
63
+
64
+    /**
65
+     * Constructor
66
+     *
67
+     * @param string $app app providing the template
68
+     * @param string $name of the template file (without suffix)
69
+     * @param string $renderAs If $renderAs is set, OC_Template will try to
70
+     *                         produce a full page in the according layout. For
71
+     *                         now, $renderAs can be set to "guest", "user" or
72
+     *                         "admin".
73
+     * @param bool $registerCall = true
74
+     */
75
+    public function __construct($app, $name, $renderAs = "", $registerCall = true) {
76
+        // Read the selected theme from the config file
77
+        self::initTemplateEngine($renderAs);
78
+
79
+        $theme = OC_Util::getTheme();
80
+
81
+        $requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
82
+
83
+        $parts = explode('/', $app); // fix translation when app is something like core/lostpassword
84
+        $l10n = \OC::$server->getL10N($parts[0]);
85
+        /** @var \OCP\Defaults $themeDefaults */
86
+        $themeDefaults = \OC::$server->query(\OCP\Defaults::class);
87
+
88
+        list($path, $template) = $this->findTemplate($theme, $app, $name);
89
+
90
+        // Set the private data
91
+        $this->renderAs = $renderAs;
92
+        $this->path = $path;
93
+        $this->app = $app;
94
+
95
+        parent::__construct($template, $requestToken, $l10n, $themeDefaults);
96
+    }
97
+
98
+    /**
99
+     * @param string $renderAs
100
+     */
101
+    public static function initTemplateEngine($renderAs) {
102
+        if (self::$initTemplateEngineFirstRun){
103
+
104
+            //apps that started before the template initialization can load their own scripts/styles
105
+            //so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
106
+            //meaning the last script/style in this list will be loaded first
107
+            if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
108
+                if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
109
+                    OC_Util::addScript ( 'backgroundjobs', null, true );
110
+                }
111
+            }
112
+            OC_Util::addStyle('css-variables', null, true);
113
+            OC_Util::addStyle('server', null, true);
114
+            OC_Util::addTranslations('core', null, true);
115
+
116
+            if (\OC::$server->getSystemConfig()->getValue ('installed', false)) {
117
+                OC_Util::addStyle('search', 'results');
118
+                OC_Util::addScript('search', 'search', true);
119
+                OC_Util::addScript('search', 'searchprovider');
120
+                OC_Util::addScript('merged-template-prepend', null, true);
121
+                OC_Util::addScript('files/fileinfo');
122
+                OC_Util::addScript('files/client');
123
+            }
124
+            OC_Util::addScript('core', 'dist/main', true);
125
+
126
+            if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
127
+                // shim for the davclient.js library
128
+                \OCP\Util::addScript('files/iedavclient');
129
+            }
130
+
131
+            self::$initTemplateEngineFirstRun = false;
132
+        }
133
+
134
+    }
135
+
136
+
137
+    /**
138
+     * find the template with the given name
139
+     * @param string $name of the template file (without suffix)
140
+     *
141
+     * Will select the template file for the selected theme.
142
+     * Checking all the possible locations.
143
+     * @param string $theme
144
+     * @param string $app
145
+     * @return string[]
146
+     */
147
+    protected function findTemplate($theme, $app, $name) {
148
+        // Check if it is a app template or not.
149
+        if( $app !== '' ) {
150
+            $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
151
+        } else {
152
+            $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
153
+        }
154
+        $locator = new \OC\Template\TemplateFileLocator( $dirs );
155
+        $template = $locator->find($name);
156
+        $path = $locator->getPath();
157
+        return [$path, $template];
158
+    }
159
+
160
+    /**
161
+     * Add a custom element to the header
162
+     * @param string $tag tag name of the element
163
+     * @param array $attributes array of attributes for the element
164
+     * @param string $text the text content for the element. If $text is null then the
165
+     * element will be written as empty element. So use "" to get a closing tag.
166
+     */
167
+    public function addHeader($tag, $attributes, $text=null) {
168
+        $this->headers[]= [
169
+            'tag' => $tag,
170
+            'attributes' => $attributes,
171
+            'text' => $text
172
+        ];
173
+    }
174
+
175
+    /**
176
+     * Process the template
177
+     * @return boolean|string
178
+     *
179
+     * This function process the template. If $this->renderAs is set, it
180
+     * will produce a full page.
181
+     */
182
+    public function fetchPage($additionalParams = null) {
183
+        $data = parent::fetchPage($additionalParams);
184
+
185
+        if( $this->renderAs ) {
186
+            $page = new TemplateLayout($this->renderAs, $this->app);
187
+
188
+            if(is_array($additionalParams)) {
189
+                foreach ($additionalParams as $key => $value) {
190
+                    $page->assign($key, $value);
191
+                }
192
+            }
193
+
194
+            // Add custom headers
195
+            $headers = '';
196
+            foreach(OC_Util::$headers as $header) {
197
+                $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
198
+                if ( strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes']))) ) {
199
+                    $headers .= ' defer';
200
+                }
201
+                foreach($header['attributes'] as $name=>$value) {
202
+                    $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
203
+                }
204
+                if ($header['text'] !== null) {
205
+                    $headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
206
+                } else {
207
+                    $headers .= '/>';
208
+                }
209
+            }
210
+
211
+            $page->assign('headers', $headers);
212
+
213
+            $page->assign('content', $data);
214
+            return $page->fetchPage($additionalParams);
215
+        }
216
+
217
+        return $data;
218
+    }
219
+
220
+    /**
221
+     * Include template
222
+     *
223
+     * @param string $file
224
+     * @param array|null $additionalParams
225
+     * @return string returns content of included template
226
+     *
227
+     * Includes another template. use <?php echo $this->inc('template'); ?> to
228
+     * do this.
229
+     */
230
+    public function inc($file, $additionalParams = null) {
231
+        return $this->load($this->path.$file.'.php', $additionalParams);
232
+    }
233
+
234
+    /**
235
+     * Shortcut to print a simple page for users
236
+     * @param string $application The application we render the template for
237
+     * @param string $name Name of the template
238
+     * @param array $parameters Parameters for the template
239
+     * @return boolean|null
240
+     */
241
+    public static function printUserPage($application, $name, $parameters = []) {
242
+        $content = new OC_Template( $application, $name, "user" );
243
+        foreach( $parameters as $key => $value ) {
244
+            $content->assign( $key, $value );
245
+        }
246
+        print $content->printPage();
247
+    }
248
+
249
+    /**
250
+     * Shortcut to print a simple page for admins
251
+     * @param string $application The application we render the template for
252
+     * @param string $name Name of the template
253
+     * @param array $parameters Parameters for the template
254
+     * @return bool
255
+     */
256
+    public static function printAdminPage($application, $name, $parameters = []) {
257
+        $content = new OC_Template( $application, $name, "admin" );
258
+        foreach( $parameters as $key => $value ) {
259
+            $content->assign( $key, $value );
260
+        }
261
+        return $content->printPage();
262
+    }
263
+
264
+    /**
265
+     * Shortcut to print a simple page for guests
266
+     * @param string $application The application we render the template for
267
+     * @param string $name Name of the template
268
+     * @param array|string $parameters Parameters for the template
269
+     * @return bool
270
+     */
271
+    public static function printGuestPage($application, $name, $parameters = []) {
272
+        $content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest');
273
+        foreach( $parameters as $key => $value ) {
274
+            $content->assign( $key, $value );
275
+        }
276
+        return $content->printPage();
277
+    }
278
+
279
+    /**
280
+     * Print a fatal error page and terminates the script
281
+     * @param string $error_msg The error message to show
282
+     * @param string $hint An optional hint message - needs to be properly escape
283
+     * @param int $statusCode
284
+     * @suppress PhanAccessMethodInternal
285
+     */
286
+    public static function printErrorPage($error_msg, $hint = '', $statusCode = 500) {
287
+        if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) {
288
+            \OC_App::loadApp('theming');
289
+        }
290
+
291
+
292
+        if ($error_msg === $hint) {
293
+            // If the hint is the same as the message there is no need to display it twice.
294
+            $hint = '';
295
+        }
296
+
297
+        http_response_code($statusCode);
298
+        try {
299
+            $content = new \OC_Template( '', 'error', 'error', false );
300
+            $errors = [['error' => $error_msg, 'hint' => $hint]];
301
+            $content->assign( 'errors', $errors );
302
+            $content->printPage();
303
+        } catch (\Exception $e) {
304
+            $logger = \OC::$server->getLogger();
305
+            $logger->error("$error_msg $hint", ['app' => 'core']);
306
+            $logger->logException($e, ['app' => 'core']);
307
+
308
+            header('Content-Type: text/plain; charset=utf-8');
309
+            print("$error_msg $hint");
310
+        }
311
+        die();
312
+    }
313
+
314
+    /**
315
+     * print error page using Exception details
316
+     * @param Exception|Throwable $exception
317
+     * @param int $statusCode
318
+     * @return bool|string
319
+     * @suppress PhanAccessMethodInternal
320
+     */
321
+    public static function printExceptionErrorPage($exception, $statusCode = 503) {
322
+        http_response_code($statusCode);
323
+        try {
324
+            $request = \OC::$server->getRequest();
325
+            $content = new \OC_Template('', 'exception', 'error', false);
326
+            $content->assign('errorClass', get_class($exception));
327
+            $content->assign('errorMsg', $exception->getMessage());
328
+            $content->assign('errorCode', $exception->getCode());
329
+            $content->assign('file', $exception->getFile());
330
+            $content->assign('line', $exception->getLine());
331
+            $content->assign('trace', $exception->getTraceAsString());
332
+            $content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false));
333
+            $content->assign('remoteAddr', $request->getRemoteAddress());
334
+            $content->assign('requestID', $request->getId());
335
+            $content->printPage();
336
+        } catch (\Exception $e) {
337
+            try {
338
+                $logger = \OC::$server->getLogger();
339
+                $logger->logException($exception, ['app' => 'core']);
340
+                $logger->logException($e, ['app' => 'core']);
341
+            } catch (Throwable $e) {
342
+                // no way to log it properly - but to avoid a white page of death we send some output
343
+                header('Content-Type: text/plain; charset=utf-8');
344
+                print("Internal Server Error\n\n");
345
+                print("The server encountered an internal error and was unable to complete your request.\n");
346
+                print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
347
+                print("More details can be found in the server log.\n");
348
+
349
+                // and then throw it again to log it at least to the web server error log
350
+                throw $e;
351
+            }
352
+
353
+            header('Content-Type: text/plain; charset=utf-8');
354
+            print("Internal Server Error\n\n");
355
+            print("The server encountered an internal error and was unable to complete your request.\n");
356
+            print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
357
+            print("More details can be found in the server log.\n");
358
+        }
359
+        die();
360
+    }
361 361
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -99,21 +99,21 @@  discard block
 block discarded – undo
99 99
 	 * @param string $renderAs
100 100
 	 */
101 101
 	public static function initTemplateEngine($renderAs) {
102
-		if (self::$initTemplateEngineFirstRun){
102
+		if (self::$initTemplateEngineFirstRun) {
103 103
 
104 104
 			//apps that started before the template initialization can load their own scripts/styles
105 105
 			//so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
106 106
 			//meaning the last script/style in this list will be loaded first
107
-			if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
108
-				if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
109
-					OC_Util::addScript ( 'backgroundjobs', null, true );
107
+			if (\OC::$server->getSystemConfig()->getValue('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
108
+				if (\OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
109
+					OC_Util::addScript('backgroundjobs', null, true);
110 110
 				}
111 111
 			}
112 112
 			OC_Util::addStyle('css-variables', null, true);
113 113
 			OC_Util::addStyle('server', null, true);
114 114
 			OC_Util::addTranslations('core', null, true);
115 115
 
116
-			if (\OC::$server->getSystemConfig()->getValue ('installed', false)) {
116
+			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
117 117
 				OC_Util::addStyle('search', 'results');
118 118
 				OC_Util::addScript('search', 'search', true);
119 119
 				OC_Util::addScript('search', 'searchprovider');
@@ -146,12 +146,12 @@  discard block
 block discarded – undo
146 146
 	 */
147 147
 	protected function findTemplate($theme, $app, $name) {
148 148
 		// Check if it is a app template or not.
149
-		if( $app !== '' ) {
149
+		if ($app !== '') {
150 150
 			$dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
151 151
 		} else {
152 152
 			$dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
153 153
 		}
154
-		$locator = new \OC\Template\TemplateFileLocator( $dirs );
154
+		$locator = new \OC\Template\TemplateFileLocator($dirs);
155 155
 		$template = $locator->find($name);
156 156
 		$path = $locator->getPath();
157 157
 		return [$path, $template];
@@ -164,8 +164,8 @@  discard block
 block discarded – undo
164 164
 	 * @param string $text the text content for the element. If $text is null then the
165 165
 	 * element will be written as empty element. So use "" to get a closing tag.
166 166
 	 */
167
-	public function addHeader($tag, $attributes, $text=null) {
168
-		$this->headers[]= [
167
+	public function addHeader($tag, $attributes, $text = null) {
168
+		$this->headers[] = [
169 169
 			'tag' => $tag,
170 170
 			'attributes' => $attributes,
171 171
 			'text' => $text
@@ -182,10 +182,10 @@  discard block
 block discarded – undo
182 182
 	public function fetchPage($additionalParams = null) {
183 183
 		$data = parent::fetchPage($additionalParams);
184 184
 
185
-		if( $this->renderAs ) {
185
+		if ($this->renderAs) {
186 186
 			$page = new TemplateLayout($this->renderAs, $this->app);
187 187
 
188
-			if(is_array($additionalParams)) {
188
+			if (is_array($additionalParams)) {
189 189
 				foreach ($additionalParams as $key => $value) {
190 190
 					$page->assign($key, $value);
191 191
 				}
@@ -193,12 +193,12 @@  discard block
 block discarded – undo
193 193
 
194 194
 			// Add custom headers
195 195
 			$headers = '';
196
-			foreach(OC_Util::$headers as $header) {
196
+			foreach (OC_Util::$headers as $header) {
197 197
 				$headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
198
-				if ( strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes']))) ) {
198
+				if (strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes'])))) {
199 199
 					$headers .= ' defer';
200 200
 				}
201
-				foreach($header['attributes'] as $name=>$value) {
201
+				foreach ($header['attributes'] as $name=>$value) {
202 202
 					$headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
203 203
 				}
204 204
 				if ($header['text'] !== null) {
@@ -239,9 +239,9 @@  discard block
 block discarded – undo
239 239
 	 * @return boolean|null
240 240
 	 */
241 241
 	public static function printUserPage($application, $name, $parameters = []) {
242
-		$content = new OC_Template( $application, $name, "user" );
243
-		foreach( $parameters as $key => $value ) {
244
-			$content->assign( $key, $value );
242
+		$content = new OC_Template($application, $name, "user");
243
+		foreach ($parameters as $key => $value) {
244
+			$content->assign($key, $value);
245 245
 		}
246 246
 		print $content->printPage();
247 247
 	}
@@ -254,9 +254,9 @@  discard block
 block discarded – undo
254 254
 	 * @return bool
255 255
 	 */
256 256
 	public static function printAdminPage($application, $name, $parameters = []) {
257
-		$content = new OC_Template( $application, $name, "admin" );
258
-		foreach( $parameters as $key => $value ) {
259
-			$content->assign( $key, $value );
257
+		$content = new OC_Template($application, $name, "admin");
258
+		foreach ($parameters as $key => $value) {
259
+			$content->assign($key, $value);
260 260
 		}
261 261
 		return $content->printPage();
262 262
 	}
@@ -270,8 +270,8 @@  discard block
 block discarded – undo
270 270
 	 */
271 271
 	public static function printGuestPage($application, $name, $parameters = []) {
272 272
 		$content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest');
273
-		foreach( $parameters as $key => $value ) {
274
-			$content->assign( $key, $value );
273
+		foreach ($parameters as $key => $value) {
274
+			$content->assign($key, $value);
275 275
 		}
276 276
 		return $content->printPage();
277 277
 	}
@@ -296,9 +296,9 @@  discard block
 block discarded – undo
296 296
 
297 297
 		http_response_code($statusCode);
298 298
 		try {
299
-			$content = new \OC_Template( '', 'error', 'error', false );
299
+			$content = new \OC_Template('', 'error', 'error', false);
300 300
 			$errors = [['error' => $error_msg, 'hint' => $hint]];
301
-			$content->assign( 'errors', $errors );
301
+			$content->assign('errors', $errors);
302 302
 			$content->printPage();
303 303
 		} catch (\Exception $e) {
304 304
 			$logger = \OC::$server->getLogger();
Please login to merge, or discard this patch.
lib/private/legacy/OC_Response.php 2 patches
Indentation   +73 added lines, -73 removed lines patch added patch discarded remove patch
@@ -28,81 +28,81 @@
 block discarded – undo
28 28
  */
29 29
 
30 30
 class OC_Response {
31
-	/**
32
-	 * Sets the content disposition header (with possible workarounds)
33
-	 * @param string $filename file name
34
-	 * @param string $type disposition type, either 'attachment' or 'inline'
35
-	 */
36
-	static public function setContentDispositionHeader($filename, $type = 'attachment') {
37
-		if (\OC::$server->getRequest()->isUserAgent(
38
-			[
39
-				\OC\AppFramework\Http\Request::USER_AGENT_IE,
40
-				\OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
41
-				\OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
42
-			])) {
43
-			header( 'Content-Disposition: ' . rawurlencode($type) . '; filename="' . rawurlencode( $filename ) . '"' );
44
-		} else {
45
-			header( 'Content-Disposition: ' . rawurlencode($type) . '; filename*=UTF-8\'\'' . rawurlencode( $filename )
46
-												 . '; filename="' . rawurlencode( $filename ) . '"' );
47
-		}
48
-	}
31
+    /**
32
+     * Sets the content disposition header (with possible workarounds)
33
+     * @param string $filename file name
34
+     * @param string $type disposition type, either 'attachment' or 'inline'
35
+     */
36
+    static public function setContentDispositionHeader($filename, $type = 'attachment') {
37
+        if (\OC::$server->getRequest()->isUserAgent(
38
+            [
39
+                \OC\AppFramework\Http\Request::USER_AGENT_IE,
40
+                \OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
41
+                \OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
42
+            ])) {
43
+            header( 'Content-Disposition: ' . rawurlencode($type) . '; filename="' . rawurlencode( $filename ) . '"' );
44
+        } else {
45
+            header( 'Content-Disposition: ' . rawurlencode($type) . '; filename*=UTF-8\'\'' . rawurlencode( $filename )
46
+                                                    . '; filename="' . rawurlencode( $filename ) . '"' );
47
+        }
48
+    }
49 49
 
50
-	/**
51
-	 * Sets the content length header (with possible workarounds)
52
-	 * @param string|int|float $length Length to be sent
53
-	 */
54
-	static public function setContentLengthHeader($length) {
55
-		if (PHP_INT_SIZE === 4) {
56
-			if ($length > PHP_INT_MAX && stripos(PHP_SAPI, 'apache') === 0) {
57
-				// Apache PHP SAPI casts Content-Length headers to PHP integers.
58
-				// This enforces a limit of PHP_INT_MAX (2147483647 on 32-bit
59
-				// platforms). So, if the length is greater than PHP_INT_MAX,
60
-				// we just do not send a Content-Length header to prevent
61
-				// bodies from being received incompletely.
62
-				return;
63
-			}
64
-			// Convert signed integer or float to unsigned base-10 string.
65
-			$lfh = new \OC\LargeFileHelper;
66
-			$length = $lfh->formatUnsignedInteger($length);
67
-		}
68
-		header('Content-Length: '.$length);
69
-	}
50
+    /**
51
+     * Sets the content length header (with possible workarounds)
52
+     * @param string|int|float $length Length to be sent
53
+     */
54
+    static public function setContentLengthHeader($length) {
55
+        if (PHP_INT_SIZE === 4) {
56
+            if ($length > PHP_INT_MAX && stripos(PHP_SAPI, 'apache') === 0) {
57
+                // Apache PHP SAPI casts Content-Length headers to PHP integers.
58
+                // This enforces a limit of PHP_INT_MAX (2147483647 on 32-bit
59
+                // platforms). So, if the length is greater than PHP_INT_MAX,
60
+                // we just do not send a Content-Length header to prevent
61
+                // bodies from being received incompletely.
62
+                return;
63
+            }
64
+            // Convert signed integer or float to unsigned base-10 string.
65
+            $lfh = new \OC\LargeFileHelper;
66
+            $length = $lfh->formatUnsignedInteger($length);
67
+        }
68
+        header('Content-Length: '.$length);
69
+    }
70 70
 
71
-	/**
72
-	 * This function adds some security related headers to all requests served via base.php
73
-	 * The implementation of this function has to happen here to ensure that all third-party
74
-	 * components (e.g. SabreDAV) also benefit from this headers.
75
-	 */
76
-	public static function addSecurityHeaders() {
77
-		/**
78
-		 * FIXME: Content Security Policy for legacy ownCloud components. This
79
-		 * can be removed once \OCP\AppFramework\Http\Response from the AppFramework
80
-		 * is used everywhere.
81
-		 * @see \OCP\AppFramework\Http\Response::getHeaders
82
-		 */
83
-		$policy = 'default-src \'self\'; '
84
-			. 'script-src \'self\' \'nonce-'.\OC::$server->getContentSecurityPolicyNonceManager()->getNonce().'\'; '
85
-			. 'style-src \'self\' \'unsafe-inline\'; '
86
-			. 'frame-src *; '
87
-			. 'img-src * data: blob:; '
88
-			. 'font-src \'self\' data:; '
89
-			. 'media-src *; '
90
-			. 'connect-src *; '
91
-			. 'object-src \'none\'; '
92
-			. 'base-uri \'self\'; ';
93
-		header('Content-Security-Policy:' . $policy);
71
+    /**
72
+     * This function adds some security related headers to all requests served via base.php
73
+     * The implementation of this function has to happen here to ensure that all third-party
74
+     * components (e.g. SabreDAV) also benefit from this headers.
75
+     */
76
+    public static function addSecurityHeaders() {
77
+        /**
78
+         * FIXME: Content Security Policy for legacy ownCloud components. This
79
+         * can be removed once \OCP\AppFramework\Http\Response from the AppFramework
80
+         * is used everywhere.
81
+         * @see \OCP\AppFramework\Http\Response::getHeaders
82
+         */
83
+        $policy = 'default-src \'self\'; '
84
+            . 'script-src \'self\' \'nonce-'.\OC::$server->getContentSecurityPolicyNonceManager()->getNonce().'\'; '
85
+            . 'style-src \'self\' \'unsafe-inline\'; '
86
+            . 'frame-src *; '
87
+            . 'img-src * data: blob:; '
88
+            . 'font-src \'self\' data:; '
89
+            . 'media-src *; '
90
+            . 'connect-src *; '
91
+            . 'object-src \'none\'; '
92
+            . 'base-uri \'self\'; ';
93
+        header('Content-Security-Policy:' . $policy);
94 94
 
95
-		// Send fallback headers for installations that don't have the possibility to send
96
-		// custom headers on the webserver side
97
-		if(getenv('modHeadersAvailable') !== 'true') {
98
-			header('Referrer-Policy: no-referrer'); // https://www.w3.org/TR/referrer-policy/
99
-			header('X-Content-Type-Options: nosniff'); // Disable sniffing the content type for IE
100
-			header('X-Download-Options: noopen'); // https://msdn.microsoft.com/en-us/library/jj542450(v=vs.85).aspx
101
-			header('X-Frame-Options: SAMEORIGIN'); // Disallow iFraming from other domains
102
-			header('X-Permitted-Cross-Domain-Policies: none'); // https://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html
103
-			header('X-Robots-Tag: none'); // https://developers.google.com/webmasters/control-crawl-index/docs/robots_meta_tag
104
-			header('X-XSS-Protection: 1; mode=block'); // Enforce browser based XSS filters
105
-		}
106
-	}
95
+        // Send fallback headers for installations that don't have the possibility to send
96
+        // custom headers on the webserver side
97
+        if(getenv('modHeadersAvailable') !== 'true') {
98
+            header('Referrer-Policy: no-referrer'); // https://www.w3.org/TR/referrer-policy/
99
+            header('X-Content-Type-Options: nosniff'); // Disable sniffing the content type for IE
100
+            header('X-Download-Options: noopen'); // https://msdn.microsoft.com/en-us/library/jj542450(v=vs.85).aspx
101
+            header('X-Frame-Options: SAMEORIGIN'); // Disallow iFraming from other domains
102
+            header('X-Permitted-Cross-Domain-Policies: none'); // https://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html
103
+            header('X-Robots-Tag: none'); // https://developers.google.com/webmasters/control-crawl-index/docs/robots_meta_tag
104
+            header('X-XSS-Protection: 1; mode=block'); // Enforce browser based XSS filters
105
+        }
106
+    }
107 107
 
108 108
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -40,10 +40,10 @@  discard block
 block discarded – undo
40 40
 				\OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
41 41
 				\OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
42 42
 			])) {
43
-			header( 'Content-Disposition: ' . rawurlencode($type) . '; filename="' . rawurlencode( $filename ) . '"' );
43
+			header('Content-Disposition: '.rawurlencode($type).'; filename="'.rawurlencode($filename).'"');
44 44
 		} else {
45
-			header( 'Content-Disposition: ' . rawurlencode($type) . '; filename*=UTF-8\'\'' . rawurlencode( $filename )
46
-												 . '; filename="' . rawurlencode( $filename ) . '"' );
45
+			header('Content-Disposition: '.rawurlencode($type).'; filename*=UTF-8\'\''.rawurlencode($filename)
46
+												 . '; filename="'.rawurlencode($filename).'"');
47 47
 		}
48 48
 	}
49 49
 
@@ -90,11 +90,11 @@  discard block
 block discarded – undo
90 90
 			. 'connect-src *; '
91 91
 			. 'object-src \'none\'; '
92 92
 			. 'base-uri \'self\'; ';
93
-		header('Content-Security-Policy:' . $policy);
93
+		header('Content-Security-Policy:'.$policy);
94 94
 
95 95
 		// Send fallback headers for installations that don't have the possibility to send
96 96
 		// custom headers on the webserver side
97
-		if(getenv('modHeadersAvailable') !== 'true') {
97
+		if (getenv('modHeadersAvailable') !== 'true') {
98 98
 			header('Referrer-Policy: no-referrer'); // https://www.w3.org/TR/referrer-policy/
99 99
 			header('X-Content-Type-Options: nosniff'); // Disable sniffing the content type for IE
100 100
 			header('X-Download-Options: noopen'); // https://msdn.microsoft.com/en-us/library/jj542450(v=vs.85).aspx
Please login to merge, or discard this patch.
lib/private/legacy/OC_Files.php 2 patches
Indentation   +380 added lines, -380 removed lines patch added patch discarded remove patch
@@ -50,385 +50,385 @@
 block discarded – undo
50 50
  *
51 51
  */
52 52
 class OC_Files {
53
-	const FILE = 1;
54
-	const ZIP_FILES = 2;
55
-	const ZIP_DIR = 3;
56
-
57
-	const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
58
-
59
-
60
-	private static $multipartBoundary = '';
61
-
62
-	/**
63
-	 * @return string
64
-	 */
65
-	private static function getBoundary() {
66
-		if (empty(self::$multipartBoundary)) {
67
-			self::$multipartBoundary = md5(mt_rand());
68
-		}
69
-		return self::$multipartBoundary;
70
-	}
71
-
72
-	/**
73
-	 * @param string $filename
74
-	 * @param string $name
75
-	 * @param array $rangeArray ('from'=>int,'to'=>int), ...
76
-	 */
77
-	private static function sendHeaders($filename, $name, array $rangeArray) {
78
-		OC_Response::setContentDispositionHeader($name, 'attachment');
79
-		header('Content-Transfer-Encoding: binary', true);
80
-		header('Pragma: public');// enable caching in IE
81
-		header('Expires: 0');
82
-		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
83
-		$fileSize = \OC\Files\Filesystem::filesize($filename);
84
-		$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
85
-		if ($fileSize > -1) {
86
-			if (!empty($rangeArray)) {
87
-				http_response_code(206);
88
-				header('Accept-Ranges: bytes', true);
89
-				if (count($rangeArray) > 1) {
90
-				$type = 'multipart/byteranges; boundary='.self::getBoundary();
91
-				// no Content-Length header here
92
-				}
93
-				else {
94
-				header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
95
-				OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
96
-				}
97
-			}
98
-			else {
99
-				OC_Response::setContentLengthHeader($fileSize);
100
-			}
101
-		}
102
-		header('Content-Type: '.$type, true);
103
-	}
104
-
105
-	/**
106
-	 * return the content of a file or return a zip file containing multiple files
107
-	 *
108
-	 * @param string $dir
109
-	 * @param string $files ; separated list of files to download
110
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
111
-	 */
112
-	public static function get($dir, $files, $params = null) {
113
-
114
-		$view = \OC\Files\Filesystem::getView();
115
-		$getType = self::FILE;
116
-		$filename = $dir;
117
-		try {
118
-
119
-			if (is_array($files) && count($files) === 1) {
120
-				$files = $files[0];
121
-			}
122
-
123
-			if (!is_array($files)) {
124
-				$filename = $dir . '/' . $files;
125
-				if (!$view->is_dir($filename)) {
126
-					self::getSingleFile($view, $dir, $files, is_null($params) ? [] : $params);
127
-					return;
128
-				}
129
-			}
130
-
131
-			$name = 'download';
132
-			if (is_array($files)) {
133
-				$getType = self::ZIP_FILES;
134
-				$basename = basename($dir);
135
-				if ($basename) {
136
-					$name = $basename;
137
-				}
138
-
139
-				$filename = $dir . '/' . $name;
140
-			} else {
141
-				$filename = $dir . '/' . $files;
142
-				$getType = self::ZIP_DIR;
143
-				// downloading root ?
144
-				if ($files !== '') {
145
-					$name = $files;
146
-				}
147
-			}
148
-
149
-			self::lockFiles($view, $dir, $files);
150
-
151
-			/* Calculate filesize and number of files */
152
-			if ($getType === self::ZIP_FILES) {
153
-				$fileInfos = [];
154
-				$fileSize = 0;
155
-				foreach ($files as $file) {
156
-					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
157
-					$fileSize += $fileInfo->getSize();
158
-					$fileInfos[] = $fileInfo;
159
-				}
160
-				$numberOfFiles = self::getNumberOfFiles($fileInfos);
161
-			} elseif ($getType === self::ZIP_DIR) {
162
-				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
163
-				$fileSize = $fileInfo->getSize();
164
-				$numberOfFiles = self::getNumberOfFiles([$fileInfo]);
165
-			}
166
-
167
-			$streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
168
-			OC_Util::obEnd();
169
-
170
-			$streamer->sendHeaders($name);
171
-			$executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
172
-			if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
173
-				@set_time_limit(0);
174
-			}
175
-			ignore_user_abort(true);
176
-
177
-			if ($getType === self::ZIP_FILES) {
178
-				foreach ($files as $file) {
179
-					$file = $dir . '/' . $file;
180
-					if (\OC\Files\Filesystem::is_file($file)) {
181
-						$userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
182
-						$file = $userFolder->get($file);
183
-						if($file instanceof \OC\Files\Node\File) {
184
-							try {
185
-								$fh = $file->fopen('r');
186
-							} catch (\OCP\Files\NotPermittedException $e) {
187
-								continue;
188
-							}
189
-							$fileSize = $file->getSize();
190
-							$fileTime = $file->getMTime();
191
-						} else {
192
-							// File is not a file? …
193
-							\OC::$server->getLogger()->debug(
194
-								'File given, but no Node available. Name {file}',
195
-								[ 'app' => 'files', 'file' => $file ]
196
-							);
197
-							continue;
198
-						}
199
-						$streamer->addFileFromStream($fh, $file->getName(), $fileSize, $fileTime);
200
-						fclose($fh);
201
-					} elseif (\OC\Files\Filesystem::is_dir($file)) {
202
-						$streamer->addDirRecursive($file);
203
-					}
204
-				}
205
-			} elseif ($getType === self::ZIP_DIR) {
206
-				$file = $dir . '/' . $files;
207
-				$streamer->addDirRecursive($file);
208
-			}
209
-			$streamer->finalize();
210
-			set_time_limit($executionTime);
211
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
212
-		} catch (\OCP\Lock\LockedException $ex) {
213
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
214
-			OC::$server->getLogger()->logException($ex);
215
-			$l = \OC::$server->getL10N('core');
216
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
217
-			\OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint, 200);
218
-		} catch (\OCP\Files\ForbiddenException $ex) {
219
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
220
-			OC::$server->getLogger()->logException($ex);
221
-			$l = \OC::$server->getL10N('core');
222
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage(), 200);
223
-		} catch (\Exception $ex) {
224
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
225
-			OC::$server->getLogger()->logException($ex);
226
-			$l = \OC::$server->getL10N('core');
227
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
228
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $hint, 200);
229
-		}
230
-	}
231
-
232
-	/**
233
-	 * @param string $rangeHeaderPos
234
-	 * @param int $fileSize
235
-	 * @return array $rangeArray ('from'=>int,'to'=>int), ...
236
-	 */
237
-	private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
238
-		$rArray=explode(',', $rangeHeaderPos);
239
-		$minOffset = 0;
240
-		$ind = 0;
241
-
242
-		$rangeArray = [];
243
-
244
-		foreach ($rArray as $value) {
245
-			$ranges = explode('-', $value);
246
-			if (is_numeric($ranges[0])) {
247
-				if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
248
-					$ranges[0] = $minOffset;
249
-				}
250
-				if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
251
-					$ind--;
252
-					$ranges[0] = $rangeArray[$ind]['from'];
253
-				}
254
-			}
255
-
256
-			if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
257
-				// case: x-x
258
-				if ($ranges[1] >= $fileSize) {
259
-					$ranges[1] = $fileSize-1;
260
-				}
261
-				$rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ];
262
-				$minOffset = $ranges[1] + 1;
263
-				if ($minOffset >= $fileSize) {
264
-					break;
265
-				}
266
-			}
267
-			elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
268
-				// case: x-
269
-				$rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize ];
270
-				break;
271
-			}
272
-			elseif (is_numeric($ranges[1])) {
273
-				// case: -x
274
-				if ($ranges[1] > $fileSize) {
275
-					$ranges[1] = $fileSize;
276
-				}
277
-				$rangeArray[$ind++] = [ 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize ];
278
-				break;
279
-			}
280
-		}
281
-		return $rangeArray;
282
-	}
283
-
284
-	/**
285
-	 * @param View $view
286
-	 * @param string $name
287
-	 * @param string $dir
288
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
289
-	 */
290
-	private static function getSingleFile($view, $dir, $name, $params) {
291
-		$filename = $dir . '/' . $name;
292
-		$file = null;
293
-
294
-		try {
295
-			$userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
296
-			$file = $userFolder->get($filename);
297
-			if(!$file instanceof \OC\Files\Node\File || !$file->isReadable()) {
298
-				http_response_code(403);
299
-				die('403 Forbidden');
300
-			}
301
-			$fileSize = $file->getSize();
302
-		} catch (\OCP\Files\NotPermittedException $e) {
303
-			http_response_code(403);
304
-			die('403 Forbidden');
305
-		} catch (\OCP\Files\InvalidPathException $e) {
306
-			http_response_code(403);
307
-			die('403 Forbidden');
308
-		} catch (\OCP\Files\NotFoundException $e) {
309
-			http_response_code(404);
310
-			$tmpl = new OC_Template('', '404', 'guest');
311
-			$tmpl->printPage();
312
-			exit();
313
-		}
314
-
315
-		OC_Util::obEnd();
316
-		$view->lockFile($filename, ILockingProvider::LOCK_SHARED);
317
-
318
-		$rangeArray = [];
319
-
320
-		if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
321
-			$rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), $fileSize);
322
-		}
323
-
324
-		self::sendHeaders($filename, $name, $rangeArray);
325
-
326
-		if (isset($params['head']) && $params['head']) {
327
-			return;
328
-		}
329
-
330
-		if (!empty($rangeArray)) {
331
-			try {
332
-				if (count($rangeArray) == 1) {
333
-				$view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
334
-				}
335
-				else {
336
-				// check if file is seekable (if not throw UnseekableException)
337
-				// we have to check it before body contents
338
-				$view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
339
-
340
-				$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
341
-
342
-				foreach ($rangeArray as $range) {
343
-					echo "\r\n--".self::getBoundary()."\r\n".
344
-						 "Content-type: ".$type."\r\n".
345
-						 "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
346
-					$view->readfilePart($filename, $range['from'], $range['to']);
347
-				}
348
-				echo "\r\n--".self::getBoundary()."--\r\n";
349
-				}
350
-			} catch (\OCP\Files\UnseekableException $ex) {
351
-				// file is unseekable
352
-				header_remove('Accept-Ranges');
353
-				header_remove('Content-Range');
354
-				http_response_code(200);
355
-				self::sendHeaders($filename, $name, []);
356
-				$view->readfile($filename);
357
-			}
358
-		}
359
-		else {
360
-			$view->readfile($filename);
361
-		}
362
-	}
363
-
364
-	/**
365
-	 * Returns the total (recursive) number of files and folders in the given
366
-	 * FileInfos.
367
-	 *
368
-	 * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
369
-	 * @return int the total number of files and folders
370
-	 */
371
-	private static function getNumberOfFiles($fileInfos) {
372
-		$numberOfFiles = 0;
373
-
374
-		$view = new View();
375
-
376
-		while ($fileInfo = array_pop($fileInfos)) {
377
-			$numberOfFiles++;
378
-
379
-			if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
380
-				$fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
381
-			}
382
-		}
383
-
384
-		return $numberOfFiles;
385
-	}
386
-
387
-	/**
388
-	 * @param View $view
389
-	 * @param string $dir
390
-	 * @param string[]|string $files
391
-	 */
392
-	public static function lockFiles($view, $dir, $files) {
393
-		if (!is_array($files)) {
394
-			$file = $dir . '/' . $files;
395
-			$files = [$file];
396
-		}
397
-		foreach ($files as $file) {
398
-			$file = $dir . '/' . $file;
399
-			$view->lockFile($file, ILockingProvider::LOCK_SHARED);
400
-			if ($view->is_dir($file)) {
401
-				$contents = $view->getDirectoryContent($file);
402
-				$contents = array_map(function ($fileInfo) use ($file) {
403
-					/** @var \OCP\Files\FileInfo $fileInfo */
404
-					return $file . '/' . $fileInfo->getName();
405
-				}, $contents);
406
-				self::lockFiles($view, $dir, $contents);
407
-			}
408
-		}
409
-	}
410
-
411
-	/**
412
-	 * @param string $dir
413
-	 * @param $files
414
-	 * @param integer $getType
415
-	 * @param View $view
416
-	 * @param string $filename
417
-	 */
418
-	private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
419
-		if ($getType === self::FILE) {
420
-			$view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
421
-		}
422
-		if ($getType === self::ZIP_FILES) {
423
-			foreach ($files as $file) {
424
-				$file = $dir . '/' . $file;
425
-				$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
426
-			}
427
-		}
428
-		if ($getType === self::ZIP_DIR) {
429
-			$file = $dir . '/' . $files;
430
-			$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
431
-		}
432
-	}
53
+    const FILE = 1;
54
+    const ZIP_FILES = 2;
55
+    const ZIP_DIR = 3;
56
+
57
+    const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
58
+
59
+
60
+    private static $multipartBoundary = '';
61
+
62
+    /**
63
+     * @return string
64
+     */
65
+    private static function getBoundary() {
66
+        if (empty(self::$multipartBoundary)) {
67
+            self::$multipartBoundary = md5(mt_rand());
68
+        }
69
+        return self::$multipartBoundary;
70
+    }
71
+
72
+    /**
73
+     * @param string $filename
74
+     * @param string $name
75
+     * @param array $rangeArray ('from'=>int,'to'=>int), ...
76
+     */
77
+    private static function sendHeaders($filename, $name, array $rangeArray) {
78
+        OC_Response::setContentDispositionHeader($name, 'attachment');
79
+        header('Content-Transfer-Encoding: binary', true);
80
+        header('Pragma: public');// enable caching in IE
81
+        header('Expires: 0');
82
+        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
83
+        $fileSize = \OC\Files\Filesystem::filesize($filename);
84
+        $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
85
+        if ($fileSize > -1) {
86
+            if (!empty($rangeArray)) {
87
+                http_response_code(206);
88
+                header('Accept-Ranges: bytes', true);
89
+                if (count($rangeArray) > 1) {
90
+                $type = 'multipart/byteranges; boundary='.self::getBoundary();
91
+                // no Content-Length header here
92
+                }
93
+                else {
94
+                header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
95
+                OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
96
+                }
97
+            }
98
+            else {
99
+                OC_Response::setContentLengthHeader($fileSize);
100
+            }
101
+        }
102
+        header('Content-Type: '.$type, true);
103
+    }
104
+
105
+    /**
106
+     * return the content of a file or return a zip file containing multiple files
107
+     *
108
+     * @param string $dir
109
+     * @param string $files ; separated list of files to download
110
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
111
+     */
112
+    public static function get($dir, $files, $params = null) {
113
+
114
+        $view = \OC\Files\Filesystem::getView();
115
+        $getType = self::FILE;
116
+        $filename = $dir;
117
+        try {
118
+
119
+            if (is_array($files) && count($files) === 1) {
120
+                $files = $files[0];
121
+            }
122
+
123
+            if (!is_array($files)) {
124
+                $filename = $dir . '/' . $files;
125
+                if (!$view->is_dir($filename)) {
126
+                    self::getSingleFile($view, $dir, $files, is_null($params) ? [] : $params);
127
+                    return;
128
+                }
129
+            }
130
+
131
+            $name = 'download';
132
+            if (is_array($files)) {
133
+                $getType = self::ZIP_FILES;
134
+                $basename = basename($dir);
135
+                if ($basename) {
136
+                    $name = $basename;
137
+                }
138
+
139
+                $filename = $dir . '/' . $name;
140
+            } else {
141
+                $filename = $dir . '/' . $files;
142
+                $getType = self::ZIP_DIR;
143
+                // downloading root ?
144
+                if ($files !== '') {
145
+                    $name = $files;
146
+                }
147
+            }
148
+
149
+            self::lockFiles($view, $dir, $files);
150
+
151
+            /* Calculate filesize and number of files */
152
+            if ($getType === self::ZIP_FILES) {
153
+                $fileInfos = [];
154
+                $fileSize = 0;
155
+                foreach ($files as $file) {
156
+                    $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
157
+                    $fileSize += $fileInfo->getSize();
158
+                    $fileInfos[] = $fileInfo;
159
+                }
160
+                $numberOfFiles = self::getNumberOfFiles($fileInfos);
161
+            } elseif ($getType === self::ZIP_DIR) {
162
+                $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
163
+                $fileSize = $fileInfo->getSize();
164
+                $numberOfFiles = self::getNumberOfFiles([$fileInfo]);
165
+            }
166
+
167
+            $streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
168
+            OC_Util::obEnd();
169
+
170
+            $streamer->sendHeaders($name);
171
+            $executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
172
+            if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
173
+                @set_time_limit(0);
174
+            }
175
+            ignore_user_abort(true);
176
+
177
+            if ($getType === self::ZIP_FILES) {
178
+                foreach ($files as $file) {
179
+                    $file = $dir . '/' . $file;
180
+                    if (\OC\Files\Filesystem::is_file($file)) {
181
+                        $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
182
+                        $file = $userFolder->get($file);
183
+                        if($file instanceof \OC\Files\Node\File) {
184
+                            try {
185
+                                $fh = $file->fopen('r');
186
+                            } catch (\OCP\Files\NotPermittedException $e) {
187
+                                continue;
188
+                            }
189
+                            $fileSize = $file->getSize();
190
+                            $fileTime = $file->getMTime();
191
+                        } else {
192
+                            // File is not a file? …
193
+                            \OC::$server->getLogger()->debug(
194
+                                'File given, but no Node available. Name {file}',
195
+                                [ 'app' => 'files', 'file' => $file ]
196
+                            );
197
+                            continue;
198
+                        }
199
+                        $streamer->addFileFromStream($fh, $file->getName(), $fileSize, $fileTime);
200
+                        fclose($fh);
201
+                    } elseif (\OC\Files\Filesystem::is_dir($file)) {
202
+                        $streamer->addDirRecursive($file);
203
+                    }
204
+                }
205
+            } elseif ($getType === self::ZIP_DIR) {
206
+                $file = $dir . '/' . $files;
207
+                $streamer->addDirRecursive($file);
208
+            }
209
+            $streamer->finalize();
210
+            set_time_limit($executionTime);
211
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
212
+        } catch (\OCP\Lock\LockedException $ex) {
213
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
214
+            OC::$server->getLogger()->logException($ex);
215
+            $l = \OC::$server->getL10N('core');
216
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
217
+            \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint, 200);
218
+        } catch (\OCP\Files\ForbiddenException $ex) {
219
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
220
+            OC::$server->getLogger()->logException($ex);
221
+            $l = \OC::$server->getL10N('core');
222
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage(), 200);
223
+        } catch (\Exception $ex) {
224
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
225
+            OC::$server->getLogger()->logException($ex);
226
+            $l = \OC::$server->getL10N('core');
227
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
228
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint, 200);
229
+        }
230
+    }
231
+
232
+    /**
233
+     * @param string $rangeHeaderPos
234
+     * @param int $fileSize
235
+     * @return array $rangeArray ('from'=>int,'to'=>int), ...
236
+     */
237
+    private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
238
+        $rArray=explode(',', $rangeHeaderPos);
239
+        $minOffset = 0;
240
+        $ind = 0;
241
+
242
+        $rangeArray = [];
243
+
244
+        foreach ($rArray as $value) {
245
+            $ranges = explode('-', $value);
246
+            if (is_numeric($ranges[0])) {
247
+                if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
248
+                    $ranges[0] = $minOffset;
249
+                }
250
+                if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
251
+                    $ind--;
252
+                    $ranges[0] = $rangeArray[$ind]['from'];
253
+                }
254
+            }
255
+
256
+            if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
257
+                // case: x-x
258
+                if ($ranges[1] >= $fileSize) {
259
+                    $ranges[1] = $fileSize-1;
260
+                }
261
+                $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ];
262
+                $minOffset = $ranges[1] + 1;
263
+                if ($minOffset >= $fileSize) {
264
+                    break;
265
+                }
266
+            }
267
+            elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
268
+                // case: x-
269
+                $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize ];
270
+                break;
271
+            }
272
+            elseif (is_numeric($ranges[1])) {
273
+                // case: -x
274
+                if ($ranges[1] > $fileSize) {
275
+                    $ranges[1] = $fileSize;
276
+                }
277
+                $rangeArray[$ind++] = [ 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize ];
278
+                break;
279
+            }
280
+        }
281
+        return $rangeArray;
282
+    }
283
+
284
+    /**
285
+     * @param View $view
286
+     * @param string $name
287
+     * @param string $dir
288
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
289
+     */
290
+    private static function getSingleFile($view, $dir, $name, $params) {
291
+        $filename = $dir . '/' . $name;
292
+        $file = null;
293
+
294
+        try {
295
+            $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
296
+            $file = $userFolder->get($filename);
297
+            if(!$file instanceof \OC\Files\Node\File || !$file->isReadable()) {
298
+                http_response_code(403);
299
+                die('403 Forbidden');
300
+            }
301
+            $fileSize = $file->getSize();
302
+        } catch (\OCP\Files\NotPermittedException $e) {
303
+            http_response_code(403);
304
+            die('403 Forbidden');
305
+        } catch (\OCP\Files\InvalidPathException $e) {
306
+            http_response_code(403);
307
+            die('403 Forbidden');
308
+        } catch (\OCP\Files\NotFoundException $e) {
309
+            http_response_code(404);
310
+            $tmpl = new OC_Template('', '404', 'guest');
311
+            $tmpl->printPage();
312
+            exit();
313
+        }
314
+
315
+        OC_Util::obEnd();
316
+        $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
317
+
318
+        $rangeArray = [];
319
+
320
+        if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
321
+            $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), $fileSize);
322
+        }
323
+
324
+        self::sendHeaders($filename, $name, $rangeArray);
325
+
326
+        if (isset($params['head']) && $params['head']) {
327
+            return;
328
+        }
329
+
330
+        if (!empty($rangeArray)) {
331
+            try {
332
+                if (count($rangeArray) == 1) {
333
+                $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
334
+                }
335
+                else {
336
+                // check if file is seekable (if not throw UnseekableException)
337
+                // we have to check it before body contents
338
+                $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
339
+
340
+                $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
341
+
342
+                foreach ($rangeArray as $range) {
343
+                    echo "\r\n--".self::getBoundary()."\r\n".
344
+                            "Content-type: ".$type."\r\n".
345
+                            "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
346
+                    $view->readfilePart($filename, $range['from'], $range['to']);
347
+                }
348
+                echo "\r\n--".self::getBoundary()."--\r\n";
349
+                }
350
+            } catch (\OCP\Files\UnseekableException $ex) {
351
+                // file is unseekable
352
+                header_remove('Accept-Ranges');
353
+                header_remove('Content-Range');
354
+                http_response_code(200);
355
+                self::sendHeaders($filename, $name, []);
356
+                $view->readfile($filename);
357
+            }
358
+        }
359
+        else {
360
+            $view->readfile($filename);
361
+        }
362
+    }
363
+
364
+    /**
365
+     * Returns the total (recursive) number of files and folders in the given
366
+     * FileInfos.
367
+     *
368
+     * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
369
+     * @return int the total number of files and folders
370
+     */
371
+    private static function getNumberOfFiles($fileInfos) {
372
+        $numberOfFiles = 0;
373
+
374
+        $view = new View();
375
+
376
+        while ($fileInfo = array_pop($fileInfos)) {
377
+            $numberOfFiles++;
378
+
379
+            if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
380
+                $fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
381
+            }
382
+        }
383
+
384
+        return $numberOfFiles;
385
+    }
386
+
387
+    /**
388
+     * @param View $view
389
+     * @param string $dir
390
+     * @param string[]|string $files
391
+     */
392
+    public static function lockFiles($view, $dir, $files) {
393
+        if (!is_array($files)) {
394
+            $file = $dir . '/' . $files;
395
+            $files = [$file];
396
+        }
397
+        foreach ($files as $file) {
398
+            $file = $dir . '/' . $file;
399
+            $view->lockFile($file, ILockingProvider::LOCK_SHARED);
400
+            if ($view->is_dir($file)) {
401
+                $contents = $view->getDirectoryContent($file);
402
+                $contents = array_map(function ($fileInfo) use ($file) {
403
+                    /** @var \OCP\Files\FileInfo $fileInfo */
404
+                    return $file . '/' . $fileInfo->getName();
405
+                }, $contents);
406
+                self::lockFiles($view, $dir, $contents);
407
+            }
408
+        }
409
+    }
410
+
411
+    /**
412
+     * @param string $dir
413
+     * @param $files
414
+     * @param integer $getType
415
+     * @param View $view
416
+     * @param string $filename
417
+     */
418
+    private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
419
+        if ($getType === self::FILE) {
420
+            $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
421
+        }
422
+        if ($getType === self::ZIP_FILES) {
423
+            foreach ($files as $file) {
424
+                $file = $dir . '/' . $file;
425
+                $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
426
+            }
427
+        }
428
+        if ($getType === self::ZIP_DIR) {
429
+            $file = $dir . '/' . $files;
430
+            $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
431
+        }
432
+    }
433 433
 
434 434
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 	private static function sendHeaders($filename, $name, array $rangeArray) {
78 78
 		OC_Response::setContentDispositionHeader($name, 'attachment');
79 79
 		header('Content-Transfer-Encoding: binary', true);
80
-		header('Pragma: public');// enable caching in IE
80
+		header('Pragma: public'); // enable caching in IE
81 81
 		header('Expires: 0');
82 82
 		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
83 83
 		$fileSize = \OC\Files\Filesystem::filesize($filename);
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 			}
122 122
 
123 123
 			if (!is_array($files)) {
124
-				$filename = $dir . '/' . $files;
124
+				$filename = $dir.'/'.$files;
125 125
 				if (!$view->is_dir($filename)) {
126 126
 					self::getSingleFile($view, $dir, $files, is_null($params) ? [] : $params);
127 127
 					return;
@@ -136,9 +136,9 @@  discard block
 block discarded – undo
136 136
 					$name = $basename;
137 137
 				}
138 138
 
139
-				$filename = $dir . '/' . $name;
139
+				$filename = $dir.'/'.$name;
140 140
 			} else {
141
-				$filename = $dir . '/' . $files;
141
+				$filename = $dir.'/'.$files;
142 142
 				$getType = self::ZIP_DIR;
143 143
 				// downloading root ?
144 144
 				if ($files !== '') {
@@ -153,13 +153,13 @@  discard block
 block discarded – undo
153 153
 				$fileInfos = [];
154 154
 				$fileSize = 0;
155 155
 				foreach ($files as $file) {
156
-					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
156
+					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir.'/'.$file);
157 157
 					$fileSize += $fileInfo->getSize();
158 158
 					$fileInfos[] = $fileInfo;
159 159
 				}
160 160
 				$numberOfFiles = self::getNumberOfFiles($fileInfos);
161 161
 			} elseif ($getType === self::ZIP_DIR) {
162
-				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
162
+				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir.'/'.$files);
163 163
 				$fileSize = $fileInfo->getSize();
164 164
 				$numberOfFiles = self::getNumberOfFiles([$fileInfo]);
165 165
 			}
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 			OC_Util::obEnd();
169 169
 
170 170
 			$streamer->sendHeaders($name);
171
-			$executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
171
+			$executionTime = (int) OC::$server->getIniWrapper()->getNumeric('max_execution_time');
172 172
 			if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
173 173
 				@set_time_limit(0);
174 174
 			}
@@ -176,11 +176,11 @@  discard block
 block discarded – undo
176 176
 
177 177
 			if ($getType === self::ZIP_FILES) {
178 178
 				foreach ($files as $file) {
179
-					$file = $dir . '/' . $file;
179
+					$file = $dir.'/'.$file;
180 180
 					if (\OC\Files\Filesystem::is_file($file)) {
181 181
 						$userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
182 182
 						$file = $userFolder->get($file);
183
-						if($file instanceof \OC\Files\Node\File) {
183
+						if ($file instanceof \OC\Files\Node\File) {
184 184
 							try {
185 185
 								$fh = $file->fopen('r');
186 186
 							} catch (\OCP\Files\NotPermittedException $e) {
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 							// File is not a file? …
193 193
 							\OC::$server->getLogger()->debug(
194 194
 								'File given, but no Node available. Name {file}',
195
-								[ 'app' => 'files', 'file' => $file ]
195
+								['app' => 'files', 'file' => $file]
196 196
 							);
197 197
 							continue;
198 198
 						}
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
 					}
204 204
 				}
205 205
 			} elseif ($getType === self::ZIP_DIR) {
206
-				$file = $dir . '/' . $files;
206
+				$file = $dir.'/'.$files;
207 207
 				$streamer->addDirRecursive($file);
208 208
 			}
209 209
 			$streamer->finalize();
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 	 * @return array $rangeArray ('from'=>int,'to'=>int), ...
236 236
 	 */
237 237
 	private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
238
-		$rArray=explode(',', $rangeHeaderPos);
238
+		$rArray = explode(',', $rangeHeaderPos);
239 239
 		$minOffset = 0;
240 240
 		$ind = 0;
241 241
 
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 				if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
248 248
 					$ranges[0] = $minOffset;
249 249
 				}
250
-				if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
250
+				if ($ind > 0 && $rangeArray[$ind - 1]['to'] + 1 == $ranges[0]) { // case: bytes=500-600,601-999
251 251
 					$ind--;
252 252
 					$ranges[0] = $rangeArray[$ind]['from'];
253 253
 				}
@@ -256,9 +256,9 @@  discard block
 block discarded – undo
256 256
 			if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
257 257
 				// case: x-x
258 258
 				if ($ranges[1] >= $fileSize) {
259
-					$ranges[1] = $fileSize-1;
259
+					$ranges[1] = $fileSize - 1;
260 260
 				}
261
-				$rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ];
261
+				$rangeArray[$ind++] = ['from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize];
262 262
 				$minOffset = $ranges[1] + 1;
263 263
 				if ($minOffset >= $fileSize) {
264 264
 					break;
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 			}
267 267
 			elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
268 268
 				// case: x-
269
-				$rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize ];
269
+				$rangeArray[$ind++] = ['from' => $ranges[0], 'to' => $fileSize - 1, 'size' => $fileSize];
270 270
 				break;
271 271
 			}
272 272
 			elseif (is_numeric($ranges[1])) {
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
 				if ($ranges[1] > $fileSize) {
275 275
 					$ranges[1] = $fileSize;
276 276
 				}
277
-				$rangeArray[$ind++] = [ 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize ];
277
+				$rangeArray[$ind++] = ['from' => $fileSize - $ranges[1], 'to' => $fileSize - 1, 'size' => $fileSize];
278 278
 				break;
279 279
 			}
280 280
 		}
@@ -288,13 +288,13 @@  discard block
 block discarded – undo
288 288
 	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
289 289
 	 */
290 290
 	private static function getSingleFile($view, $dir, $name, $params) {
291
-		$filename = $dir . '/' . $name;
291
+		$filename = $dir.'/'.$name;
292 292
 		$file = null;
293 293
 
294 294
 		try {
295 295
 			$userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
296 296
 			$file = $userFolder->get($filename);
297
-			if(!$file instanceof \OC\Files\Node\File || !$file->isReadable()) {
297
+			if (!$file instanceof \OC\Files\Node\File || !$file->isReadable()) {
298 298
 				http_response_code(403);
299 299
 				die('403 Forbidden');
300 300
 			}
@@ -391,17 +391,17 @@  discard block
 block discarded – undo
391 391
 	 */
392 392
 	public static function lockFiles($view, $dir, $files) {
393 393
 		if (!is_array($files)) {
394
-			$file = $dir . '/' . $files;
394
+			$file = $dir.'/'.$files;
395 395
 			$files = [$file];
396 396
 		}
397 397
 		foreach ($files as $file) {
398
-			$file = $dir . '/' . $file;
398
+			$file = $dir.'/'.$file;
399 399
 			$view->lockFile($file, ILockingProvider::LOCK_SHARED);
400 400
 			if ($view->is_dir($file)) {
401 401
 				$contents = $view->getDirectoryContent($file);
402
-				$contents = array_map(function ($fileInfo) use ($file) {
402
+				$contents = array_map(function($fileInfo) use ($file) {
403 403
 					/** @var \OCP\Files\FileInfo $fileInfo */
404
-					return $file . '/' . $fileInfo->getName();
404
+					return $file.'/'.$fileInfo->getName();
405 405
 				}, $contents);
406 406
 				self::lockFiles($view, $dir, $contents);
407 407
 			}
@@ -421,12 +421,12 @@  discard block
 block discarded – undo
421 421
 		}
422 422
 		if ($getType === self::ZIP_FILES) {
423 423
 			foreach ($files as $file) {
424
-				$file = $dir . '/' . $file;
424
+				$file = $dir.'/'.$file;
425 425
 				$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
426 426
 			}
427 427
 		}
428 428
 		if ($getType === self::ZIP_DIR) {
429
-			$file = $dir . '/' . $files;
429
+			$file = $dir.'/'.$files;
430 430
 			$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
431 431
 		}
432 432
 	}
Please login to merge, or discard this patch.
lib/private/legacy/template/functions.php 2 patches
Indentation   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
  * @param string $string the string which will be escaped and printed
38 38
  */
39 39
 function p($string) {
40
-	print(\OCP\Util::sanitizeHTML($string));
40
+    print(\OCP\Util::sanitizeHTML($string));
41 41
 }
42 42
 
43 43
 
@@ -47,14 +47,14 @@  discard block
 block discarded – undo
47 47
  * @param string $opts, additional optional options
48 48
  */
49 49
 function emit_css_tag($href, $opts = '') {
50
-	$s='<link rel="stylesheet"';
51
-	if (!empty($href)) {
52
-		$s.=' href="' . $href .'"';
53
-	}
54
-	if (!empty($opts)) {
55
-		$s.=' '.$opts;
56
-	}
57
-	print_unescaped($s.">\n");
50
+    $s='<link rel="stylesheet"';
51
+    if (!empty($href)) {
52
+        $s.=' href="' . $href .'"';
53
+    }
54
+    if (!empty($opts)) {
55
+        $s.=' '.$opts;
56
+    }
57
+    print_unescaped($s.">\n");
58 58
 }
59 59
 
60 60
 /**
@@ -62,12 +62,12 @@  discard block
 block discarded – undo
62 62
  * @param array $obj all the script information from template
63 63
  */
64 64
 function emit_css_loading_tags($obj) {
65
-	foreach($obj['cssfiles'] as $css) {
66
-		emit_css_tag($css);
67
-	}
68
-	foreach($obj['printcssfiles'] as $css) {
69
-		emit_css_tag($css, 'media="print"');
70
-	}
65
+    foreach($obj['cssfiles'] as $css) {
66
+        emit_css_tag($css);
67
+    }
68
+    foreach($obj['printcssfiles'] as $css) {
69
+        emit_css_tag($css, 'media="print"');
70
+    }
71 71
 }
72 72
 
73 73
 /**
@@ -76,20 +76,20 @@  discard block
 block discarded – undo
76 76
  * @param string $script_content the inline script content, ignored when empty
77 77
  */
78 78
 function emit_script_tag($src, $script_content='') {
79
-	$defer_str=' defer';
80
-	$s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
81
-	if (!empty($src)) {
82
-		 // emit script tag for deferred loading from $src
83
-		$s.=$defer_str.' src="' . $src .'">';
84
-	} else if (!empty($script_content)) {
85
-		// emit script tag for inline script from $script_content without defer (see MDN)
86
-		$s.=">\n".$script_content."\n";
87
-	} else {
88
-		// no $src nor $src_content, really useless empty tag
89
-		$s.='>';
90
-	}
91
-	$s.='</script>';
92
-	print_unescaped($s."\n");
79
+    $defer_str=' defer';
80
+    $s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
81
+    if (!empty($src)) {
82
+            // emit script tag for deferred loading from $src
83
+        $s.=$defer_str.' src="' . $src .'">';
84
+    } else if (!empty($script_content)) {
85
+        // emit script tag for inline script from $script_content without defer (see MDN)
86
+        $s.=">\n".$script_content."\n";
87
+    } else {
88
+        // no $src nor $src_content, really useless empty tag
89
+        $s.='>';
90
+    }
91
+    $s.='</script>';
92
+    print_unescaped($s."\n");
93 93
 }
94 94
 
95 95
 /**
@@ -97,12 +97,12 @@  discard block
 block discarded – undo
97 97
  * @param array $obj all the script information from template
98 98
  */
99 99
 function emit_script_loading_tags($obj) {
100
-	foreach($obj['jsfiles'] as $jsfile) {
101
-		emit_script_tag($jsfile, '');
102
-	}
103
-	if (!empty($obj['inline_ocjs'])) {
104
-		emit_script_tag('', $obj['inline_ocjs']);
105
-	}
100
+    foreach($obj['jsfiles'] as $jsfile) {
101
+        emit_script_tag($jsfile, '');
102
+    }
103
+    if (!empty($obj['inline_ocjs'])) {
104
+        emit_script_tag('', $obj['inline_ocjs']);
105
+    }
106 106
 }
107 107
 
108 108
 /**
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
  * @param string|array $string the string which will be printed as it is
112 112
  */
113 113
 function print_unescaped($string) {
114
-	print($string);
114
+    print($string);
115 115
 }
116 116
 
117 117
 /**
@@ -121,13 +121,13 @@  discard block
 block discarded – undo
121 121
  * if an array is given it will add all scripts
122 122
  */
123 123
 function script($app, $file = null) {
124
-	if(is_array($file)) {
125
-		foreach($file as $f) {
126
-			OC_Util::addScript($app, $f);
127
-		}
128
-	} else {
129
-		OC_Util::addScript($app, $file);
130
-	}
124
+    if(is_array($file)) {
125
+        foreach($file as $f) {
126
+            OC_Util::addScript($app, $f);
127
+        }
128
+    } else {
129
+        OC_Util::addScript($app, $file);
130
+    }
131 131
 }
132 132
 
133 133
 /**
@@ -137,13 +137,13 @@  discard block
 block discarded – undo
137 137
  * if an array is given it will add all scripts
138 138
  */
139 139
 function vendor_script($app, $file = null) {
140
-	if(is_array($file)) {
141
-		foreach($file as $f) {
142
-			OC_Util::addVendorScript($app, $f);
143
-		}
144
-	} else {
145
-		OC_Util::addVendorScript($app, $file);
146
-	}
140
+    if(is_array($file)) {
141
+        foreach($file as $f) {
142
+            OC_Util::addVendorScript($app, $f);
143
+        }
144
+    } else {
145
+        OC_Util::addVendorScript($app, $file);
146
+    }
147 147
 }
148 148
 
149 149
 /**
@@ -153,13 +153,13 @@  discard block
 block discarded – undo
153 153
  * if an array is given it will add all styles
154 154
  */
155 155
 function style($app, $file = null) {
156
-	if(is_array($file)) {
157
-		foreach($file as $f) {
158
-			OC_Util::addStyle($app, $f);
159
-		}
160
-	} else {
161
-		OC_Util::addStyle($app, $file);
162
-	}
156
+    if(is_array($file)) {
157
+        foreach($file as $f) {
158
+            OC_Util::addStyle($app, $f);
159
+        }
160
+    } else {
161
+        OC_Util::addStyle($app, $file);
162
+    }
163 163
 }
164 164
 
165 165
 /**
@@ -169,13 +169,13 @@  discard block
 block discarded – undo
169 169
  * if an array is given it will add all styles
170 170
  */
171 171
 function vendor_style($app, $file = null) {
172
-	if(is_array($file)) {
173
-		foreach($file as $f) {
174
-			OC_Util::addVendorStyle($app, $f);
175
-		}
176
-	} else {
177
-		OC_Util::addVendorStyle($app, $file);
178
-	}
172
+    if(is_array($file)) {
173
+        foreach($file as $f) {
174
+            OC_Util::addVendorStyle($app, $f);
175
+        }
176
+    } else {
177
+        OC_Util::addVendorStyle($app, $file);
178
+    }
179 179
 }
180 180
 
181 181
 /**
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
  * if an array is given it will add all styles
185 185
  */
186 186
 function translation($app) {
187
-	OC_Util::addTranslations($app);
187
+    OC_Util::addTranslations($app);
188 188
 }
189 189
 
190 190
 /**
@@ -194,15 +194,15 @@  discard block
 block discarded – undo
194 194
  * if an array is given it will add all components
195 195
  */
196 196
 function component($app, $file) {
197
-	if(is_array($file)) {
198
-		foreach($file as $f) {
199
-			$url = link_to($app, 'component/' . $f . '.html');
200
-			OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
201
-		}
202
-	} else {
203
-		$url = link_to($app, 'component/' . $file . '.html');
204
-		OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
205
-	}
197
+    if(is_array($file)) {
198
+        foreach($file as $f) {
199
+            $url = link_to($app, 'component/' . $f . '.html');
200
+            OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
201
+        }
202
+    } else {
203
+        $url = link_to($app, 'component/' . $file . '.html');
204
+        OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
205
+    }
206 206
 }
207 207
 
208 208
 /**
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
  * For further information have a look at \OCP\IURLGenerator::linkTo
216 216
  */
217 217
 function link_to($app, $file, $args = []) {
218
-	return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
218
+    return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
219 219
 }
220 220
 
221 221
 /**
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
  * @return string url to the online documentation
224 224
  */
225 225
 function link_to_docs($key) {
226
-	return \OC::$server->getURLGenerator()->linkToDocs($key);
226
+    return \OC::$server->getURLGenerator()->linkToDocs($key);
227 227
 }
228 228
 
229 229
 /**
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
  * For further information have a look at \OCP\IURLGenerator::imagePath
236 236
  */
237 237
 function image_path($app, $image) {
238
-	return \OC::$server->getURLGenerator()->imagePath( $app, $image );
238
+    return \OC::$server->getURLGenerator()->imagePath( $app, $image );
239 239
 }
240 240
 
241 241
 /**
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
  * @return string link to the image
245 245
  */
246 246
 function mimetype_icon($mimetype) {
247
-	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
247
+    return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
248 248
 }
249 249
 
250 250
 /**
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
  * @return string link to the preview
255 255
  */
256 256
 function preview_icon($path) {
257
-	return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
257
+    return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
258 258
 }
259 259
 
260 260
 /**
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
  * @return string
264 264
  */
265 265
 function publicPreview_icon($path, $token) {
266
-	return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 'token' => $token]);
266
+    return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 'token' => $token]);
267 267
 }
268 268
 
269 269
 /**
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
  * For further information have a look at OC_Helper::humanFileSize
275 275
  */
276 276
 function human_file_size($bytes) {
277
-	return OC_Helper::humanFileSize( $bytes );
277
+    return OC_Helper::humanFileSize( $bytes );
278 278
 }
279 279
 
280 280
 /**
@@ -283,9 +283,9 @@  discard block
 block discarded – undo
283 283
  * @return int timestamp without time value
284 284
  */
285 285
 function strip_time($timestamp) {
286
-	$date = new \DateTime("@{$timestamp}");
287
-	$date->setTime(0, 0, 0);
288
-	return (int)$date->format('U');
286
+    $date = new \DateTime("@{$timestamp}");
287
+    $date->setTime(0, 0, 0);
288
+    return (int)$date->format('U');
289 289
 }
290 290
 
291 291
 /**
@@ -297,39 +297,39 @@  discard block
 block discarded – undo
297 297
  * @return string timestamp
298 298
  */
299 299
 function relative_modified_date($timestamp, $fromTime = null, $dateOnly = false) {
300
-	/** @var \OC\DateTimeFormatter $formatter */
301
-	$formatter = \OC::$server->query('DateTimeFormatter');
300
+    /** @var \OC\DateTimeFormatter $formatter */
301
+    $formatter = \OC::$server->query('DateTimeFormatter');
302 302
 
303
-	if ($dateOnly){
304
-		return $formatter->formatDateSpan($timestamp, $fromTime);
305
-	}
306
-	return $formatter->formatTimeSpan($timestamp, $fromTime);
303
+    if ($dateOnly){
304
+        return $formatter->formatDateSpan($timestamp, $fromTime);
305
+    }
306
+    return $formatter->formatTimeSpan($timestamp, $fromTime);
307 307
 }
308 308
 
309 309
 function html_select_options($options, $selected, $params=[]) {
310
-	if (!is_array($selected)) {
311
-		$selected=[$selected];
312
-	}
313
-	if (isset($params['combine']) && $params['combine']) {
314
-		$options = array_combine($options, $options);
315
-	}
316
-	$value_name = $label_name = false;
317
-	if (isset($params['value'])) {
318
-		$value_name = $params['value'];
319
-	}
320
-	if (isset($params['label'])) {
321
-		$label_name = $params['label'];
322
-	}
323
-	$html = '';
324
-	foreach($options as $value => $label) {
325
-		if ($value_name && is_array($label)) {
326
-			$value = $label[$value_name];
327
-		}
328
-		if ($label_name && is_array($label)) {
329
-			$label = $label[$label_name];
330
-		}
331
-		$select = in_array($value, $selected) ? ' selected="selected"' : '';
332
-		$html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
333
-	}
334
-	return $html;
310
+    if (!is_array($selected)) {
311
+        $selected=[$selected];
312
+    }
313
+    if (isset($params['combine']) && $params['combine']) {
314
+        $options = array_combine($options, $options);
315
+    }
316
+    $value_name = $label_name = false;
317
+    if (isset($params['value'])) {
318
+        $value_name = $params['value'];
319
+    }
320
+    if (isset($params['label'])) {
321
+        $label_name = $params['label'];
322
+    }
323
+    $html = '';
324
+    foreach($options as $value => $label) {
325
+        if ($value_name && is_array($label)) {
326
+            $value = $label[$value_name];
327
+        }
328
+        if ($label_name && is_array($label)) {
329
+            $label = $label[$label_name];
330
+        }
331
+        $select = in_array($value, $selected) ? ' selected="selected"' : '';
332
+        $html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
333
+    }
334
+    return $html;
335 335
 }
Please login to merge, or discard this patch.
Spacing   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -47,12 +47,12 @@  discard block
 block discarded – undo
47 47
  * @param string $opts, additional optional options
48 48
  */
49 49
 function emit_css_tag($href, $opts = '') {
50
-	$s='<link rel="stylesheet"';
50
+	$s = '<link rel="stylesheet"';
51 51
 	if (!empty($href)) {
52
-		$s.=' href="' . $href .'"';
52
+		$s .= ' href="'.$href.'"';
53 53
 	}
54 54
 	if (!empty($opts)) {
55
-		$s.=' '.$opts;
55
+		$s .= ' '.$opts;
56 56
 	}
57 57
 	print_unescaped($s.">\n");
58 58
 }
@@ -62,10 +62,10 @@  discard block
 block discarded – undo
62 62
  * @param array $obj all the script information from template
63 63
  */
64 64
 function emit_css_loading_tags($obj) {
65
-	foreach($obj['cssfiles'] as $css) {
65
+	foreach ($obj['cssfiles'] as $css) {
66 66
 		emit_css_tag($css);
67 67
 	}
68
-	foreach($obj['printcssfiles'] as $css) {
68
+	foreach ($obj['printcssfiles'] as $css) {
69 69
 		emit_css_tag($css, 'media="print"');
70 70
 	}
71 71
 }
@@ -75,20 +75,20 @@  discard block
 block discarded – undo
75 75
  * @param string $src the source URL, ignored when empty
76 76
  * @param string $script_content the inline script content, ignored when empty
77 77
  */
78
-function emit_script_tag($src, $script_content='') {
79
-	$defer_str=' defer';
80
-	$s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
78
+function emit_script_tag($src, $script_content = '') {
79
+	$defer_str = ' defer';
80
+	$s = '<script nonce="'.\OC::$server->getContentSecurityPolicyNonceManager()->getNonce().'"';
81 81
 	if (!empty($src)) {
82 82
 		 // emit script tag for deferred loading from $src
83
-		$s.=$defer_str.' src="' . $src .'">';
83
+		$s .= $defer_str.' src="'.$src.'">';
84 84
 	} else if (!empty($script_content)) {
85 85
 		// emit script tag for inline script from $script_content without defer (see MDN)
86
-		$s.=">\n".$script_content."\n";
86
+		$s .= ">\n".$script_content."\n";
87 87
 	} else {
88 88
 		// no $src nor $src_content, really useless empty tag
89
-		$s.='>';
89
+		$s .= '>';
90 90
 	}
91
-	$s.='</script>';
91
+	$s .= '</script>';
92 92
 	print_unescaped($s."\n");
93 93
 }
94 94
 
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
  * @param array $obj all the script information from template
98 98
  */
99 99
 function emit_script_loading_tags($obj) {
100
-	foreach($obj['jsfiles'] as $jsfile) {
100
+	foreach ($obj['jsfiles'] as $jsfile) {
101 101
 		emit_script_tag($jsfile, '');
102 102
 	}
103 103
 	if (!empty($obj['inline_ocjs'])) {
@@ -121,8 +121,8 @@  discard block
 block discarded – undo
121 121
  * if an array is given it will add all scripts
122 122
  */
123 123
 function script($app, $file = null) {
124
-	if(is_array($file)) {
125
-		foreach($file as $f) {
124
+	if (is_array($file)) {
125
+		foreach ($file as $f) {
126 126
 			OC_Util::addScript($app, $f);
127 127
 		}
128 128
 	} else {
@@ -137,8 +137,8 @@  discard block
 block discarded – undo
137 137
  * if an array is given it will add all scripts
138 138
  */
139 139
 function vendor_script($app, $file = null) {
140
-	if(is_array($file)) {
141
-		foreach($file as $f) {
140
+	if (is_array($file)) {
141
+		foreach ($file as $f) {
142 142
 			OC_Util::addVendorScript($app, $f);
143 143
 		}
144 144
 	} else {
@@ -153,8 +153,8 @@  discard block
 block discarded – undo
153 153
  * if an array is given it will add all styles
154 154
  */
155 155
 function style($app, $file = null) {
156
-	if(is_array($file)) {
157
-		foreach($file as $f) {
156
+	if (is_array($file)) {
157
+		foreach ($file as $f) {
158 158
 			OC_Util::addStyle($app, $f);
159 159
 		}
160 160
 	} else {
@@ -169,8 +169,8 @@  discard block
 block discarded – undo
169 169
  * if an array is given it will add all styles
170 170
  */
171 171
 function vendor_style($app, $file = null) {
172
-	if(is_array($file)) {
173
-		foreach($file as $f) {
172
+	if (is_array($file)) {
173
+		foreach ($file as $f) {
174 174
 			OC_Util::addVendorStyle($app, $f);
175 175
 		}
176 176
 	} else {
@@ -194,13 +194,13 @@  discard block
 block discarded – undo
194 194
  * if an array is given it will add all components
195 195
  */
196 196
 function component($app, $file) {
197
-	if(is_array($file)) {
198
-		foreach($file as $f) {
199
-			$url = link_to($app, 'component/' . $f . '.html');
197
+	if (is_array($file)) {
198
+		foreach ($file as $f) {
199
+			$url = link_to($app, 'component/'.$f.'.html');
200 200
 			OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
201 201
 		}
202 202
 	} else {
203
-		$url = link_to($app, 'component/' . $file . '.html');
203
+		$url = link_to($app, 'component/'.$file.'.html');
204 204
 		OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
205 205
 	}
206 206
 }
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
  * For further information have a look at \OCP\IURLGenerator::imagePath
236 236
  */
237 237
 function image_path($app, $image) {
238
-	return \OC::$server->getURLGenerator()->imagePath( $app, $image );
238
+	return \OC::$server->getURLGenerator()->imagePath($app, $image);
239 239
 }
240 240
 
241 241
 /**
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
  * @return string link to the image
245 245
  */
246 246
 function mimetype_icon($mimetype) {
247
-	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
247
+	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon($mimetype);
248 248
 }
249 249
 
250 250
 /**
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
  * For further information have a look at OC_Helper::humanFileSize
275 275
  */
276 276
 function human_file_size($bytes) {
277
-	return OC_Helper::humanFileSize( $bytes );
277
+	return OC_Helper::humanFileSize($bytes);
278 278
 }
279 279
 
280 280
 /**
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 function strip_time($timestamp) {
286 286
 	$date = new \DateTime("@{$timestamp}");
287 287
 	$date->setTime(0, 0, 0);
288
-	return (int)$date->format('U');
288
+	return (int) $date->format('U');
289 289
 }
290 290
 
291 291
 /**
@@ -300,15 +300,15 @@  discard block
 block discarded – undo
300 300
 	/** @var \OC\DateTimeFormatter $formatter */
301 301
 	$formatter = \OC::$server->query('DateTimeFormatter');
302 302
 
303
-	if ($dateOnly){
303
+	if ($dateOnly) {
304 304
 		return $formatter->formatDateSpan($timestamp, $fromTime);
305 305
 	}
306 306
 	return $formatter->formatTimeSpan($timestamp, $fromTime);
307 307
 }
308 308
 
309
-function html_select_options($options, $selected, $params=[]) {
309
+function html_select_options($options, $selected, $params = []) {
310 310
 	if (!is_array($selected)) {
311
-		$selected=[$selected];
311
+		$selected = [$selected];
312 312
 	}
313 313
 	if (isset($params['combine']) && $params['combine']) {
314 314
 		$options = array_combine($options, $options);
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
 		$label_name = $params['label'];
322 322
 	}
323 323
 	$html = '';
324
-	foreach($options as $value => $label) {
324
+	foreach ($options as $value => $label) {
325 325
 		if ($value_name && is_array($label)) {
326 326
 			$value = $label[$value_name];
327 327
 		}
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
 			$label = $label[$label_name];
330 330
 		}
331 331
 		$select = in_array($value, $selected) ? ' selected="selected"' : '';
332
-		$html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
332
+		$html .= '<option value="'.\OCP\Util::sanitizeHTML($value).'"'.$select.'>'.\OCP\Util::sanitizeHTML($label).'</option>'."\n";
333 333
 	}
334 334
 	return $html;
335 335
 }
Please login to merge, or discard this patch.
lib/private/legacy/OC_DB.php 2 patches
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -38,209 +38,209 @@
 block discarded – undo
38 38
  */
39 39
 class OC_DB {
40 40
 
41
-	/**
42
-	 * get MDB2 schema manager
43
-	 *
44
-	 * @return \OC\DB\MDB2SchemaManager
45
-	 */
46
-	private static function getMDB2SchemaManager() {
47
-		return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
48
-	}
41
+    /**
42
+     * get MDB2 schema manager
43
+     *
44
+     * @return \OC\DB\MDB2SchemaManager
45
+     */
46
+    private static function getMDB2SchemaManager() {
47
+        return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
48
+    }
49 49
 
50
-	/**
51
-	 * Prepare a SQL query
52
-	 * @param string $query Query string
53
-	 * @param int|null $limit
54
-	 * @param int|null $offset
55
-	 * @param bool|null $isManipulation
56
-	 * @throws \OC\DatabaseException
57
-	 * @return OC_DB_StatementWrapper prepared SQL query
58
-	 *
59
-	 * SQL query via Doctrine prepare(), needs to be execute()'d!
60
-	 */
61
-	static public function prepare($query , $limit = null, $offset = null, $isManipulation = null) {
62
-		$connection = \OC::$server->getDatabaseConnection();
50
+    /**
51
+     * Prepare a SQL query
52
+     * @param string $query Query string
53
+     * @param int|null $limit
54
+     * @param int|null $offset
55
+     * @param bool|null $isManipulation
56
+     * @throws \OC\DatabaseException
57
+     * @return OC_DB_StatementWrapper prepared SQL query
58
+     *
59
+     * SQL query via Doctrine prepare(), needs to be execute()'d!
60
+     */
61
+    static public function prepare($query , $limit = null, $offset = null, $isManipulation = null) {
62
+        $connection = \OC::$server->getDatabaseConnection();
63 63
 
64
-		if ($isManipulation === null) {
65
-			//try to guess, so we return the number of rows on manipulations
66
-			$isManipulation = self::isManipulation($query);
67
-		}
64
+        if ($isManipulation === null) {
65
+            //try to guess, so we return the number of rows on manipulations
66
+            $isManipulation = self::isManipulation($query);
67
+        }
68 68
 
69
-		// return the result
70
-		try {
71
-			$result =$connection->prepare($query, $limit, $offset);
72
-		} catch (\Doctrine\DBAL\DBALException $e) {
73
-			throw new \OC\DatabaseException($e->getMessage());
74
-		}
75
-		// differentiate between query and manipulation
76
-		$result = new OC_DB_StatementWrapper($result, $isManipulation);
77
-		return $result;
78
-	}
69
+        // return the result
70
+        try {
71
+            $result =$connection->prepare($query, $limit, $offset);
72
+        } catch (\Doctrine\DBAL\DBALException $e) {
73
+            throw new \OC\DatabaseException($e->getMessage());
74
+        }
75
+        // differentiate between query and manipulation
76
+        $result = new OC_DB_StatementWrapper($result, $isManipulation);
77
+        return $result;
78
+    }
79 79
 
80
-	/**
81
-	 * tries to guess the type of statement based on the first 10 characters
82
-	 * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
83
-	 *
84
-	 * @param string $sql
85
-	 * @return bool
86
-	 */
87
-	static public function isManipulation($sql) {
88
-		$selectOccurrence = stripos($sql, 'SELECT');
89
-		if ($selectOccurrence !== false && $selectOccurrence < 10) {
90
-			return false;
91
-		}
92
-		$insertOccurrence = stripos($sql, 'INSERT');
93
-		if ($insertOccurrence !== false && $insertOccurrence < 10) {
94
-			return true;
95
-		}
96
-		$updateOccurrence = stripos($sql, 'UPDATE');
97
-		if ($updateOccurrence !== false && $updateOccurrence < 10) {
98
-			return true;
99
-		}
100
-		$deleteOccurrence = stripos($sql, 'DELETE');
101
-		if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
102
-			return true;
103
-		}
104
-		return false;
105
-	}
80
+    /**
81
+     * tries to guess the type of statement based on the first 10 characters
82
+     * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
83
+     *
84
+     * @param string $sql
85
+     * @return bool
86
+     */
87
+    static public function isManipulation($sql) {
88
+        $selectOccurrence = stripos($sql, 'SELECT');
89
+        if ($selectOccurrence !== false && $selectOccurrence < 10) {
90
+            return false;
91
+        }
92
+        $insertOccurrence = stripos($sql, 'INSERT');
93
+        if ($insertOccurrence !== false && $insertOccurrence < 10) {
94
+            return true;
95
+        }
96
+        $updateOccurrence = stripos($sql, 'UPDATE');
97
+        if ($updateOccurrence !== false && $updateOccurrence < 10) {
98
+            return true;
99
+        }
100
+        $deleteOccurrence = stripos($sql, 'DELETE');
101
+        if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
102
+            return true;
103
+        }
104
+        return false;
105
+    }
106 106
 
107
-	/**
108
-	 * execute a prepared statement, on error write log and throw exception
109
-	 * @param mixed $stmt OC_DB_StatementWrapper,
110
-	 *					  an array with 'sql' and optionally 'limit' and 'offset' keys
111
-	 *					.. or a simple sql query string
112
-	 * @param array $parameters
113
-	 * @return OC_DB_StatementWrapper
114
-	 * @throws \OC\DatabaseException
115
-	 */
116
-	static public function executeAudited($stmt, array $parameters = []) {
117
-		if (is_string($stmt)) {
118
-			// convert to an array with 'sql'
119
-			if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
120
-				// TODO try to convert LIMIT OFFSET notation to parameters
121
-				$message = 'LIMIT and OFFSET are forbidden for portability reasons,'
122
-						 . ' pass an array with \'limit\' and \'offset\' instead';
123
-				throw new \OC\DatabaseException($message);
124
-			}
125
-			$stmt = ['sql' => $stmt, 'limit' => null, 'offset' => null];
126
-		}
127
-		if (is_array($stmt)) {
128
-			// convert to prepared statement
129
-			if ( ! array_key_exists('sql', $stmt) ) {
130
-				$message = 'statement array must at least contain key \'sql\'';
131
-				throw new \OC\DatabaseException($message);
132
-			}
133
-			if ( ! array_key_exists('limit', $stmt) ) {
134
-				$stmt['limit'] = null;
135
-			}
136
-			if ( ! array_key_exists('limit', $stmt) ) {
137
-				$stmt['offset'] = null;
138
-			}
139
-			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
140
-		}
141
-		self::raiseExceptionOnError($stmt, 'Could not prepare statement');
142
-		if ($stmt instanceof OC_DB_StatementWrapper) {
143
-			$result = $stmt->execute($parameters);
144
-			self::raiseExceptionOnError($result, 'Could not execute statement');
145
-		} else {
146
-			if (is_object($stmt)) {
147
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
148
-			} else {
149
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
150
-			}
151
-			throw new \OC\DatabaseException($message);
152
-		}
153
-		return $result;
154
-	}
107
+    /**
108
+     * execute a prepared statement, on error write log and throw exception
109
+     * @param mixed $stmt OC_DB_StatementWrapper,
110
+     *					  an array with 'sql' and optionally 'limit' and 'offset' keys
111
+     *					.. or a simple sql query string
112
+     * @param array $parameters
113
+     * @return OC_DB_StatementWrapper
114
+     * @throws \OC\DatabaseException
115
+     */
116
+    static public function executeAudited($stmt, array $parameters = []) {
117
+        if (is_string($stmt)) {
118
+            // convert to an array with 'sql'
119
+            if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
120
+                // TODO try to convert LIMIT OFFSET notation to parameters
121
+                $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
122
+                            . ' pass an array with \'limit\' and \'offset\' instead';
123
+                throw new \OC\DatabaseException($message);
124
+            }
125
+            $stmt = ['sql' => $stmt, 'limit' => null, 'offset' => null];
126
+        }
127
+        if (is_array($stmt)) {
128
+            // convert to prepared statement
129
+            if ( ! array_key_exists('sql', $stmt) ) {
130
+                $message = 'statement array must at least contain key \'sql\'';
131
+                throw new \OC\DatabaseException($message);
132
+            }
133
+            if ( ! array_key_exists('limit', $stmt) ) {
134
+                $stmt['limit'] = null;
135
+            }
136
+            if ( ! array_key_exists('limit', $stmt) ) {
137
+                $stmt['offset'] = null;
138
+            }
139
+            $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
140
+        }
141
+        self::raiseExceptionOnError($stmt, 'Could not prepare statement');
142
+        if ($stmt instanceof OC_DB_StatementWrapper) {
143
+            $result = $stmt->execute($parameters);
144
+            self::raiseExceptionOnError($result, 'Could not execute statement');
145
+        } else {
146
+            if (is_object($stmt)) {
147
+                $message = 'Expected a prepared statement or array got ' . get_class($stmt);
148
+            } else {
149
+                $message = 'Expected a prepared statement or array got ' . gettype($stmt);
150
+            }
151
+            throw new \OC\DatabaseException($message);
152
+        }
153
+        return $result;
154
+    }
155 155
 
156
-	/**
157
-	 * saves database schema to xml file
158
-	 * @param string $file name of file
159
-	 * @return bool
160
-	 *
161
-	 * TODO: write more documentation
162
-	 */
163
-	public static function getDbStructure($file) {
164
-		$schemaManager = self::getMDB2SchemaManager();
165
-		return $schemaManager->getDbStructure($file);
166
-	}
156
+    /**
157
+     * saves database schema to xml file
158
+     * @param string $file name of file
159
+     * @return bool
160
+     *
161
+     * TODO: write more documentation
162
+     */
163
+    public static function getDbStructure($file) {
164
+        $schemaManager = self::getMDB2SchemaManager();
165
+        return $schemaManager->getDbStructure($file);
166
+    }
167 167
 
168
-	/**
169
-	 * Creates tables from XML file
170
-	 * @param string $file file to read structure from
171
-	 * @return bool
172
-	 *
173
-	 * TODO: write more documentation
174
-	 */
175
-	public static function createDbFromStructure($file) {
176
-		$schemaManager = self::getMDB2SchemaManager();
177
-		return $schemaManager->createDbFromStructure($file);
178
-	}
168
+    /**
169
+     * Creates tables from XML file
170
+     * @param string $file file to read structure from
171
+     * @return bool
172
+     *
173
+     * TODO: write more documentation
174
+     */
175
+    public static function createDbFromStructure($file) {
176
+        $schemaManager = self::getMDB2SchemaManager();
177
+        return $schemaManager->createDbFromStructure($file);
178
+    }
179 179
 
180
-	/**
181
-	 * update the database schema
182
-	 * @param string $file file to read structure from
183
-	 * @throws Exception
184
-	 * @return string|boolean
185
-	 * @suppress PhanDeprecatedFunction
186
-	 */
187
-	public static function updateDbFromStructure($file) {
188
-		$schemaManager = self::getMDB2SchemaManager();
189
-		try {
190
-			$result = $schemaManager->updateDbFromStructure($file);
191
-		} catch (Exception $e) {
192
-			\OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', ILogger::FATAL);
193
-			throw $e;
194
-		}
195
-		return $result;
196
-	}
180
+    /**
181
+     * update the database schema
182
+     * @param string $file file to read structure from
183
+     * @throws Exception
184
+     * @return string|boolean
185
+     * @suppress PhanDeprecatedFunction
186
+     */
187
+    public static function updateDbFromStructure($file) {
188
+        $schemaManager = self::getMDB2SchemaManager();
189
+        try {
190
+            $result = $schemaManager->updateDbFromStructure($file);
191
+        } catch (Exception $e) {
192
+            \OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', ILogger::FATAL);
193
+            throw $e;
194
+        }
195
+        return $result;
196
+    }
197 197
 
198
-	/**
199
-	 * remove all tables defined in a database structure xml file
200
-	 * @param string $file the xml file describing the tables
201
-	 */
202
-	public static function removeDBStructure($file) {
203
-		$schemaManager = self::getMDB2SchemaManager();
204
-		$schemaManager->removeDBStructure($file);
205
-	}
198
+    /**
199
+     * remove all tables defined in a database structure xml file
200
+     * @param string $file the xml file describing the tables
201
+     */
202
+    public static function removeDBStructure($file) {
203
+        $schemaManager = self::getMDB2SchemaManager();
204
+        $schemaManager->removeDBStructure($file);
205
+    }
206 206
 
207
-	/**
208
-	 * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
209
-	 * @param mixed $result
210
-	 * @param string $message
211
-	 * @return void
212
-	 * @throws \OC\DatabaseException
213
-	 */
214
-	public static function raiseExceptionOnError($result, $message = null) {
215
-		if($result === false) {
216
-			if ($message === null) {
217
-				$message = self::getErrorMessage();
218
-			} else {
219
-				$message .= ', Root cause:' . self::getErrorMessage();
220
-			}
221
-			throw new \OC\DatabaseException($message);
222
-		}
223
-	}
207
+    /**
208
+     * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
209
+     * @param mixed $result
210
+     * @param string $message
211
+     * @return void
212
+     * @throws \OC\DatabaseException
213
+     */
214
+    public static function raiseExceptionOnError($result, $message = null) {
215
+        if($result === false) {
216
+            if ($message === null) {
217
+                $message = self::getErrorMessage();
218
+            } else {
219
+                $message .= ', Root cause:' . self::getErrorMessage();
220
+            }
221
+            throw new \OC\DatabaseException($message);
222
+        }
223
+    }
224 224
 
225
-	/**
226
-	 * returns the error code and message as a string for logging
227
-	 * works with DoctrineException
228
-	 * @return string
229
-	 */
230
-	public static function getErrorMessage() {
231
-		$connection = \OC::$server->getDatabaseConnection();
232
-		return $connection->getError();
233
-	}
225
+    /**
226
+     * returns the error code and message as a string for logging
227
+     * works with DoctrineException
228
+     * @return string
229
+     */
230
+    public static function getErrorMessage() {
231
+        $connection = \OC::$server->getDatabaseConnection();
232
+        return $connection->getError();
233
+    }
234 234
 
235
-	/**
236
-	 * Checks if a table exists in the database - the database prefix will be prepended
237
-	 *
238
-	 * @param string $table
239
-	 * @return bool
240
-	 * @throws \OC\DatabaseException
241
-	 */
242
-	public static function tableExists($table) {
243
-		$connection = \OC::$server->getDatabaseConnection();
244
-		return $connection->tableExists($table);
245
-	}
235
+    /**
236
+     * Checks if a table exists in the database - the database prefix will be prepended
237
+     *
238
+     * @param string $table
239
+     * @return bool
240
+     * @throws \OC\DatabaseException
241
+     */
242
+    public static function tableExists($table) {
243
+        $connection = \OC::$server->getDatabaseConnection();
244
+        return $connection->tableExists($table);
245
+    }
246 246
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 	 *
59 59
 	 * SQL query via Doctrine prepare(), needs to be execute()'d!
60 60
 	 */
61
-	static public function prepare($query , $limit = null, $offset = null, $isManipulation = null) {
61
+	static public function prepare($query, $limit = null, $offset = null, $isManipulation = null) {
62 62
 		$connection = \OC::$server->getDatabaseConnection();
63 63
 
64 64
 		if ($isManipulation === null) {
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 
69 69
 		// return the result
70 70
 		try {
71
-			$result =$connection->prepare($query, $limit, $offset);
71
+			$result = $connection->prepare($query, $limit, $offset);
72 72
 		} catch (\Doctrine\DBAL\DBALException $e) {
73 73
 			throw new \OC\DatabaseException($e->getMessage());
74 74
 		}
@@ -126,14 +126,14 @@  discard block
 block discarded – undo
126 126
 		}
127 127
 		if (is_array($stmt)) {
128 128
 			// convert to prepared statement
129
-			if ( ! array_key_exists('sql', $stmt) ) {
129
+			if (!array_key_exists('sql', $stmt)) {
130 130
 				$message = 'statement array must at least contain key \'sql\'';
131 131
 				throw new \OC\DatabaseException($message);
132 132
 			}
133
-			if ( ! array_key_exists('limit', $stmt) ) {
133
+			if (!array_key_exists('limit', $stmt)) {
134 134
 				$stmt['limit'] = null;
135 135
 			}
136
-			if ( ! array_key_exists('limit', $stmt) ) {
136
+			if (!array_key_exists('limit', $stmt)) {
137 137
 				$stmt['offset'] = null;
138 138
 			}
139 139
 			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
@@ -144,9 +144,9 @@  discard block
 block discarded – undo
144 144
 			self::raiseExceptionOnError($result, 'Could not execute statement');
145 145
 		} else {
146 146
 			if (is_object($stmt)) {
147
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
147
+				$message = 'Expected a prepared statement or array got '.get_class($stmt);
148 148
 			} else {
149
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
149
+				$message = 'Expected a prepared statement or array got '.gettype($stmt);
150 150
 			}
151 151
 			throw new \OC\DatabaseException($message);
152 152
 		}
@@ -212,11 +212,11 @@  discard block
 block discarded – undo
212 212
 	 * @throws \OC\DatabaseException
213 213
 	 */
214 214
 	public static function raiseExceptionOnError($result, $message = null) {
215
-		if($result === false) {
215
+		if ($result === false) {
216 216
 			if ($message === null) {
217 217
 				$message = self::getErrorMessage();
218 218
 			} else {
219
-				$message .= ', Root cause:' . self::getErrorMessage();
219
+				$message .= ', Root cause:'.self::getErrorMessage();
220 220
 			}
221 221
 			throw new \OC\DatabaseException($message);
222 222
 		}
Please login to merge, or discard this patch.