Completed
Push — master ( 3c4ac6...7b2c08 )
by Morris
17:26
created
lib/private/Files/Cache/Scanner.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -37,7 +37,6 @@
 block discarded – undo
37 37
 
38 38
 use OC\Files\Filesystem;
39 39
 use OC\Hooks\BasicEmitter;
40
-use OCP\Config;
41 40
 use OCP\Files\Cache\IScanner;
42 41
 use OCP\Files\ForbiddenException;
43 42
 use OCP\Lock\ILockingProvider;
Please login to merge, or discard this patch.
Indentation   +475 added lines, -475 removed lines patch added patch discarded remove patch
@@ -54,479 +54,479 @@
 block discarded – undo
54 54
  * @package OC\Files\Cache
55 55
  */
56 56
 class Scanner extends BasicEmitter implements IScanner {
57
-	/**
58
-	 * @var \OC\Files\Storage\Storage $storage
59
-	 */
60
-	protected $storage;
61
-
62
-	/**
63
-	 * @var string $storageId
64
-	 */
65
-	protected $storageId;
66
-
67
-	/**
68
-	 * @var \OC\Files\Cache\Cache $cache
69
-	 */
70
-	protected $cache;
71
-
72
-	/**
73
-	 * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache
74
-	 */
75
-	protected $cacheActive;
76
-
77
-	/**
78
-	 * @var bool $useTransactions whether to use transactions
79
-	 */
80
-	protected $useTransactions = true;
81
-
82
-	/**
83
-	 * @var \OCP\Lock\ILockingProvider
84
-	 */
85
-	protected $lockingProvider;
86
-
87
-	public function __construct(\OC\Files\Storage\Storage $storage) {
88
-		$this->storage = $storage;
89
-		$this->storageId = $this->storage->getId();
90
-		$this->cache = $storage->getCache();
91
-		$this->cacheActive = !\OC::$server->getConfig()->getSystemValue('filesystem_cache_readonly', false);
92
-		$this->lockingProvider = \OC::$server->getLockingProvider();
93
-	}
94
-
95
-	/**
96
-	 * Whether to wrap the scanning of a folder in a database transaction
97
-	 * On default transactions are used
98
-	 *
99
-	 * @param bool $useTransactions
100
-	 */
101
-	public function setUseTransactions($useTransactions) {
102
-		$this->useTransactions = $useTransactions;
103
-	}
104
-
105
-	/**
106
-	 * get all the metadata of a file or folder
107
-	 * *
108
-	 *
109
-	 * @param string $path
110
-	 * @return array an array of metadata of the file
111
-	 */
112
-	protected function getData($path) {
113
-		$data = $this->storage->getMetaData($path);
114
-		if (is_null($data)) {
115
-			\OCP\Util::writeLog('OC\Files\Cache\Scanner', "!!! Path '$path' is not accessible or present !!!", \OCP\Util::DEBUG);
116
-		}
117
-		return $data;
118
-	}
119
-
120
-	/**
121
-	 * scan a single file and store it in the cache
122
-	 *
123
-	 * @param string $file
124
-	 * @param int $reuseExisting
125
-	 * @param int $parentId
126
-	 * @param array | null $cacheData existing data in the cache for the file to be scanned
127
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
128
-	 * @return array an array of metadata of the scanned file
129
-	 * @throws \OC\ServerNotAvailableException
130
-	 * @throws \OCP\Lock\LockedException
131
-	 */
132
-	public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) {
133
-		if ($file !== '') {
134
-			try {
135
-				$this->storage->verifyPath(dirname($file), basename($file));
136
-			} catch (\Exception $e) {
137
-				return null;
138
-			}
139
-		}
140
-
141
-		// only proceed if $file is not a partial file nor a blacklisted file
142
-		if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) {
143
-
144
-			//acquire a lock
145
-			if ($lock) {
146
-				if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
147
-					$this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
148
-				}
149
-			}
150
-
151
-			try {
152
-				$data = $this->getData($file);
153
-			} catch (ForbiddenException $e) {
154
-				return null;
155
-			}
156
-
157
-			if ($data) {
158
-
159
-				// pre-emit only if it was a file. By that we avoid counting/treating folders as files
160
-				if ($data['mimetype'] !== 'httpd/unix-directory') {
161
-					$this->emit('\OC\Files\Cache\Scanner', 'scanFile', array($file, $this->storageId));
162
-					\OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId));
163
-				}
164
-
165
-				$parent = dirname($file);
166
-				if ($parent === '.' or $parent === '/') {
167
-					$parent = '';
168
-				}
169
-				if ($parentId === -1) {
170
-					$parentId = $this->cache->getParentId($file);
171
-				}
172
-
173
-				// scan the parent if it's not in the cache (id -1) and the current file is not the root folder
174
-				if ($file and $parentId === -1) {
175
-					$parentData = $this->scanFile($parent);
176
-					if (!$parentData) {
177
-						return null;
178
-					}
179
-					$parentId = $parentData['fileid'];
180
-				}
181
-				if ($parent) {
182
-					$data['parent'] = $parentId;
183
-				}
184
-				if (is_null($cacheData)) {
185
-					/** @var CacheEntry $cacheData */
186
-					$cacheData = $this->cache->get($file);
187
-				}
188
-				if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) {
189
-					// prevent empty etag
190
-					if (empty($cacheData['etag'])) {
191
-						$etag = $data['etag'];
192
-					} else {
193
-						$etag = $cacheData['etag'];
194
-					}
195
-					$fileId = $cacheData['fileid'];
196
-					$data['fileid'] = $fileId;
197
-					// only reuse data if the file hasn't explicitly changed
198
-					if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) {
199
-						$data['mtime'] = $cacheData['mtime'];
200
-						if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) {
201
-							$data['size'] = $cacheData['size'];
202
-						}
203
-						if ($reuseExisting & self::REUSE_ETAG) {
204
-							$data['etag'] = $etag;
205
-						}
206
-					}
207
-					// Only update metadata that has changed
208
-					$newData = array_diff_assoc($data, $cacheData->getData());
209
-				} else {
210
-					$newData = $data;
211
-					$fileId = -1;
212
-				}
213
-				if (!empty($newData)) {
214
-					// Reset the checksum if the data has changed
215
-					$newData['checksum'] = '';
216
-					$data['fileid'] = $this->addToCache($file, $newData, $fileId);
217
-				}
218
-				if (isset($cacheData['size'])) {
219
-					$data['oldSize'] = $cacheData['size'];
220
-				} else {
221
-					$data['oldSize'] = 0;
222
-				}
223
-
224
-				if (isset($cacheData['encrypted'])) {
225
-					$data['encrypted'] = $cacheData['encrypted'];
226
-				}
227
-
228
-				// post-emit only if it was a file. By that we avoid counting/treating folders as files
229
-				if ($data['mimetype'] !== 'httpd/unix-directory') {
230
-					$this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId));
231
-					\OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId));
232
-				}
233
-
234
-			} else {
235
-				$this->removeFromCache($file);
236
-			}
237
-
238
-			//release the acquired lock
239
-			if ($lock) {
240
-				if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
241
-					$this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
242
-				}
243
-			}
244
-
245
-			if ($data && !isset($data['encrypted'])) {
246
-				$data['encrypted'] = false;
247
-			}
248
-			return $data;
249
-		}
250
-
251
-		return null;
252
-	}
253
-
254
-	protected function removeFromCache($path) {
255
-		\OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path));
256
-		$this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path));
257
-		if ($this->cacheActive) {
258
-			$this->cache->remove($path);
259
-		}
260
-	}
261
-
262
-	/**
263
-	 * @param string $path
264
-	 * @param array $data
265
-	 * @param int $fileId
266
-	 * @return int the id of the added file
267
-	 */
268
-	protected function addToCache($path, $data, $fileId = -1) {
269
-		if (isset($data['scan_permissions'])) {
270
-			$data['permissions'] = $data['scan_permissions'];
271
-		}
272
-		\OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
273
-		$this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data));
274
-		if ($this->cacheActive) {
275
-			if ($fileId !== -1) {
276
-				$this->cache->update($fileId, $data);
277
-				return $fileId;
278
-			} else {
279
-				return $this->cache->put($path, $data);
280
-			}
281
-		} else {
282
-			return -1;
283
-		}
284
-	}
285
-
286
-	/**
287
-	 * @param string $path
288
-	 * @param array $data
289
-	 * @param int $fileId
290
-	 */
291
-	protected function updateCache($path, $data, $fileId = -1) {
292
-		\OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
293
-		$this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data));
294
-		if ($this->cacheActive) {
295
-			if ($fileId !== -1) {
296
-				$this->cache->update($fileId, $data);
297
-			} else {
298
-				$this->cache->put($path, $data);
299
-			}
300
-		}
301
-	}
302
-
303
-	/**
304
-	 * scan a folder and all it's children
305
-	 *
306
-	 * @param string $path
307
-	 * @param bool $recursive
308
-	 * @param int $reuse
309
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
310
-	 * @return array an array of the meta data of the scanned file or folder
311
-	 */
312
-	public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
313
-		if ($reuse === -1) {
314
-			$reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
315
-		}
316
-		if ($lock) {
317
-			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
318
-				$this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
319
-				$this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
320
-			}
321
-		}
322
-		$data = $this->scanFile($path, $reuse, -1, null, $lock);
323
-		if ($data and $data['mimetype'] === 'httpd/unix-directory') {
324
-			$size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock);
325
-			$data['size'] = $size;
326
-		}
327
-		if ($lock) {
328
-			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
329
-				$this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
330
-				$this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
331
-			}
332
-		}
333
-		return $data;
334
-	}
335
-
336
-	/**
337
-	 * Get the children currently in the cache
338
-	 *
339
-	 * @param int $folderId
340
-	 * @return array[]
341
-	 */
342
-	protected function getExistingChildren($folderId) {
343
-		$existingChildren = array();
344
-		$children = $this->cache->getFolderContentsById($folderId);
345
-		foreach ($children as $child) {
346
-			$existingChildren[$child['name']] = $child;
347
-		}
348
-		return $existingChildren;
349
-	}
350
-
351
-	/**
352
-	 * Get the children from the storage
353
-	 *
354
-	 * @param string $folder
355
-	 * @return string[]
356
-	 */
357
-	protected function getNewChildren($folder) {
358
-		$children = array();
359
-		if ($dh = $this->storage->opendir($folder)) {
360
-			if (is_resource($dh)) {
361
-				while (($file = readdir($dh)) !== false) {
362
-					if (!Filesystem::isIgnoredDir($file)) {
363
-						$children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/');
364
-					}
365
-				}
366
-			}
367
-		}
368
-		return $children;
369
-	}
370
-
371
-	/**
372
-	 * scan all the files and folders in a folder
373
-	 *
374
-	 * @param string $path
375
-	 * @param bool $recursive
376
-	 * @param int $reuse
377
-	 * @param int $folderId id for the folder to be scanned
378
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
379
-	 * @return int the size of the scanned folder or -1 if the size is unknown at this stage
380
-	 */
381
-	protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) {
382
-		if ($reuse === -1) {
383
-			$reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
384
-		}
385
-		$this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId));
386
-		$size = 0;
387
-		if (!is_null($folderId)) {
388
-			$folderId = $this->cache->getId($path);
389
-		}
390
-		$childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size);
391
-
392
-		foreach ($childQueue as $child => $childId) {
393
-			$childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock);
394
-			if ($childSize === -1) {
395
-				$size = -1;
396
-			} else if ($size !== -1) {
397
-				$size += $childSize;
398
-			}
399
-		}
400
-		if ($this->cacheActive) {
401
-			$this->cache->update($folderId, array('size' => $size));
402
-		}
403
-		$this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId));
404
-		return $size;
405
-	}
406
-
407
-	private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) {
408
-		// we put this in it's own function so it cleans up the memory before we start recursing
409
-		$existingChildren = $this->getExistingChildren($folderId);
410
-		$newChildren = $this->getNewChildren($path);
411
-
412
-		if ($this->useTransactions) {
413
-			\OC::$server->getDatabaseConnection()->beginTransaction();
414
-		}
415
-
416
-		$exceptionOccurred = false;
417
-		$childQueue = [];
418
-		foreach ($newChildren as $file) {
419
-			$child = ($path) ? $path . '/' . $file : $file;
420
-			try {
421
-				$existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
422
-				$data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
423
-				if ($data) {
424
-					if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) {
425
-						$childQueue[$child] = $data['fileid'];
426
-					} else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) {
427
-						// only recurse into folders which aren't fully scanned
428
-						$childQueue[$child] = $data['fileid'];
429
-					} else if ($data['size'] === -1) {
430
-						$size = -1;
431
-					} else if ($size !== -1) {
432
-						$size += $data['size'];
433
-					}
434
-				}
435
-			} catch (\Doctrine\DBAL\DBALException $ex) {
436
-				// might happen if inserting duplicate while a scanning
437
-				// process is running in parallel
438
-				// log and ignore
439
-				\OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG);
440
-				$exceptionOccurred = true;
441
-			} catch (\OCP\Lock\LockedException $e) {
442
-				if ($this->useTransactions) {
443
-					\OC::$server->getDatabaseConnection()->rollback();
444
-				}
445
-				throw $e;
446
-			}
447
-		}
448
-		$removedChildren = \array_diff(array_keys($existingChildren), $newChildren);
449
-		foreach ($removedChildren as $childName) {
450
-			$child = ($path) ? $path . '/' . $childName : $childName;
451
-			$this->removeFromCache($child);
452
-		}
453
-		if ($this->useTransactions) {
454
-			\OC::$server->getDatabaseConnection()->commit();
455
-		}
456
-		if ($exceptionOccurred) {
457
-			// It might happen that the parallel scan process has already
458
-			// inserted mimetypes but those weren't available yet inside the transaction
459
-			// To make sure to have the updated mime types in such cases,
460
-			// we reload them here
461
-			\OC::$server->getMimeTypeLoader()->reset();
462
-		}
463
-		return $childQueue;
464
-	}
465
-
466
-	/**
467
-	 * check if the file should be ignored when scanning
468
-	 * NOTE: files with a '.part' extension are ignored as well!
469
-	 *       prevents unfinished put requests to be scanned
470
-	 *
471
-	 * @param string $file
472
-	 * @return boolean
473
-	 */
474
-	public static function isPartialFile($file) {
475
-		if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
476
-			return true;
477
-		}
478
-		if (strpos($file, '.part/') !== false) {
479
-			return true;
480
-		}
481
-
482
-		return false;
483
-	}
484
-
485
-	/**
486
-	 * walk over any folders that are not fully scanned yet and scan them
487
-	 */
488
-	public function backgroundScan() {
489
-		if (!$this->cache->inCache('')) {
490
-			$this->runBackgroundScanJob(function () {
491
-				$this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
492
-			}, '');
493
-		} else {
494
-			$lastPath = null;
495
-			while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
496
-				$this->runBackgroundScanJob(function () use ($path) {
497
-					$this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
498
-				}, $path);
499
-				// FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
500
-				// to make this possible
501
-				$lastPath = $path;
502
-			}
503
-		}
504
-	}
505
-
506
-	private function runBackgroundScanJob(callable $callback, $path) {
507
-		try {
508
-			$callback();
509
-			\OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path));
510
-			if ($this->cacheActive && $this->cache instanceof Cache) {
511
-				$this->cache->correctFolderSize($path);
512
-			}
513
-		} catch (\OCP\Files\StorageInvalidException $e) {
514
-			// skip unavailable storages
515
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
516
-			// skip unavailable storages
517
-		} catch (\OCP\Files\ForbiddenException $e) {
518
-			// skip forbidden storages
519
-		} catch (\OCP\Lock\LockedException $e) {
520
-			// skip unavailable storages
521
-		}
522
-	}
523
-
524
-	/**
525
-	 * Set whether the cache is affected by scan operations
526
-	 *
527
-	 * @param boolean $active The active state of the cache
528
-	 */
529
-	public function setCacheActive($active) {
530
-		$this->cacheActive = $active;
531
-	}
57
+    /**
58
+     * @var \OC\Files\Storage\Storage $storage
59
+     */
60
+    protected $storage;
61
+
62
+    /**
63
+     * @var string $storageId
64
+     */
65
+    protected $storageId;
66
+
67
+    /**
68
+     * @var \OC\Files\Cache\Cache $cache
69
+     */
70
+    protected $cache;
71
+
72
+    /**
73
+     * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache
74
+     */
75
+    protected $cacheActive;
76
+
77
+    /**
78
+     * @var bool $useTransactions whether to use transactions
79
+     */
80
+    protected $useTransactions = true;
81
+
82
+    /**
83
+     * @var \OCP\Lock\ILockingProvider
84
+     */
85
+    protected $lockingProvider;
86
+
87
+    public function __construct(\OC\Files\Storage\Storage $storage) {
88
+        $this->storage = $storage;
89
+        $this->storageId = $this->storage->getId();
90
+        $this->cache = $storage->getCache();
91
+        $this->cacheActive = !\OC::$server->getConfig()->getSystemValue('filesystem_cache_readonly', false);
92
+        $this->lockingProvider = \OC::$server->getLockingProvider();
93
+    }
94
+
95
+    /**
96
+     * Whether to wrap the scanning of a folder in a database transaction
97
+     * On default transactions are used
98
+     *
99
+     * @param bool $useTransactions
100
+     */
101
+    public function setUseTransactions($useTransactions) {
102
+        $this->useTransactions = $useTransactions;
103
+    }
104
+
105
+    /**
106
+     * get all the metadata of a file or folder
107
+     * *
108
+     *
109
+     * @param string $path
110
+     * @return array an array of metadata of the file
111
+     */
112
+    protected function getData($path) {
113
+        $data = $this->storage->getMetaData($path);
114
+        if (is_null($data)) {
115
+            \OCP\Util::writeLog('OC\Files\Cache\Scanner', "!!! Path '$path' is not accessible or present !!!", \OCP\Util::DEBUG);
116
+        }
117
+        return $data;
118
+    }
119
+
120
+    /**
121
+     * scan a single file and store it in the cache
122
+     *
123
+     * @param string $file
124
+     * @param int $reuseExisting
125
+     * @param int $parentId
126
+     * @param array | null $cacheData existing data in the cache for the file to be scanned
127
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
128
+     * @return array an array of metadata of the scanned file
129
+     * @throws \OC\ServerNotAvailableException
130
+     * @throws \OCP\Lock\LockedException
131
+     */
132
+    public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) {
133
+        if ($file !== '') {
134
+            try {
135
+                $this->storage->verifyPath(dirname($file), basename($file));
136
+            } catch (\Exception $e) {
137
+                return null;
138
+            }
139
+        }
140
+
141
+        // only proceed if $file is not a partial file nor a blacklisted file
142
+        if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) {
143
+
144
+            //acquire a lock
145
+            if ($lock) {
146
+                if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
147
+                    $this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
148
+                }
149
+            }
150
+
151
+            try {
152
+                $data = $this->getData($file);
153
+            } catch (ForbiddenException $e) {
154
+                return null;
155
+            }
156
+
157
+            if ($data) {
158
+
159
+                // pre-emit only if it was a file. By that we avoid counting/treating folders as files
160
+                if ($data['mimetype'] !== 'httpd/unix-directory') {
161
+                    $this->emit('\OC\Files\Cache\Scanner', 'scanFile', array($file, $this->storageId));
162
+                    \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId));
163
+                }
164
+
165
+                $parent = dirname($file);
166
+                if ($parent === '.' or $parent === '/') {
167
+                    $parent = '';
168
+                }
169
+                if ($parentId === -1) {
170
+                    $parentId = $this->cache->getParentId($file);
171
+                }
172
+
173
+                // scan the parent if it's not in the cache (id -1) and the current file is not the root folder
174
+                if ($file and $parentId === -1) {
175
+                    $parentData = $this->scanFile($parent);
176
+                    if (!$parentData) {
177
+                        return null;
178
+                    }
179
+                    $parentId = $parentData['fileid'];
180
+                }
181
+                if ($parent) {
182
+                    $data['parent'] = $parentId;
183
+                }
184
+                if (is_null($cacheData)) {
185
+                    /** @var CacheEntry $cacheData */
186
+                    $cacheData = $this->cache->get($file);
187
+                }
188
+                if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) {
189
+                    // prevent empty etag
190
+                    if (empty($cacheData['etag'])) {
191
+                        $etag = $data['etag'];
192
+                    } else {
193
+                        $etag = $cacheData['etag'];
194
+                    }
195
+                    $fileId = $cacheData['fileid'];
196
+                    $data['fileid'] = $fileId;
197
+                    // only reuse data if the file hasn't explicitly changed
198
+                    if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) {
199
+                        $data['mtime'] = $cacheData['mtime'];
200
+                        if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) {
201
+                            $data['size'] = $cacheData['size'];
202
+                        }
203
+                        if ($reuseExisting & self::REUSE_ETAG) {
204
+                            $data['etag'] = $etag;
205
+                        }
206
+                    }
207
+                    // Only update metadata that has changed
208
+                    $newData = array_diff_assoc($data, $cacheData->getData());
209
+                } else {
210
+                    $newData = $data;
211
+                    $fileId = -1;
212
+                }
213
+                if (!empty($newData)) {
214
+                    // Reset the checksum if the data has changed
215
+                    $newData['checksum'] = '';
216
+                    $data['fileid'] = $this->addToCache($file, $newData, $fileId);
217
+                }
218
+                if (isset($cacheData['size'])) {
219
+                    $data['oldSize'] = $cacheData['size'];
220
+                } else {
221
+                    $data['oldSize'] = 0;
222
+                }
223
+
224
+                if (isset($cacheData['encrypted'])) {
225
+                    $data['encrypted'] = $cacheData['encrypted'];
226
+                }
227
+
228
+                // post-emit only if it was a file. By that we avoid counting/treating folders as files
229
+                if ($data['mimetype'] !== 'httpd/unix-directory') {
230
+                    $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId));
231
+                    \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId));
232
+                }
233
+
234
+            } else {
235
+                $this->removeFromCache($file);
236
+            }
237
+
238
+            //release the acquired lock
239
+            if ($lock) {
240
+                if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
241
+                    $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
242
+                }
243
+            }
244
+
245
+            if ($data && !isset($data['encrypted'])) {
246
+                $data['encrypted'] = false;
247
+            }
248
+            return $data;
249
+        }
250
+
251
+        return null;
252
+    }
253
+
254
+    protected function removeFromCache($path) {
255
+        \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path));
256
+        $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path));
257
+        if ($this->cacheActive) {
258
+            $this->cache->remove($path);
259
+        }
260
+    }
261
+
262
+    /**
263
+     * @param string $path
264
+     * @param array $data
265
+     * @param int $fileId
266
+     * @return int the id of the added file
267
+     */
268
+    protected function addToCache($path, $data, $fileId = -1) {
269
+        if (isset($data['scan_permissions'])) {
270
+            $data['permissions'] = $data['scan_permissions'];
271
+        }
272
+        \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
273
+        $this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data));
274
+        if ($this->cacheActive) {
275
+            if ($fileId !== -1) {
276
+                $this->cache->update($fileId, $data);
277
+                return $fileId;
278
+            } else {
279
+                return $this->cache->put($path, $data);
280
+            }
281
+        } else {
282
+            return -1;
283
+        }
284
+    }
285
+
286
+    /**
287
+     * @param string $path
288
+     * @param array $data
289
+     * @param int $fileId
290
+     */
291
+    protected function updateCache($path, $data, $fileId = -1) {
292
+        \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
293
+        $this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data));
294
+        if ($this->cacheActive) {
295
+            if ($fileId !== -1) {
296
+                $this->cache->update($fileId, $data);
297
+            } else {
298
+                $this->cache->put($path, $data);
299
+            }
300
+        }
301
+    }
302
+
303
+    /**
304
+     * scan a folder and all it's children
305
+     *
306
+     * @param string $path
307
+     * @param bool $recursive
308
+     * @param int $reuse
309
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
310
+     * @return array an array of the meta data of the scanned file or folder
311
+     */
312
+    public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
313
+        if ($reuse === -1) {
314
+            $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
315
+        }
316
+        if ($lock) {
317
+            if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
318
+                $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
319
+                $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
320
+            }
321
+        }
322
+        $data = $this->scanFile($path, $reuse, -1, null, $lock);
323
+        if ($data and $data['mimetype'] === 'httpd/unix-directory') {
324
+            $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock);
325
+            $data['size'] = $size;
326
+        }
327
+        if ($lock) {
328
+            if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
329
+                $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
330
+                $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
331
+            }
332
+        }
333
+        return $data;
334
+    }
335
+
336
+    /**
337
+     * Get the children currently in the cache
338
+     *
339
+     * @param int $folderId
340
+     * @return array[]
341
+     */
342
+    protected function getExistingChildren($folderId) {
343
+        $existingChildren = array();
344
+        $children = $this->cache->getFolderContentsById($folderId);
345
+        foreach ($children as $child) {
346
+            $existingChildren[$child['name']] = $child;
347
+        }
348
+        return $existingChildren;
349
+    }
350
+
351
+    /**
352
+     * Get the children from the storage
353
+     *
354
+     * @param string $folder
355
+     * @return string[]
356
+     */
357
+    protected function getNewChildren($folder) {
358
+        $children = array();
359
+        if ($dh = $this->storage->opendir($folder)) {
360
+            if (is_resource($dh)) {
361
+                while (($file = readdir($dh)) !== false) {
362
+                    if (!Filesystem::isIgnoredDir($file)) {
363
+                        $children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/');
364
+                    }
365
+                }
366
+            }
367
+        }
368
+        return $children;
369
+    }
370
+
371
+    /**
372
+     * scan all the files and folders in a folder
373
+     *
374
+     * @param string $path
375
+     * @param bool $recursive
376
+     * @param int $reuse
377
+     * @param int $folderId id for the folder to be scanned
378
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
379
+     * @return int the size of the scanned folder or -1 if the size is unknown at this stage
380
+     */
381
+    protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) {
382
+        if ($reuse === -1) {
383
+            $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
384
+        }
385
+        $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId));
386
+        $size = 0;
387
+        if (!is_null($folderId)) {
388
+            $folderId = $this->cache->getId($path);
389
+        }
390
+        $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size);
391
+
392
+        foreach ($childQueue as $child => $childId) {
393
+            $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock);
394
+            if ($childSize === -1) {
395
+                $size = -1;
396
+            } else if ($size !== -1) {
397
+                $size += $childSize;
398
+            }
399
+        }
400
+        if ($this->cacheActive) {
401
+            $this->cache->update($folderId, array('size' => $size));
402
+        }
403
+        $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId));
404
+        return $size;
405
+    }
406
+
407
+    private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) {
408
+        // we put this in it's own function so it cleans up the memory before we start recursing
409
+        $existingChildren = $this->getExistingChildren($folderId);
410
+        $newChildren = $this->getNewChildren($path);
411
+
412
+        if ($this->useTransactions) {
413
+            \OC::$server->getDatabaseConnection()->beginTransaction();
414
+        }
415
+
416
+        $exceptionOccurred = false;
417
+        $childQueue = [];
418
+        foreach ($newChildren as $file) {
419
+            $child = ($path) ? $path . '/' . $file : $file;
420
+            try {
421
+                $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
422
+                $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
423
+                if ($data) {
424
+                    if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) {
425
+                        $childQueue[$child] = $data['fileid'];
426
+                    } else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) {
427
+                        // only recurse into folders which aren't fully scanned
428
+                        $childQueue[$child] = $data['fileid'];
429
+                    } else if ($data['size'] === -1) {
430
+                        $size = -1;
431
+                    } else if ($size !== -1) {
432
+                        $size += $data['size'];
433
+                    }
434
+                }
435
+            } catch (\Doctrine\DBAL\DBALException $ex) {
436
+                // might happen if inserting duplicate while a scanning
437
+                // process is running in parallel
438
+                // log and ignore
439
+                \OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG);
440
+                $exceptionOccurred = true;
441
+            } catch (\OCP\Lock\LockedException $e) {
442
+                if ($this->useTransactions) {
443
+                    \OC::$server->getDatabaseConnection()->rollback();
444
+                }
445
+                throw $e;
446
+            }
447
+        }
448
+        $removedChildren = \array_diff(array_keys($existingChildren), $newChildren);
449
+        foreach ($removedChildren as $childName) {
450
+            $child = ($path) ? $path . '/' . $childName : $childName;
451
+            $this->removeFromCache($child);
452
+        }
453
+        if ($this->useTransactions) {
454
+            \OC::$server->getDatabaseConnection()->commit();
455
+        }
456
+        if ($exceptionOccurred) {
457
+            // It might happen that the parallel scan process has already
458
+            // inserted mimetypes but those weren't available yet inside the transaction
459
+            // To make sure to have the updated mime types in such cases,
460
+            // we reload them here
461
+            \OC::$server->getMimeTypeLoader()->reset();
462
+        }
463
+        return $childQueue;
464
+    }
465
+
466
+    /**
467
+     * check if the file should be ignored when scanning
468
+     * NOTE: files with a '.part' extension are ignored as well!
469
+     *       prevents unfinished put requests to be scanned
470
+     *
471
+     * @param string $file
472
+     * @return boolean
473
+     */
474
+    public static function isPartialFile($file) {
475
+        if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
476
+            return true;
477
+        }
478
+        if (strpos($file, '.part/') !== false) {
479
+            return true;
480
+        }
481
+
482
+        return false;
483
+    }
484
+
485
+    /**
486
+     * walk over any folders that are not fully scanned yet and scan them
487
+     */
488
+    public function backgroundScan() {
489
+        if (!$this->cache->inCache('')) {
490
+            $this->runBackgroundScanJob(function () {
491
+                $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
492
+            }, '');
493
+        } else {
494
+            $lastPath = null;
495
+            while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
496
+                $this->runBackgroundScanJob(function () use ($path) {
497
+                    $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
498
+                }, $path);
499
+                // FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
500
+                // to make this possible
501
+                $lastPath = $path;
502
+            }
503
+        }
504
+    }
505
+
506
+    private function runBackgroundScanJob(callable $callback, $path) {
507
+        try {
508
+            $callback();
509
+            \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path));
510
+            if ($this->cacheActive && $this->cache instanceof Cache) {
511
+                $this->cache->correctFolderSize($path);
512
+            }
513
+        } catch (\OCP\Files\StorageInvalidException $e) {
514
+            // skip unavailable storages
515
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
516
+            // skip unavailable storages
517
+        } catch (\OCP\Files\ForbiddenException $e) {
518
+            // skip forbidden storages
519
+        } catch (\OCP\Lock\LockedException $e) {
520
+            // skip unavailable storages
521
+        }
522
+    }
523
+
524
+    /**
525
+     * Set whether the cache is affected by scan operations
526
+     *
527
+     * @param boolean $active The active state of the cache
528
+     */
529
+    public function setCacheActive($active) {
530
+        $this->cacheActive = $active;
531
+    }
532 532
 }
Please login to merge, or discard this patch.
apps/files_versions/lib/Storage.php 2 patches
Indentation   +785 added lines, -785 removed lines patch added patch discarded remove patch
@@ -53,790 +53,790 @@
 block discarded – undo
53 53
 
54 54
 class Storage {
55 55
 
56
-	const DEFAULTENABLED=true;
57
-	const DEFAULTMAXSIZE=50; // unit: percentage; 50% of available disk space/quota
58
-	const VERSIONS_ROOT = 'files_versions/';
59
-
60
-	const DELETE_TRIGGER_MASTER_REMOVED = 0;
61
-	const DELETE_TRIGGER_RETENTION_CONSTRAINT = 1;
62
-	const DELETE_TRIGGER_QUOTA_EXCEEDED = 2;
63
-
64
-	// files for which we can remove the versions after the delete operation was successful
65
-	private static $deletedFiles = array();
66
-
67
-	private static $sourcePathAndUser = array();
68
-
69
-	private static $max_versions_per_interval = array(
70
-		//first 10sec, one version every 2sec
71
-		1 => array('intervalEndsAfter' => 10,      'step' => 2),
72
-		//next minute, one version every 10sec
73
-		2 => array('intervalEndsAfter' => 60,      'step' => 10),
74
-		//next hour, one version every minute
75
-		3 => array('intervalEndsAfter' => 3600,    'step' => 60),
76
-		//next 24h, one version every hour
77
-		4 => array('intervalEndsAfter' => 86400,   'step' => 3600),
78
-		//next 30days, one version per day
79
-		5 => array('intervalEndsAfter' => 2592000, 'step' => 86400),
80
-		//until the end one version per week
81
-		6 => array('intervalEndsAfter' => -1,      'step' => 604800),
82
-	);
83
-
84
-	/** @var \OCA\Files_Versions\AppInfo\Application */
85
-	private static $application;
86
-
87
-	/**
88
-	 * get the UID of the owner of the file and the path to the file relative to
89
-	 * owners files folder
90
-	 *
91
-	 * @param string $filename
92
-	 * @return array
93
-	 * @throws \OC\User\NoUserException
94
-	 */
95
-	public static function getUidAndFilename($filename) {
96
-		$uid = Filesystem::getOwner($filename);
97
-		$userManager = \OC::$server->getUserManager();
98
-		// if the user with the UID doesn't exists, e.g. because the UID points
99
-		// to a remote user with a federated cloud ID we use the current logged-in
100
-		// user. We need a valid local user to create the versions
101
-		if (!$userManager->userExists($uid)) {
102
-			$uid = User::getUser();
103
-		}
104
-		Filesystem::initMountPoints($uid);
105
-		if ( $uid != User::getUser() ) {
106
-			$info = Filesystem::getFileInfo($filename);
107
-			$ownerView = new View('/'.$uid.'/files');
108
-			try {
109
-				$filename = $ownerView->getPath($info['fileid']);
110
-				// make sure that the file name doesn't end with a trailing slash
111
-				// can for example happen single files shared across servers
112
-				$filename = rtrim($filename, '/');
113
-			} catch (NotFoundException $e) {
114
-				$filename = null;
115
-			}
116
-		}
117
-		return [$uid, $filename];
118
-	}
119
-
120
-	/**
121
-	 * Remember the owner and the owner path of the source file
122
-	 *
123
-	 * @param string $source source path
124
-	 */
125
-	public static function setSourcePathAndUser($source) {
126
-		list($uid, $path) = self::getUidAndFilename($source);
127
-		self::$sourcePathAndUser[$source] = array('uid' => $uid, 'path' => $path);
128
-	}
129
-
130
-	/**
131
-	 * Gets the owner and the owner path from the source path
132
-	 *
133
-	 * @param string $source source path
134
-	 * @return array with user id and path
135
-	 */
136
-	public static function getSourcePathAndUser($source) {
137
-
138
-		if (isset(self::$sourcePathAndUser[$source])) {
139
-			$uid = self::$sourcePathAndUser[$source]['uid'];
140
-			$path = self::$sourcePathAndUser[$source]['path'];
141
-			unset(self::$sourcePathAndUser[$source]);
142
-		} else {
143
-			$uid = $path = false;
144
-		}
145
-		return array($uid, $path);
146
-	}
147
-
148
-	/**
149
-	 * get current size of all versions from a given user
150
-	 *
151
-	 * @param string $user user who owns the versions
152
-	 * @return int versions size
153
-	 */
154
-	private static function getVersionsSize($user) {
155
-		$view = new View('/' . $user);
156
-		$fileInfo = $view->getFileInfo('/files_versions');
157
-		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
158
-	}
159
-
160
-	/**
161
-	 * store a new version of a file.
162
-	 */
163
-	public static function store($filename) {
164
-		if(\OC::$server->getConfig()->getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true') {
165
-
166
-			// if the file gets streamed we need to remove the .part extension
167
-			// to get the right target
168
-			$ext = pathinfo($filename, PATHINFO_EXTENSION);
169
-			if ($ext === 'part') {
170
-				$filename = substr($filename, 0, strlen($filename) - 5);
171
-			}
172
-
173
-			// we only handle existing files
174
-			if (! Filesystem::file_exists($filename) || Filesystem::is_dir($filename)) {
175
-				return false;
176
-			}
177
-
178
-			list($uid, $filename) = self::getUidAndFilename($filename);
179
-
180
-			$files_view = new View('/'.$uid .'/files');
181
-			$users_view = new View('/'.$uid);
182
-
183
-			// no use making versions for empty files
184
-			if ($files_view->filesize($filename) === 0) {
185
-				return false;
186
-			}
187
-
188
-			// create all parent folders
189
-			self::createMissingDirectories($filename, $users_view);
190
-
191
-			self::scheduleExpire($uid, $filename);
192
-
193
-			// store a new version of a file
194
-			$mtime = $users_view->filemtime('files/' . $filename);
195
-			$users_view->copy('files/' . $filename, 'files_versions/' . $filename . '.v' . $mtime);
196
-			// call getFileInfo to enforce a file cache entry for the new version
197
-			$users_view->getFileInfo('files_versions/' . $filename . '.v' . $mtime);
198
-		}
199
-	}
200
-
201
-
202
-	/**
203
-	 * mark file as deleted so that we can remove the versions if the file is gone
204
-	 * @param string $path
205
-	 */
206
-	public static function markDeletedFile($path) {
207
-		list($uid, $filename) = self::getUidAndFilename($path);
208
-		self::$deletedFiles[$path] = array(
209
-			'uid' => $uid,
210
-			'filename' => $filename);
211
-	}
212
-
213
-	/**
214
-	 * delete the version from the storage and cache
215
-	 *
216
-	 * @param View $view
217
-	 * @param string $path
218
-	 */
219
-	protected static function deleteVersion($view, $path) {
220
-		$view->unlink($path);
221
-		/**
222
-		 * @var \OC\Files\Storage\Storage $storage
223
-		 * @var string $internalPath
224
-		 */
225
-		list($storage, $internalPath) = $view->resolvePath($path);
226
-		$cache = $storage->getCache($internalPath);
227
-		$cache->remove($internalPath);
228
-	}
229
-
230
-	/**
231
-	 * Delete versions of a file
232
-	 */
233
-	public static function delete($path) {
234
-
235
-		$deletedFile = self::$deletedFiles[$path];
236
-		$uid = $deletedFile['uid'];
237
-		$filename = $deletedFile['filename'];
238
-
239
-		if (!Filesystem::file_exists($path)) {
240
-
241
-			$view = new View('/' . $uid . '/files_versions');
242
-
243
-			$versions = self::getVersions($uid, $filename);
244
-			if (!empty($versions)) {
245
-				foreach ($versions as $v) {
246
-					\OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED));
247
-					self::deleteVersion($view, $filename . '.v' . $v['version']);
248
-					\OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED));
249
-				}
250
-			}
251
-		}
252
-		unset(self::$deletedFiles[$path]);
253
-	}
254
-
255
-	/**
256
-	 * Rename or copy versions of a file of the given paths
257
-	 *
258
-	 * @param string $sourcePath source path of the file to move, relative to
259
-	 * the currently logged in user's "files" folder
260
-	 * @param string $targetPath target path of the file to move, relative to
261
-	 * the currently logged in user's "files" folder
262
-	 * @param string $operation can be 'copy' or 'rename'
263
-	 */
264
-	public static function renameOrCopy($sourcePath, $targetPath, $operation) {
265
-		list($sourceOwner, $sourcePath) = self::getSourcePathAndUser($sourcePath);
266
-
267
-		// it was a upload of a existing file if no old path exists
268
-		// in this case the pre-hook already called the store method and we can
269
-		// stop here
270
-		if ($sourcePath === false) {
271
-			return true;
272
-		}
273
-
274
-		list($targetOwner, $targetPath) = self::getUidAndFilename($targetPath);
275
-
276
-		$sourcePath = ltrim($sourcePath, '/');
277
-		$targetPath = ltrim($targetPath, '/');
278
-
279
-		$rootView = new View('');
280
-
281
-		// did we move a directory ?
282
-		if ($rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
283
-			// does the directory exists for versions too ?
284
-			if ($rootView->is_dir('/' . $sourceOwner . '/files_versions/' . $sourcePath)) {
285
-				// create missing dirs if necessary
286
-				self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
287
-
288
-				// move the directory containing the versions
289
-				$rootView->$operation(
290
-					'/' . $sourceOwner . '/files_versions/' . $sourcePath,
291
-					'/' . $targetOwner . '/files_versions/' . $targetPath
292
-				);
293
-			}
294
-		} else if ($versions = Storage::getVersions($sourceOwner, '/' . $sourcePath)) {
295
-			// create missing dirs if necessary
296
-			self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
297
-
298
-			foreach ($versions as $v) {
299
-				// move each version one by one to the target directory
300
-				$rootView->$operation(
301
-					'/' . $sourceOwner . '/files_versions/' . $sourcePath.'.v' . $v['version'],
302
-					'/' . $targetOwner . '/files_versions/' . $targetPath.'.v'.$v['version']
303
-				);
304
-			}
305
-		}
306
-
307
-		// if we moved versions directly for a file, schedule expiration check for that file
308
-		if (!$rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
309
-			self::scheduleExpire($targetOwner, $targetPath);
310
-		}
311
-
312
-	}
313
-
314
-	/**
315
-	 * Rollback to an old version of a file.
316
-	 *
317
-	 * @param string $file file name
318
-	 * @param int $revision revision timestamp
319
-	 * @return bool
320
-	 */
321
-	public static function rollback($file, $revision) {
322
-
323
-		if(\OC::$server->getConfig()->getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true') {
324
-			// add expected leading slash
325
-			$file = '/' . ltrim($file, '/');
326
-			list($uid, $filename) = self::getUidAndFilename($file);
327
-			if ($uid === null || trim($filename, '/') === '') {
328
-				return false;
329
-			}
330
-
331
-			$users_view = new View('/'.$uid);
332
-			$files_view = new View('/'. User::getUser().'/files');
333
-
334
-			$versionCreated = false;
335
-
336
-			$fileInfo = $files_view->getFileInfo($file);
337
-
338
-			// check if user has the permissions to revert a version
339
-			if (!$fileInfo->isUpdateable()) {
340
-				return false;
341
-			}
342
-
343
-			//first create a new version
344
-			$version = 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename);
345
-			if (!$users_view->file_exists($version)) {
346
-				$users_view->copy('files'.$filename, 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename));
347
-				$versionCreated = true;
348
-			}
349
-
350
-			$fileToRestore =  'files_versions' . $filename . '.v' . $revision;
351
-
352
-			// Restore encrypted version of the old file for the newly restored file
353
-			// This has to happen manually here since the file is manually copied below
354
-			$oldVersion = $users_view->getFileInfo($fileToRestore)->getEncryptedVersion();
355
-			$oldFileInfo = $users_view->getFileInfo($fileToRestore);
356
-			$cache = $fileInfo->getStorage()->getCache();
357
-			$cache->update(
358
-				$fileInfo->getId(), [
359
-					'encrypted' => $oldVersion,
360
-					'encryptedVersion' => $oldVersion,
361
-					'size' => $oldFileInfo->getSize()
362
-				]
363
-			);
364
-
365
-			// rollback
366
-			if (self::copyFileContents($users_view, $fileToRestore, 'files' . $filename)) {
367
-				$files_view->touch($file, $revision);
368
-				Storage::scheduleExpire($uid, $file);
369
-				\OC_Hook::emit('\OCP\Versions', 'rollback', array(
370
-					'path' => $filename,
371
-					'revision' => $revision,
372
-				));
373
-				return true;
374
-			} else if ($versionCreated) {
375
-				self::deleteVersion($users_view, $version);
376
-			}
377
-		}
378
-		return false;
379
-
380
-	}
381
-
382
-	/**
383
-	 * Stream copy file contents from $path1 to $path2
384
-	 *
385
-	 * @param View $view view to use for copying
386
-	 * @param string $path1 source file to copy
387
-	 * @param string $path2 target file
388
-	 *
389
-	 * @return bool true for success, false otherwise
390
-	 */
391
-	private static function copyFileContents($view, $path1, $path2) {
392
-		/** @var \OC\Files\Storage\Storage $storage1 */
393
-		list($storage1, $internalPath1) = $view->resolvePath($path1);
394
-		/** @var \OC\Files\Storage\Storage $storage2 */
395
-		list($storage2, $internalPath2) = $view->resolvePath($path2);
396
-
397
-		$view->lockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
398
-		$view->lockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
399
-
400
-		// TODO add a proper way of overwriting a file while maintaining file ids
401
-		if ($storage1->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage') || $storage2->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage')) {
402
-			$source = $storage1->fopen($internalPath1, 'r');
403
-			$target = $storage2->fopen($internalPath2, 'w');
404
-			list(, $result) = \OC_Helper::streamCopy($source, $target);
405
-			fclose($source);
406
-			fclose($target);
407
-
408
-			if ($result !== false) {
409
-				$storage1->unlink($internalPath1);
410
-			}
411
-		} else {
412
-			$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
413
-		}
414
-
415
-		$view->unlockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
416
-		$view->unlockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
417
-
418
-		return ($result !== false);
419
-	}
420
-
421
-	/**
422
-	 * get a list of all available versions of a file in descending chronological order
423
-	 * @param string $uid user id from the owner of the file
424
-	 * @param string $filename file to find versions of, relative to the user files dir
425
-	 * @param string $userFullPath
426
-	 * @return array versions newest version first
427
-	 */
428
-	public static function getVersions($uid, $filename, $userFullPath = '') {
429
-		$versions = array();
430
-		if (empty($filename)) {
431
-			return $versions;
432
-		}
433
-		// fetch for old versions
434
-		$view = new View('/' . $uid . '/');
435
-
436
-		$pathinfo = pathinfo($filename);
437
-		$versionedFile = $pathinfo['basename'];
438
-
439
-		$dir = Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
440
-
441
-		$dirContent = false;
442
-		if ($view->is_dir($dir)) {
443
-			$dirContent = $view->opendir($dir);
444
-		}
445
-
446
-		if ($dirContent === false) {
447
-			return $versions;
448
-		}
449
-
450
-		if (is_resource($dirContent)) {
451
-			while (($entryName = readdir($dirContent)) !== false) {
452
-				if (!Filesystem::isIgnoredDir($entryName)) {
453
-					$pathparts = pathinfo($entryName);
454
-					$filename = $pathparts['filename'];
455
-					if ($filename === $versionedFile) {
456
-						$pathparts = pathinfo($entryName);
457
-						$timestamp = substr($pathparts['extension'], 1);
458
-						$filename = $pathparts['filename'];
459
-						$key = $timestamp . '#' . $filename;
460
-						$versions[$key]['version'] = $timestamp;
461
-						$versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp($timestamp);
462
-						if (empty($userFullPath)) {
463
-							$versions[$key]['preview'] = '';
464
-						} else {
465
-							$versions[$key]['preview'] = \OC::$server->getURLGenerator('files_version.Preview.getPreview', ['file' => $userFullPath, 'version' => $timestamp]);
466
-						}
467
-						$versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
468
-						$versions[$key]['name'] = $versionedFile;
469
-						$versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
470
-						$versions[$key]['mimetype'] = \OC::$server->getMimeTypeDetector()->detectPath($versionedFile);
471
-					}
472
-				}
473
-			}
474
-			closedir($dirContent);
475
-		}
476
-
477
-		// sort with newest version first
478
-		krsort($versions);
479
-
480
-		return $versions;
481
-	}
482
-
483
-	/**
484
-	 * Expire versions that older than max version retention time
485
-	 * @param string $uid
486
-	 */
487
-	public static function expireOlderThanMaxForUser($uid){
488
-		$expiration = self::getExpiration();
489
-		$threshold = $expiration->getMaxAgeAsTimestamp();
490
-		$versions = self::getAllVersions($uid);
491
-		if (!$threshold || !array_key_exists('all', $versions)) {
492
-			return;
493
-		}
494
-
495
-		$toDelete = [];
496
-		foreach (array_reverse($versions['all']) as $key => $version) {
497
-			if (intval($version['version'])<$threshold) {
498
-				$toDelete[$key] = $version;
499
-			} else {
500
-				//Versions are sorted by time - nothing mo to iterate.
501
-				break;
502
-			}
503
-		}
504
-
505
-		$view = new View('/' . $uid . '/files_versions');
506
-		if (!empty($toDelete)) {
507
-			foreach ($toDelete as $version) {
508
-				\OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT));
509
-				self::deleteVersion($view, $version['path'] . '.v' . $version['version']);
510
-				\OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT));
511
-			}
512
-		}
513
-	}
514
-
515
-	/**
516
-	 * translate a timestamp into a string like "5 days ago"
517
-	 * @param int $timestamp
518
-	 * @return string for example "5 days ago"
519
-	 */
520
-	private static function getHumanReadableTimestamp($timestamp) {
521
-
522
-		$diff = time() - $timestamp;
523
-
524
-		if ($diff < 60) { // first minute
525
-			return  $diff . " seconds ago";
526
-		} elseif ($diff < 3600) { //first hour
527
-			return round($diff / 60) . " minutes ago";
528
-		} elseif ($diff < 86400) { // first day
529
-			return round($diff / 3600) . " hours ago";
530
-		} elseif ($diff < 604800) { //first week
531
-			return round($diff / 86400) . " days ago";
532
-		} elseif ($diff < 2419200) { //first month
533
-			return round($diff / 604800) . " weeks ago";
534
-		} elseif ($diff < 29030400) { // first year
535
-			return round($diff / 2419200) . " months ago";
536
-		} else {
537
-			return round($diff / 29030400) . " years ago";
538
-		}
539
-
540
-	}
541
-
542
-	/**
543
-	 * returns all stored file versions from a given user
544
-	 * @param string $uid id of the user
545
-	 * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
546
-	 */
547
-	private static function getAllVersions($uid) {
548
-		$view = new View('/' . $uid . '/');
549
-		$dirs = array(self::VERSIONS_ROOT);
550
-		$versions = array();
551
-
552
-		while (!empty($dirs)) {
553
-			$dir = array_pop($dirs);
554
-			$files = $view->getDirectoryContent($dir);
555
-
556
-			foreach ($files as $file) {
557
-				$fileData = $file->getData();
558
-				$filePath = $dir . '/' . $fileData['name'];
559
-				if ($file['type'] === 'dir') {
560
-					array_push($dirs, $filePath);
561
-				} else {
562
-					$versionsBegin = strrpos($filePath, '.v');
563
-					$relPathStart = strlen(self::VERSIONS_ROOT);
564
-					$version = substr($filePath, $versionsBegin + 2);
565
-					$relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
566
-					$key = $version . '#' . $relpath;
567
-					$versions[$key] = array('path' => $relpath, 'timestamp' => $version);
568
-				}
569
-			}
570
-		}
571
-
572
-		// newest version first
573
-		krsort($versions);
574
-
575
-		$result = array();
576
-
577
-		foreach ($versions as $key => $value) {
578
-			$size = $view->filesize(self::VERSIONS_ROOT.'/'.$value['path'].'.v'.$value['timestamp']);
579
-			$filename = $value['path'];
580
-
581
-			$result['all'][$key]['version'] = $value['timestamp'];
582
-			$result['all'][$key]['path'] = $filename;
583
-			$result['all'][$key]['size'] = $size;
584
-
585
-			$result['by_file'][$filename][$key]['version'] = $value['timestamp'];
586
-			$result['by_file'][$filename][$key]['path'] = $filename;
587
-			$result['by_file'][$filename][$key]['size'] = $size;
588
-		}
589
-
590
-		return $result;
591
-	}
592
-
593
-	/**
594
-	 * get list of files we want to expire
595
-	 * @param array $versions list of versions
596
-	 * @param integer $time
597
-	 * @param bool $quotaExceeded is versions storage limit reached
598
-	 * @return array containing the list of to deleted versions and the size of them
599
-	 */
600
-	protected static function getExpireList($time, $versions, $quotaExceeded = false) {
601
-		$expiration = self::getExpiration();
602
-
603
-		if ($expiration->shouldAutoExpire()) {
604
-			list($toDelete, $size) = self::getAutoExpireList($time, $versions);
605
-		} else {
606
-			$size = 0;
607
-			$toDelete = [];  // versions we want to delete
608
-		}
609
-
610
-		foreach ($versions as $key => $version) {
611
-			if ($expiration->isExpired($version['version'], $quotaExceeded) && !isset($toDelete[$key])) {
612
-				$size += $version['size'];
613
-				$toDelete[$key] = $version['path'] . '.v' . $version['version'];
614
-			}
615
-		}
616
-
617
-		return [$toDelete, $size];
618
-	}
619
-
620
-	/**
621
-	 * get list of files we want to expire
622
-	 * @param array $versions list of versions
623
-	 * @param integer $time
624
-	 * @return array containing the list of to deleted versions and the size of them
625
-	 */
626
-	protected static function getAutoExpireList($time, $versions) {
627
-		$size = 0;
628
-		$toDelete = array();  // versions we want to delete
629
-
630
-		$interval = 1;
631
-		$step = Storage::$max_versions_per_interval[$interval]['step'];
632
-		if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] == -1) {
633
-			$nextInterval = -1;
634
-		} else {
635
-			$nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
636
-		}
637
-
638
-		$firstVersion = reset($versions);
639
-		$firstKey = key($versions);
640
-		$prevTimestamp = $firstVersion['version'];
641
-		$nextVersion = $firstVersion['version'] - $step;
642
-		unset($versions[$firstKey]);
643
-
644
-		foreach ($versions as $key => $version) {
645
-			$newInterval = true;
646
-			while ($newInterval) {
647
-				if ($nextInterval == -1 || $prevTimestamp > $nextInterval) {
648
-					if ($version['version'] > $nextVersion) {
649
-						//distance between two version too small, mark to delete
650
-						$toDelete[$key] = $version['path'] . '.v' . $version['version'];
651
-						$size += $version['size'];
652
-						\OCP\Util::writeLog('files_versions', 'Mark to expire '. $version['path'] .' next version should be ' . $nextVersion . " or smaller. (prevTimestamp: " . $prevTimestamp . "; step: " . $step, \OCP\Util::INFO);
653
-					} else {
654
-						$nextVersion = $version['version'] - $step;
655
-						$prevTimestamp = $version['version'];
656
-					}
657
-					$newInterval = false; // version checked so we can move to the next one
658
-				} else { // time to move on to the next interval
659
-					$interval++;
660
-					$step = Storage::$max_versions_per_interval[$interval]['step'];
661
-					$nextVersion = $prevTimestamp - $step;
662
-					if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] == -1) {
663
-						$nextInterval = -1;
664
-					} else {
665
-						$nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
666
-					}
667
-					$newInterval = true; // we changed the interval -> check same version with new interval
668
-				}
669
-			}
670
-		}
671
-
672
-		return array($toDelete, $size);
673
-	}
674
-
675
-	/**
676
-	 * Schedule versions expiration for the given file
677
-	 *
678
-	 * @param string $uid owner of the file
679
-	 * @param string $fileName file/folder for which to schedule expiration
680
-	 */
681
-	private static function scheduleExpire($uid, $fileName) {
682
-		// let the admin disable auto expire
683
-		$expiration = self::getExpiration();
684
-		if ($expiration->isEnabled()) {
685
-			$command = new Expire($uid, $fileName);
686
-			\OC::$server->getCommandBus()->push($command);
687
-		}
688
-	}
689
-
690
-	/**
691
-	 * Expire versions which exceed the quota.
692
-	 *
693
-	 * This will setup the filesystem for the given user but will not
694
-	 * tear it down afterwards.
695
-	 *
696
-	 * @param string $filename path to file to expire
697
-	 * @param string $uid user for which to expire the version
698
-	 * @return bool|int|null
699
-	 */
700
-	public static function expire($filename, $uid) {
701
-		$config = \OC::$server->getConfig();
702
-		$expiration = self::getExpiration();
703
-
704
-		if($config->getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true' && $expiration->isEnabled()) {
705
-			// get available disk space for user
706
-			$user = \OC::$server->getUserManager()->get($uid);
707
-			if (is_null($user)) {
708
-				\OCP\Util::writeLog('files_versions', 'Backends provided no user object for ' . $uid, \OCP\Util::ERROR);
709
-				throw new \OC\User\NoUserException('Backends provided no user object for ' . $uid);
710
-			}
711
-
712
-			\OC_Util::setupFS($uid);
713
-
714
-			if (!Filesystem::file_exists($filename)) {
715
-				return false;
716
-			}
717
-
718
-			if (empty($filename)) {
719
-				// file maybe renamed or deleted
720
-				return false;
721
-			}
722
-			$versionsFileview = new View('/'.$uid.'/files_versions');
723
-
724
-			$softQuota = true;
725
-			$quota = $user->getQuota();
726
-			if ( $quota === null || $quota === 'none' ) {
727
-				$quota = Filesystem::free_space('/');
728
-				$softQuota = false;
729
-			} else {
730
-				$quota = \OCP\Util::computerFileSize($quota);
731
-			}
732
-
733
-			// make sure that we have the current size of the version history
734
-			$versionsSize = self::getVersionsSize($uid);
735
-
736
-			// calculate available space for version history
737
-			// subtract size of files and current versions size from quota
738
-			if ($quota >= 0) {
739
-				if ($softQuota) {
740
-					$files_view = new View('/' . $uid . '/files');
741
-					$rootInfo = $files_view->getFileInfo('/', false);
742
-					$free = $quota - $rootInfo['size']; // remaining free space for user
743
-					if ($free > 0) {
744
-						$availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
745
-					} else {
746
-						$availableSpace = $free - $versionsSize;
747
-					}
748
-				} else {
749
-					$availableSpace = $quota;
750
-				}
751
-			} else {
752
-				$availableSpace = PHP_INT_MAX;
753
-			}
754
-
755
-			$allVersions = Storage::getVersions($uid, $filename);
756
-
757
-			$time = time();
758
-			list($toDelete, $sizeOfDeletedVersions) = self::getExpireList($time, $allVersions, $availableSpace <= 0);
759
-
760
-			$availableSpace = $availableSpace + $sizeOfDeletedVersions;
761
-			$versionsSize = $versionsSize - $sizeOfDeletedVersions;
762
-
763
-			// if still not enough free space we rearrange the versions from all files
764
-			if ($availableSpace <= 0) {
765
-				$result = Storage::getAllVersions($uid);
766
-				$allVersions = $result['all'];
767
-
768
-				foreach ($result['by_file'] as $versions) {
769
-					list($toDeleteNew, $size) = self::getExpireList($time, $versions, $availableSpace <= 0);
770
-					$toDelete = array_merge($toDelete, $toDeleteNew);
771
-					$sizeOfDeletedVersions += $size;
772
-				}
773
-				$availableSpace = $availableSpace + $sizeOfDeletedVersions;
774
-				$versionsSize = $versionsSize - $sizeOfDeletedVersions;
775
-			}
776
-
777
-			foreach($toDelete as $key => $path) {
778
-				\OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
779
-				self::deleteVersion($versionsFileview, $path);
780
-				\OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
781
-				unset($allVersions[$key]); // update array with the versions we keep
782
-				\OCP\Util::writeLog('files_versions', "Expire: " . $path, \OCP\Util::INFO);
783
-			}
784
-
785
-			// Check if enough space is available after versions are rearranged.
786
-			// If not we delete the oldest versions until we meet the size limit for versions,
787
-			// but always keep the two latest versions
788
-			$numOfVersions = count($allVersions) -2 ;
789
-			$i = 0;
790
-			// sort oldest first and make sure that we start at the first element
791
-			ksort($allVersions);
792
-			reset($allVersions);
793
-			while ($availableSpace < 0 && $i < $numOfVersions) {
794
-				$version = current($allVersions);
795
-				\OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
796
-				self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
797
-				\OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
798
-				\OCP\Util::writeLog('files_versions', 'running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'] , \OCP\Util::INFO);
799
-				$versionsSize -= $version['size'];
800
-				$availableSpace += $version['size'];
801
-				next($allVersions);
802
-				$i++;
803
-			}
804
-
805
-			return $versionsSize; // finally return the new size of the version history
806
-		}
807
-
808
-		return false;
809
-	}
810
-
811
-	/**
812
-	 * Create recursively missing directories inside of files_versions
813
-	 * that match the given path to a file.
814
-	 *
815
-	 * @param string $filename $path to a file, relative to the user's
816
-	 * "files" folder
817
-	 * @param View $view view on data/user/
818
-	 */
819
-	private static function createMissingDirectories($filename, $view) {
820
-		$dirname = Filesystem::normalizePath(dirname($filename));
821
-		$dirParts = explode('/', $dirname);
822
-		$dir = "/files_versions";
823
-		foreach ($dirParts as $part) {
824
-			$dir = $dir . '/' . $part;
825
-			if (!$view->file_exists($dir)) {
826
-				$view->mkdir($dir);
827
-			}
828
-		}
829
-	}
830
-
831
-	/**
832
-	 * Static workaround
833
-	 * @return Expiration
834
-	 */
835
-	protected static function getExpiration(){
836
-		if (is_null(self::$application)) {
837
-			self::$application = new Application();
838
-		}
839
-		return self::$application->getContainer()->query('Expiration');
840
-	}
56
+    const DEFAULTENABLED=true;
57
+    const DEFAULTMAXSIZE=50; // unit: percentage; 50% of available disk space/quota
58
+    const VERSIONS_ROOT = 'files_versions/';
59
+
60
+    const DELETE_TRIGGER_MASTER_REMOVED = 0;
61
+    const DELETE_TRIGGER_RETENTION_CONSTRAINT = 1;
62
+    const DELETE_TRIGGER_QUOTA_EXCEEDED = 2;
63
+
64
+    // files for which we can remove the versions after the delete operation was successful
65
+    private static $deletedFiles = array();
66
+
67
+    private static $sourcePathAndUser = array();
68
+
69
+    private static $max_versions_per_interval = array(
70
+        //first 10sec, one version every 2sec
71
+        1 => array('intervalEndsAfter' => 10,      'step' => 2),
72
+        //next minute, one version every 10sec
73
+        2 => array('intervalEndsAfter' => 60,      'step' => 10),
74
+        //next hour, one version every minute
75
+        3 => array('intervalEndsAfter' => 3600,    'step' => 60),
76
+        //next 24h, one version every hour
77
+        4 => array('intervalEndsAfter' => 86400,   'step' => 3600),
78
+        //next 30days, one version per day
79
+        5 => array('intervalEndsAfter' => 2592000, 'step' => 86400),
80
+        //until the end one version per week
81
+        6 => array('intervalEndsAfter' => -1,      'step' => 604800),
82
+    );
83
+
84
+    /** @var \OCA\Files_Versions\AppInfo\Application */
85
+    private static $application;
86
+
87
+    /**
88
+     * get the UID of the owner of the file and the path to the file relative to
89
+     * owners files folder
90
+     *
91
+     * @param string $filename
92
+     * @return array
93
+     * @throws \OC\User\NoUserException
94
+     */
95
+    public static function getUidAndFilename($filename) {
96
+        $uid = Filesystem::getOwner($filename);
97
+        $userManager = \OC::$server->getUserManager();
98
+        // if the user with the UID doesn't exists, e.g. because the UID points
99
+        // to a remote user with a federated cloud ID we use the current logged-in
100
+        // user. We need a valid local user to create the versions
101
+        if (!$userManager->userExists($uid)) {
102
+            $uid = User::getUser();
103
+        }
104
+        Filesystem::initMountPoints($uid);
105
+        if ( $uid != User::getUser() ) {
106
+            $info = Filesystem::getFileInfo($filename);
107
+            $ownerView = new View('/'.$uid.'/files');
108
+            try {
109
+                $filename = $ownerView->getPath($info['fileid']);
110
+                // make sure that the file name doesn't end with a trailing slash
111
+                // can for example happen single files shared across servers
112
+                $filename = rtrim($filename, '/');
113
+            } catch (NotFoundException $e) {
114
+                $filename = null;
115
+            }
116
+        }
117
+        return [$uid, $filename];
118
+    }
119
+
120
+    /**
121
+     * Remember the owner and the owner path of the source file
122
+     *
123
+     * @param string $source source path
124
+     */
125
+    public static function setSourcePathAndUser($source) {
126
+        list($uid, $path) = self::getUidAndFilename($source);
127
+        self::$sourcePathAndUser[$source] = array('uid' => $uid, 'path' => $path);
128
+    }
129
+
130
+    /**
131
+     * Gets the owner and the owner path from the source path
132
+     *
133
+     * @param string $source source path
134
+     * @return array with user id and path
135
+     */
136
+    public static function getSourcePathAndUser($source) {
137
+
138
+        if (isset(self::$sourcePathAndUser[$source])) {
139
+            $uid = self::$sourcePathAndUser[$source]['uid'];
140
+            $path = self::$sourcePathAndUser[$source]['path'];
141
+            unset(self::$sourcePathAndUser[$source]);
142
+        } else {
143
+            $uid = $path = false;
144
+        }
145
+        return array($uid, $path);
146
+    }
147
+
148
+    /**
149
+     * get current size of all versions from a given user
150
+     *
151
+     * @param string $user user who owns the versions
152
+     * @return int versions size
153
+     */
154
+    private static function getVersionsSize($user) {
155
+        $view = new View('/' . $user);
156
+        $fileInfo = $view->getFileInfo('/files_versions');
157
+        return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
158
+    }
159
+
160
+    /**
161
+     * store a new version of a file.
162
+     */
163
+    public static function store($filename) {
164
+        if(\OC::$server->getConfig()->getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true') {
165
+
166
+            // if the file gets streamed we need to remove the .part extension
167
+            // to get the right target
168
+            $ext = pathinfo($filename, PATHINFO_EXTENSION);
169
+            if ($ext === 'part') {
170
+                $filename = substr($filename, 0, strlen($filename) - 5);
171
+            }
172
+
173
+            // we only handle existing files
174
+            if (! Filesystem::file_exists($filename) || Filesystem::is_dir($filename)) {
175
+                return false;
176
+            }
177
+
178
+            list($uid, $filename) = self::getUidAndFilename($filename);
179
+
180
+            $files_view = new View('/'.$uid .'/files');
181
+            $users_view = new View('/'.$uid);
182
+
183
+            // no use making versions for empty files
184
+            if ($files_view->filesize($filename) === 0) {
185
+                return false;
186
+            }
187
+
188
+            // create all parent folders
189
+            self::createMissingDirectories($filename, $users_view);
190
+
191
+            self::scheduleExpire($uid, $filename);
192
+
193
+            // store a new version of a file
194
+            $mtime = $users_view->filemtime('files/' . $filename);
195
+            $users_view->copy('files/' . $filename, 'files_versions/' . $filename . '.v' . $mtime);
196
+            // call getFileInfo to enforce a file cache entry for the new version
197
+            $users_view->getFileInfo('files_versions/' . $filename . '.v' . $mtime);
198
+        }
199
+    }
200
+
201
+
202
+    /**
203
+     * mark file as deleted so that we can remove the versions if the file is gone
204
+     * @param string $path
205
+     */
206
+    public static function markDeletedFile($path) {
207
+        list($uid, $filename) = self::getUidAndFilename($path);
208
+        self::$deletedFiles[$path] = array(
209
+            'uid' => $uid,
210
+            'filename' => $filename);
211
+    }
212
+
213
+    /**
214
+     * delete the version from the storage and cache
215
+     *
216
+     * @param View $view
217
+     * @param string $path
218
+     */
219
+    protected static function deleteVersion($view, $path) {
220
+        $view->unlink($path);
221
+        /**
222
+         * @var \OC\Files\Storage\Storage $storage
223
+         * @var string $internalPath
224
+         */
225
+        list($storage, $internalPath) = $view->resolvePath($path);
226
+        $cache = $storage->getCache($internalPath);
227
+        $cache->remove($internalPath);
228
+    }
229
+
230
+    /**
231
+     * Delete versions of a file
232
+     */
233
+    public static function delete($path) {
234
+
235
+        $deletedFile = self::$deletedFiles[$path];
236
+        $uid = $deletedFile['uid'];
237
+        $filename = $deletedFile['filename'];
238
+
239
+        if (!Filesystem::file_exists($path)) {
240
+
241
+            $view = new View('/' . $uid . '/files_versions');
242
+
243
+            $versions = self::getVersions($uid, $filename);
244
+            if (!empty($versions)) {
245
+                foreach ($versions as $v) {
246
+                    \OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED));
247
+                    self::deleteVersion($view, $filename . '.v' . $v['version']);
248
+                    \OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED));
249
+                }
250
+            }
251
+        }
252
+        unset(self::$deletedFiles[$path]);
253
+    }
254
+
255
+    /**
256
+     * Rename or copy versions of a file of the given paths
257
+     *
258
+     * @param string $sourcePath source path of the file to move, relative to
259
+     * the currently logged in user's "files" folder
260
+     * @param string $targetPath target path of the file to move, relative to
261
+     * the currently logged in user's "files" folder
262
+     * @param string $operation can be 'copy' or 'rename'
263
+     */
264
+    public static function renameOrCopy($sourcePath, $targetPath, $operation) {
265
+        list($sourceOwner, $sourcePath) = self::getSourcePathAndUser($sourcePath);
266
+
267
+        // it was a upload of a existing file if no old path exists
268
+        // in this case the pre-hook already called the store method and we can
269
+        // stop here
270
+        if ($sourcePath === false) {
271
+            return true;
272
+        }
273
+
274
+        list($targetOwner, $targetPath) = self::getUidAndFilename($targetPath);
275
+
276
+        $sourcePath = ltrim($sourcePath, '/');
277
+        $targetPath = ltrim($targetPath, '/');
278
+
279
+        $rootView = new View('');
280
+
281
+        // did we move a directory ?
282
+        if ($rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
283
+            // does the directory exists for versions too ?
284
+            if ($rootView->is_dir('/' . $sourceOwner . '/files_versions/' . $sourcePath)) {
285
+                // create missing dirs if necessary
286
+                self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
287
+
288
+                // move the directory containing the versions
289
+                $rootView->$operation(
290
+                    '/' . $sourceOwner . '/files_versions/' . $sourcePath,
291
+                    '/' . $targetOwner . '/files_versions/' . $targetPath
292
+                );
293
+            }
294
+        } else if ($versions = Storage::getVersions($sourceOwner, '/' . $sourcePath)) {
295
+            // create missing dirs if necessary
296
+            self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
297
+
298
+            foreach ($versions as $v) {
299
+                // move each version one by one to the target directory
300
+                $rootView->$operation(
301
+                    '/' . $sourceOwner . '/files_versions/' . $sourcePath.'.v' . $v['version'],
302
+                    '/' . $targetOwner . '/files_versions/' . $targetPath.'.v'.$v['version']
303
+                );
304
+            }
305
+        }
306
+
307
+        // if we moved versions directly for a file, schedule expiration check for that file
308
+        if (!$rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
309
+            self::scheduleExpire($targetOwner, $targetPath);
310
+        }
311
+
312
+    }
313
+
314
+    /**
315
+     * Rollback to an old version of a file.
316
+     *
317
+     * @param string $file file name
318
+     * @param int $revision revision timestamp
319
+     * @return bool
320
+     */
321
+    public static function rollback($file, $revision) {
322
+
323
+        if(\OC::$server->getConfig()->getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true') {
324
+            // add expected leading slash
325
+            $file = '/' . ltrim($file, '/');
326
+            list($uid, $filename) = self::getUidAndFilename($file);
327
+            if ($uid === null || trim($filename, '/') === '') {
328
+                return false;
329
+            }
330
+
331
+            $users_view = new View('/'.$uid);
332
+            $files_view = new View('/'. User::getUser().'/files');
333
+
334
+            $versionCreated = false;
335
+
336
+            $fileInfo = $files_view->getFileInfo($file);
337
+
338
+            // check if user has the permissions to revert a version
339
+            if (!$fileInfo->isUpdateable()) {
340
+                return false;
341
+            }
342
+
343
+            //first create a new version
344
+            $version = 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename);
345
+            if (!$users_view->file_exists($version)) {
346
+                $users_view->copy('files'.$filename, 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename));
347
+                $versionCreated = true;
348
+            }
349
+
350
+            $fileToRestore =  'files_versions' . $filename . '.v' . $revision;
351
+
352
+            // Restore encrypted version of the old file for the newly restored file
353
+            // This has to happen manually here since the file is manually copied below
354
+            $oldVersion = $users_view->getFileInfo($fileToRestore)->getEncryptedVersion();
355
+            $oldFileInfo = $users_view->getFileInfo($fileToRestore);
356
+            $cache = $fileInfo->getStorage()->getCache();
357
+            $cache->update(
358
+                $fileInfo->getId(), [
359
+                    'encrypted' => $oldVersion,
360
+                    'encryptedVersion' => $oldVersion,
361
+                    'size' => $oldFileInfo->getSize()
362
+                ]
363
+            );
364
+
365
+            // rollback
366
+            if (self::copyFileContents($users_view, $fileToRestore, 'files' . $filename)) {
367
+                $files_view->touch($file, $revision);
368
+                Storage::scheduleExpire($uid, $file);
369
+                \OC_Hook::emit('\OCP\Versions', 'rollback', array(
370
+                    'path' => $filename,
371
+                    'revision' => $revision,
372
+                ));
373
+                return true;
374
+            } else if ($versionCreated) {
375
+                self::deleteVersion($users_view, $version);
376
+            }
377
+        }
378
+        return false;
379
+
380
+    }
381
+
382
+    /**
383
+     * Stream copy file contents from $path1 to $path2
384
+     *
385
+     * @param View $view view to use for copying
386
+     * @param string $path1 source file to copy
387
+     * @param string $path2 target file
388
+     *
389
+     * @return bool true for success, false otherwise
390
+     */
391
+    private static function copyFileContents($view, $path1, $path2) {
392
+        /** @var \OC\Files\Storage\Storage $storage1 */
393
+        list($storage1, $internalPath1) = $view->resolvePath($path1);
394
+        /** @var \OC\Files\Storage\Storage $storage2 */
395
+        list($storage2, $internalPath2) = $view->resolvePath($path2);
396
+
397
+        $view->lockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
398
+        $view->lockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
399
+
400
+        // TODO add a proper way of overwriting a file while maintaining file ids
401
+        if ($storage1->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage') || $storage2->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage')) {
402
+            $source = $storage1->fopen($internalPath1, 'r');
403
+            $target = $storage2->fopen($internalPath2, 'w');
404
+            list(, $result) = \OC_Helper::streamCopy($source, $target);
405
+            fclose($source);
406
+            fclose($target);
407
+
408
+            if ($result !== false) {
409
+                $storage1->unlink($internalPath1);
410
+            }
411
+        } else {
412
+            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
413
+        }
414
+
415
+        $view->unlockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
416
+        $view->unlockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
417
+
418
+        return ($result !== false);
419
+    }
420
+
421
+    /**
422
+     * get a list of all available versions of a file in descending chronological order
423
+     * @param string $uid user id from the owner of the file
424
+     * @param string $filename file to find versions of, relative to the user files dir
425
+     * @param string $userFullPath
426
+     * @return array versions newest version first
427
+     */
428
+    public static function getVersions($uid, $filename, $userFullPath = '') {
429
+        $versions = array();
430
+        if (empty($filename)) {
431
+            return $versions;
432
+        }
433
+        // fetch for old versions
434
+        $view = new View('/' . $uid . '/');
435
+
436
+        $pathinfo = pathinfo($filename);
437
+        $versionedFile = $pathinfo['basename'];
438
+
439
+        $dir = Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
440
+
441
+        $dirContent = false;
442
+        if ($view->is_dir($dir)) {
443
+            $dirContent = $view->opendir($dir);
444
+        }
445
+
446
+        if ($dirContent === false) {
447
+            return $versions;
448
+        }
449
+
450
+        if (is_resource($dirContent)) {
451
+            while (($entryName = readdir($dirContent)) !== false) {
452
+                if (!Filesystem::isIgnoredDir($entryName)) {
453
+                    $pathparts = pathinfo($entryName);
454
+                    $filename = $pathparts['filename'];
455
+                    if ($filename === $versionedFile) {
456
+                        $pathparts = pathinfo($entryName);
457
+                        $timestamp = substr($pathparts['extension'], 1);
458
+                        $filename = $pathparts['filename'];
459
+                        $key = $timestamp . '#' . $filename;
460
+                        $versions[$key]['version'] = $timestamp;
461
+                        $versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp($timestamp);
462
+                        if (empty($userFullPath)) {
463
+                            $versions[$key]['preview'] = '';
464
+                        } else {
465
+                            $versions[$key]['preview'] = \OC::$server->getURLGenerator('files_version.Preview.getPreview', ['file' => $userFullPath, 'version' => $timestamp]);
466
+                        }
467
+                        $versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
468
+                        $versions[$key]['name'] = $versionedFile;
469
+                        $versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
470
+                        $versions[$key]['mimetype'] = \OC::$server->getMimeTypeDetector()->detectPath($versionedFile);
471
+                    }
472
+                }
473
+            }
474
+            closedir($dirContent);
475
+        }
476
+
477
+        // sort with newest version first
478
+        krsort($versions);
479
+
480
+        return $versions;
481
+    }
482
+
483
+    /**
484
+     * Expire versions that older than max version retention time
485
+     * @param string $uid
486
+     */
487
+    public static function expireOlderThanMaxForUser($uid){
488
+        $expiration = self::getExpiration();
489
+        $threshold = $expiration->getMaxAgeAsTimestamp();
490
+        $versions = self::getAllVersions($uid);
491
+        if (!$threshold || !array_key_exists('all', $versions)) {
492
+            return;
493
+        }
494
+
495
+        $toDelete = [];
496
+        foreach (array_reverse($versions['all']) as $key => $version) {
497
+            if (intval($version['version'])<$threshold) {
498
+                $toDelete[$key] = $version;
499
+            } else {
500
+                //Versions are sorted by time - nothing mo to iterate.
501
+                break;
502
+            }
503
+        }
504
+
505
+        $view = new View('/' . $uid . '/files_versions');
506
+        if (!empty($toDelete)) {
507
+            foreach ($toDelete as $version) {
508
+                \OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT));
509
+                self::deleteVersion($view, $version['path'] . '.v' . $version['version']);
510
+                \OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT));
511
+            }
512
+        }
513
+    }
514
+
515
+    /**
516
+     * translate a timestamp into a string like "5 days ago"
517
+     * @param int $timestamp
518
+     * @return string for example "5 days ago"
519
+     */
520
+    private static function getHumanReadableTimestamp($timestamp) {
521
+
522
+        $diff = time() - $timestamp;
523
+
524
+        if ($diff < 60) { // first minute
525
+            return  $diff . " seconds ago";
526
+        } elseif ($diff < 3600) { //first hour
527
+            return round($diff / 60) . " minutes ago";
528
+        } elseif ($diff < 86400) { // first day
529
+            return round($diff / 3600) . " hours ago";
530
+        } elseif ($diff < 604800) { //first week
531
+            return round($diff / 86400) . " days ago";
532
+        } elseif ($diff < 2419200) { //first month
533
+            return round($diff / 604800) . " weeks ago";
534
+        } elseif ($diff < 29030400) { // first year
535
+            return round($diff / 2419200) . " months ago";
536
+        } else {
537
+            return round($diff / 29030400) . " years ago";
538
+        }
539
+
540
+    }
541
+
542
+    /**
543
+     * returns all stored file versions from a given user
544
+     * @param string $uid id of the user
545
+     * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
546
+     */
547
+    private static function getAllVersions($uid) {
548
+        $view = new View('/' . $uid . '/');
549
+        $dirs = array(self::VERSIONS_ROOT);
550
+        $versions = array();
551
+
552
+        while (!empty($dirs)) {
553
+            $dir = array_pop($dirs);
554
+            $files = $view->getDirectoryContent($dir);
555
+
556
+            foreach ($files as $file) {
557
+                $fileData = $file->getData();
558
+                $filePath = $dir . '/' . $fileData['name'];
559
+                if ($file['type'] === 'dir') {
560
+                    array_push($dirs, $filePath);
561
+                } else {
562
+                    $versionsBegin = strrpos($filePath, '.v');
563
+                    $relPathStart = strlen(self::VERSIONS_ROOT);
564
+                    $version = substr($filePath, $versionsBegin + 2);
565
+                    $relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
566
+                    $key = $version . '#' . $relpath;
567
+                    $versions[$key] = array('path' => $relpath, 'timestamp' => $version);
568
+                }
569
+            }
570
+        }
571
+
572
+        // newest version first
573
+        krsort($versions);
574
+
575
+        $result = array();
576
+
577
+        foreach ($versions as $key => $value) {
578
+            $size = $view->filesize(self::VERSIONS_ROOT.'/'.$value['path'].'.v'.$value['timestamp']);
579
+            $filename = $value['path'];
580
+
581
+            $result['all'][$key]['version'] = $value['timestamp'];
582
+            $result['all'][$key]['path'] = $filename;
583
+            $result['all'][$key]['size'] = $size;
584
+
585
+            $result['by_file'][$filename][$key]['version'] = $value['timestamp'];
586
+            $result['by_file'][$filename][$key]['path'] = $filename;
587
+            $result['by_file'][$filename][$key]['size'] = $size;
588
+        }
589
+
590
+        return $result;
591
+    }
592
+
593
+    /**
594
+     * get list of files we want to expire
595
+     * @param array $versions list of versions
596
+     * @param integer $time
597
+     * @param bool $quotaExceeded is versions storage limit reached
598
+     * @return array containing the list of to deleted versions and the size of them
599
+     */
600
+    protected static function getExpireList($time, $versions, $quotaExceeded = false) {
601
+        $expiration = self::getExpiration();
602
+
603
+        if ($expiration->shouldAutoExpire()) {
604
+            list($toDelete, $size) = self::getAutoExpireList($time, $versions);
605
+        } else {
606
+            $size = 0;
607
+            $toDelete = [];  // versions we want to delete
608
+        }
609
+
610
+        foreach ($versions as $key => $version) {
611
+            if ($expiration->isExpired($version['version'], $quotaExceeded) && !isset($toDelete[$key])) {
612
+                $size += $version['size'];
613
+                $toDelete[$key] = $version['path'] . '.v' . $version['version'];
614
+            }
615
+        }
616
+
617
+        return [$toDelete, $size];
618
+    }
619
+
620
+    /**
621
+     * get list of files we want to expire
622
+     * @param array $versions list of versions
623
+     * @param integer $time
624
+     * @return array containing the list of to deleted versions and the size of them
625
+     */
626
+    protected static function getAutoExpireList($time, $versions) {
627
+        $size = 0;
628
+        $toDelete = array();  // versions we want to delete
629
+
630
+        $interval = 1;
631
+        $step = Storage::$max_versions_per_interval[$interval]['step'];
632
+        if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] == -1) {
633
+            $nextInterval = -1;
634
+        } else {
635
+            $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
636
+        }
637
+
638
+        $firstVersion = reset($versions);
639
+        $firstKey = key($versions);
640
+        $prevTimestamp = $firstVersion['version'];
641
+        $nextVersion = $firstVersion['version'] - $step;
642
+        unset($versions[$firstKey]);
643
+
644
+        foreach ($versions as $key => $version) {
645
+            $newInterval = true;
646
+            while ($newInterval) {
647
+                if ($nextInterval == -1 || $prevTimestamp > $nextInterval) {
648
+                    if ($version['version'] > $nextVersion) {
649
+                        //distance between two version too small, mark to delete
650
+                        $toDelete[$key] = $version['path'] . '.v' . $version['version'];
651
+                        $size += $version['size'];
652
+                        \OCP\Util::writeLog('files_versions', 'Mark to expire '. $version['path'] .' next version should be ' . $nextVersion . " or smaller. (prevTimestamp: " . $prevTimestamp . "; step: " . $step, \OCP\Util::INFO);
653
+                    } else {
654
+                        $nextVersion = $version['version'] - $step;
655
+                        $prevTimestamp = $version['version'];
656
+                    }
657
+                    $newInterval = false; // version checked so we can move to the next one
658
+                } else { // time to move on to the next interval
659
+                    $interval++;
660
+                    $step = Storage::$max_versions_per_interval[$interval]['step'];
661
+                    $nextVersion = $prevTimestamp - $step;
662
+                    if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] == -1) {
663
+                        $nextInterval = -1;
664
+                    } else {
665
+                        $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
666
+                    }
667
+                    $newInterval = true; // we changed the interval -> check same version with new interval
668
+                }
669
+            }
670
+        }
671
+
672
+        return array($toDelete, $size);
673
+    }
674
+
675
+    /**
676
+     * Schedule versions expiration for the given file
677
+     *
678
+     * @param string $uid owner of the file
679
+     * @param string $fileName file/folder for which to schedule expiration
680
+     */
681
+    private static function scheduleExpire($uid, $fileName) {
682
+        // let the admin disable auto expire
683
+        $expiration = self::getExpiration();
684
+        if ($expiration->isEnabled()) {
685
+            $command = new Expire($uid, $fileName);
686
+            \OC::$server->getCommandBus()->push($command);
687
+        }
688
+    }
689
+
690
+    /**
691
+     * Expire versions which exceed the quota.
692
+     *
693
+     * This will setup the filesystem for the given user but will not
694
+     * tear it down afterwards.
695
+     *
696
+     * @param string $filename path to file to expire
697
+     * @param string $uid user for which to expire the version
698
+     * @return bool|int|null
699
+     */
700
+    public static function expire($filename, $uid) {
701
+        $config = \OC::$server->getConfig();
702
+        $expiration = self::getExpiration();
703
+
704
+        if($config->getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true' && $expiration->isEnabled()) {
705
+            // get available disk space for user
706
+            $user = \OC::$server->getUserManager()->get($uid);
707
+            if (is_null($user)) {
708
+                \OCP\Util::writeLog('files_versions', 'Backends provided no user object for ' . $uid, \OCP\Util::ERROR);
709
+                throw new \OC\User\NoUserException('Backends provided no user object for ' . $uid);
710
+            }
711
+
712
+            \OC_Util::setupFS($uid);
713
+
714
+            if (!Filesystem::file_exists($filename)) {
715
+                return false;
716
+            }
717
+
718
+            if (empty($filename)) {
719
+                // file maybe renamed or deleted
720
+                return false;
721
+            }
722
+            $versionsFileview = new View('/'.$uid.'/files_versions');
723
+
724
+            $softQuota = true;
725
+            $quota = $user->getQuota();
726
+            if ( $quota === null || $quota === 'none' ) {
727
+                $quota = Filesystem::free_space('/');
728
+                $softQuota = false;
729
+            } else {
730
+                $quota = \OCP\Util::computerFileSize($quota);
731
+            }
732
+
733
+            // make sure that we have the current size of the version history
734
+            $versionsSize = self::getVersionsSize($uid);
735
+
736
+            // calculate available space for version history
737
+            // subtract size of files and current versions size from quota
738
+            if ($quota >= 0) {
739
+                if ($softQuota) {
740
+                    $files_view = new View('/' . $uid . '/files');
741
+                    $rootInfo = $files_view->getFileInfo('/', false);
742
+                    $free = $quota - $rootInfo['size']; // remaining free space for user
743
+                    if ($free > 0) {
744
+                        $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
745
+                    } else {
746
+                        $availableSpace = $free - $versionsSize;
747
+                    }
748
+                } else {
749
+                    $availableSpace = $quota;
750
+                }
751
+            } else {
752
+                $availableSpace = PHP_INT_MAX;
753
+            }
754
+
755
+            $allVersions = Storage::getVersions($uid, $filename);
756
+
757
+            $time = time();
758
+            list($toDelete, $sizeOfDeletedVersions) = self::getExpireList($time, $allVersions, $availableSpace <= 0);
759
+
760
+            $availableSpace = $availableSpace + $sizeOfDeletedVersions;
761
+            $versionsSize = $versionsSize - $sizeOfDeletedVersions;
762
+
763
+            // if still not enough free space we rearrange the versions from all files
764
+            if ($availableSpace <= 0) {
765
+                $result = Storage::getAllVersions($uid);
766
+                $allVersions = $result['all'];
767
+
768
+                foreach ($result['by_file'] as $versions) {
769
+                    list($toDeleteNew, $size) = self::getExpireList($time, $versions, $availableSpace <= 0);
770
+                    $toDelete = array_merge($toDelete, $toDeleteNew);
771
+                    $sizeOfDeletedVersions += $size;
772
+                }
773
+                $availableSpace = $availableSpace + $sizeOfDeletedVersions;
774
+                $versionsSize = $versionsSize - $sizeOfDeletedVersions;
775
+            }
776
+
777
+            foreach($toDelete as $key => $path) {
778
+                \OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
779
+                self::deleteVersion($versionsFileview, $path);
780
+                \OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
781
+                unset($allVersions[$key]); // update array with the versions we keep
782
+                \OCP\Util::writeLog('files_versions', "Expire: " . $path, \OCP\Util::INFO);
783
+            }
784
+
785
+            // Check if enough space is available after versions are rearranged.
786
+            // If not we delete the oldest versions until we meet the size limit for versions,
787
+            // but always keep the two latest versions
788
+            $numOfVersions = count($allVersions) -2 ;
789
+            $i = 0;
790
+            // sort oldest first and make sure that we start at the first element
791
+            ksort($allVersions);
792
+            reset($allVersions);
793
+            while ($availableSpace < 0 && $i < $numOfVersions) {
794
+                $version = current($allVersions);
795
+                \OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
796
+                self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
797
+                \OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
798
+                \OCP\Util::writeLog('files_versions', 'running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'] , \OCP\Util::INFO);
799
+                $versionsSize -= $version['size'];
800
+                $availableSpace += $version['size'];
801
+                next($allVersions);
802
+                $i++;
803
+            }
804
+
805
+            return $versionsSize; // finally return the new size of the version history
806
+        }
807
+
808
+        return false;
809
+    }
810
+
811
+    /**
812
+     * Create recursively missing directories inside of files_versions
813
+     * that match the given path to a file.
814
+     *
815
+     * @param string $filename $path to a file, relative to the user's
816
+     * "files" folder
817
+     * @param View $view view on data/user/
818
+     */
819
+    private static function createMissingDirectories($filename, $view) {
820
+        $dirname = Filesystem::normalizePath(dirname($filename));
821
+        $dirParts = explode('/', $dirname);
822
+        $dir = "/files_versions";
823
+        foreach ($dirParts as $part) {
824
+            $dir = $dir . '/' . $part;
825
+            if (!$view->file_exists($dir)) {
826
+                $view->mkdir($dir);
827
+            }
828
+        }
829
+    }
830
+
831
+    /**
832
+     * Static workaround
833
+     * @return Expiration
834
+     */
835
+    protected static function getExpiration(){
836
+        if (is_null(self::$application)) {
837
+            self::$application = new Application();
838
+        }
839
+        return self::$application->getContainer()->query('Expiration');
840
+    }
841 841
 
842 842
 }
Please login to merge, or discard this patch.
Spacing   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -53,8 +53,8 @@  discard block
 block discarded – undo
53 53
 
54 54
 class Storage {
55 55
 
56
-	const DEFAULTENABLED=true;
57
-	const DEFAULTMAXSIZE=50; // unit: percentage; 50% of available disk space/quota
56
+	const DEFAULTENABLED = true;
57
+	const DEFAULTMAXSIZE = 50; // unit: percentage; 50% of available disk space/quota
58 58
 	const VERSIONS_ROOT = 'files_versions/';
59 59
 
60 60
 	const DELETE_TRIGGER_MASTER_REMOVED = 0;
@@ -68,17 +68,17 @@  discard block
 block discarded – undo
68 68
 
69 69
 	private static $max_versions_per_interval = array(
70 70
 		//first 10sec, one version every 2sec
71
-		1 => array('intervalEndsAfter' => 10,      'step' => 2),
71
+		1 => array('intervalEndsAfter' => 10, 'step' => 2),
72 72
 		//next minute, one version every 10sec
73
-		2 => array('intervalEndsAfter' => 60,      'step' => 10),
73
+		2 => array('intervalEndsAfter' => 60, 'step' => 10),
74 74
 		//next hour, one version every minute
75
-		3 => array('intervalEndsAfter' => 3600,    'step' => 60),
75
+		3 => array('intervalEndsAfter' => 3600, 'step' => 60),
76 76
 		//next 24h, one version every hour
77
-		4 => array('intervalEndsAfter' => 86400,   'step' => 3600),
77
+		4 => array('intervalEndsAfter' => 86400, 'step' => 3600),
78 78
 		//next 30days, one version per day
79 79
 		5 => array('intervalEndsAfter' => 2592000, 'step' => 86400),
80 80
 		//until the end one version per week
81
-		6 => array('intervalEndsAfter' => -1,      'step' => 604800),
81
+		6 => array('intervalEndsAfter' => -1, 'step' => 604800),
82 82
 	);
83 83
 
84 84
 	/** @var \OCA\Files_Versions\AppInfo\Application */
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 			$uid = User::getUser();
103 103
 		}
104 104
 		Filesystem::initMountPoints($uid);
105
-		if ( $uid != User::getUser() ) {
105
+		if ($uid != User::getUser()) {
106 106
 			$info = Filesystem::getFileInfo($filename);
107 107
 			$ownerView = new View('/'.$uid.'/files');
108 108
 			try {
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
 	 * @return int versions size
153 153
 	 */
154 154
 	private static function getVersionsSize($user) {
155
-		$view = new View('/' . $user);
155
+		$view = new View('/'.$user);
156 156
 		$fileInfo = $view->getFileInfo('/files_versions');
157 157
 		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
158 158
 	}
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 	 * store a new version of a file.
162 162
 	 */
163 163
 	public static function store($filename) {
164
-		if(\OC::$server->getConfig()->getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true') {
164
+		if (\OC::$server->getConfig()->getSystemValue('files_versions', Storage::DEFAULTENABLED) == 'true') {
165 165
 
166 166
 			// if the file gets streamed we need to remove the .part extension
167 167
 			// to get the right target
@@ -171,13 +171,13 @@  discard block
 block discarded – undo
171 171
 			}
172 172
 
173 173
 			// we only handle existing files
174
-			if (! Filesystem::file_exists($filename) || Filesystem::is_dir($filename)) {
174
+			if (!Filesystem::file_exists($filename) || Filesystem::is_dir($filename)) {
175 175
 				return false;
176 176
 			}
177 177
 
178 178
 			list($uid, $filename) = self::getUidAndFilename($filename);
179 179
 
180
-			$files_view = new View('/'.$uid .'/files');
180
+			$files_view = new View('/'.$uid.'/files');
181 181
 			$users_view = new View('/'.$uid);
182 182
 
183 183
 			// no use making versions for empty files
@@ -191,10 +191,10 @@  discard block
 block discarded – undo
191 191
 			self::scheduleExpire($uid, $filename);
192 192
 
193 193
 			// store a new version of a file
194
-			$mtime = $users_view->filemtime('files/' . $filename);
195
-			$users_view->copy('files/' . $filename, 'files_versions/' . $filename . '.v' . $mtime);
194
+			$mtime = $users_view->filemtime('files/'.$filename);
195
+			$users_view->copy('files/'.$filename, 'files_versions/'.$filename.'.v'.$mtime);
196 196
 			// call getFileInfo to enforce a file cache entry for the new version
197
-			$users_view->getFileInfo('files_versions/' . $filename . '.v' . $mtime);
197
+			$users_view->getFileInfo('files_versions/'.$filename.'.v'.$mtime);
198 198
 		}
199 199
 	}
200 200
 
@@ -238,14 +238,14 @@  discard block
 block discarded – undo
238 238
 
239 239
 		if (!Filesystem::file_exists($path)) {
240 240
 
241
-			$view = new View('/' . $uid . '/files_versions');
241
+			$view = new View('/'.$uid.'/files_versions');
242 242
 
243 243
 			$versions = self::getVersions($uid, $filename);
244 244
 			if (!empty($versions)) {
245 245
 				foreach ($versions as $v) {
246
-					\OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED));
247
-					self::deleteVersion($view, $filename . '.v' . $v['version']);
248
-					\OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED));
246
+					\OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $path.$v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED));
247
+					self::deleteVersion($view, $filename.'.v'.$v['version']);
248
+					\OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $path.$v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED));
249 249
 				}
250 250
 			}
251 251
 		}
@@ -279,33 +279,33 @@  discard block
 block discarded – undo
279 279
 		$rootView = new View('');
280 280
 
281 281
 		// did we move a directory ?
282
-		if ($rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
282
+		if ($rootView->is_dir('/'.$targetOwner.'/files/'.$targetPath)) {
283 283
 			// does the directory exists for versions too ?
284
-			if ($rootView->is_dir('/' . $sourceOwner . '/files_versions/' . $sourcePath)) {
284
+			if ($rootView->is_dir('/'.$sourceOwner.'/files_versions/'.$sourcePath)) {
285 285
 				// create missing dirs if necessary
286
-				self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
286
+				self::createMissingDirectories($targetPath, new View('/'.$targetOwner));
287 287
 
288 288
 				// move the directory containing the versions
289 289
 				$rootView->$operation(
290
-					'/' . $sourceOwner . '/files_versions/' . $sourcePath,
291
-					'/' . $targetOwner . '/files_versions/' . $targetPath
290
+					'/'.$sourceOwner.'/files_versions/'.$sourcePath,
291
+					'/'.$targetOwner.'/files_versions/'.$targetPath
292 292
 				);
293 293
 			}
294
-		} else if ($versions = Storage::getVersions($sourceOwner, '/' . $sourcePath)) {
294
+		} else if ($versions = Storage::getVersions($sourceOwner, '/'.$sourcePath)) {
295 295
 			// create missing dirs if necessary
296
-			self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
296
+			self::createMissingDirectories($targetPath, new View('/'.$targetOwner));
297 297
 
298 298
 			foreach ($versions as $v) {
299 299
 				// move each version one by one to the target directory
300 300
 				$rootView->$operation(
301
-					'/' . $sourceOwner . '/files_versions/' . $sourcePath.'.v' . $v['version'],
302
-					'/' . $targetOwner . '/files_versions/' . $targetPath.'.v'.$v['version']
301
+					'/'.$sourceOwner.'/files_versions/'.$sourcePath.'.v'.$v['version'],
302
+					'/'.$targetOwner.'/files_versions/'.$targetPath.'.v'.$v['version']
303 303
 				);
304 304
 			}
305 305
 		}
306 306
 
307 307
 		// if we moved versions directly for a file, schedule expiration check for that file
308
-		if (!$rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
308
+		if (!$rootView->is_dir('/'.$targetOwner.'/files/'.$targetPath)) {
309 309
 			self::scheduleExpire($targetOwner, $targetPath);
310 310
 		}
311 311
 
@@ -320,16 +320,16 @@  discard block
 block discarded – undo
320 320
 	 */
321 321
 	public static function rollback($file, $revision) {
322 322
 
323
-		if(\OC::$server->getConfig()->getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true') {
323
+		if (\OC::$server->getConfig()->getSystemValue('files_versions', Storage::DEFAULTENABLED) == 'true') {
324 324
 			// add expected leading slash
325
-			$file = '/' . ltrim($file, '/');
325
+			$file = '/'.ltrim($file, '/');
326 326
 			list($uid, $filename) = self::getUidAndFilename($file);
327 327
 			if ($uid === null || trim($filename, '/') === '') {
328 328
 				return false;
329 329
 			}
330 330
 
331 331
 			$users_view = new View('/'.$uid);
332
-			$files_view = new View('/'. User::getUser().'/files');
332
+			$files_view = new View('/'.User::getUser().'/files');
333 333
 
334 334
 			$versionCreated = false;
335 335
 
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
 				$versionCreated = true;
348 348
 			}
349 349
 
350
-			$fileToRestore =  'files_versions' . $filename . '.v' . $revision;
350
+			$fileToRestore = 'files_versions'.$filename.'.v'.$revision;
351 351
 
352 352
 			// Restore encrypted version of the old file for the newly restored file
353 353
 			// This has to happen manually here since the file is manually copied below
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
 			);
364 364
 
365 365
 			// rollback
366
-			if (self::copyFileContents($users_view, $fileToRestore, 'files' . $filename)) {
366
+			if (self::copyFileContents($users_view, $fileToRestore, 'files'.$filename)) {
367 367
 				$files_view->touch($file, $revision);
368 368
 				Storage::scheduleExpire($uid, $file);
369 369
 				\OC_Hook::emit('\OCP\Versions', 'rollback', array(
@@ -431,12 +431,12 @@  discard block
 block discarded – undo
431 431
 			return $versions;
432 432
 		}
433 433
 		// fetch for old versions
434
-		$view = new View('/' . $uid . '/');
434
+		$view = new View('/'.$uid.'/');
435 435
 
436 436
 		$pathinfo = pathinfo($filename);
437 437
 		$versionedFile = $pathinfo['basename'];
438 438
 
439
-		$dir = Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
439
+		$dir = Filesystem::normalizePath(self::VERSIONS_ROOT.'/'.$pathinfo['dirname']);
440 440
 
441 441
 		$dirContent = false;
442 442
 		if ($view->is_dir($dir)) {
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
 						$pathparts = pathinfo($entryName);
457 457
 						$timestamp = substr($pathparts['extension'], 1);
458 458
 						$filename = $pathparts['filename'];
459
-						$key = $timestamp . '#' . $filename;
459
+						$key = $timestamp.'#'.$filename;
460 460
 						$versions[$key]['version'] = $timestamp;
461 461
 						$versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp($timestamp);
462 462
 						if (empty($userFullPath)) {
@@ -464,9 +464,9 @@  discard block
 block discarded – undo
464 464
 						} else {
465 465
 							$versions[$key]['preview'] = \OC::$server->getURLGenerator('files_version.Preview.getPreview', ['file' => $userFullPath, 'version' => $timestamp]);
466 466
 						}
467
-						$versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
467
+						$versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'].'/'.$filename);
468 468
 						$versions[$key]['name'] = $versionedFile;
469
-						$versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
469
+						$versions[$key]['size'] = $view->filesize($dir.'/'.$entryName);
470 470
 						$versions[$key]['mimetype'] = \OC::$server->getMimeTypeDetector()->detectPath($versionedFile);
471 471
 					}
472 472
 				}
@@ -484,7 +484,7 @@  discard block
 block discarded – undo
484 484
 	 * Expire versions that older than max version retention time
485 485
 	 * @param string $uid
486 486
 	 */
487
-	public static function expireOlderThanMaxForUser($uid){
487
+	public static function expireOlderThanMaxForUser($uid) {
488 488
 		$expiration = self::getExpiration();
489 489
 		$threshold = $expiration->getMaxAgeAsTimestamp();
490 490
 		$versions = self::getAllVersions($uid);
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
 
495 495
 		$toDelete = [];
496 496
 		foreach (array_reverse($versions['all']) as $key => $version) {
497
-			if (intval($version['version'])<$threshold) {
497
+			if (intval($version['version']) < $threshold) {
498 498
 				$toDelete[$key] = $version;
499 499
 			} else {
500 500
 				//Versions are sorted by time - nothing mo to iterate.
@@ -502,11 +502,11 @@  discard block
 block discarded – undo
502 502
 			}
503 503
 		}
504 504
 
505
-		$view = new View('/' . $uid . '/files_versions');
505
+		$view = new View('/'.$uid.'/files_versions');
506 506
 		if (!empty($toDelete)) {
507 507
 			foreach ($toDelete as $version) {
508 508
 				\OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT));
509
-				self::deleteVersion($view, $version['path'] . '.v' . $version['version']);
509
+				self::deleteVersion($view, $version['path'].'.v'.$version['version']);
510 510
 				\OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT));
511 511
 			}
512 512
 		}
@@ -522,19 +522,19 @@  discard block
 block discarded – undo
522 522
 		$diff = time() - $timestamp;
523 523
 
524 524
 		if ($diff < 60) { // first minute
525
-			return  $diff . " seconds ago";
525
+			return  $diff." seconds ago";
526 526
 		} elseif ($diff < 3600) { //first hour
527
-			return round($diff / 60) . " minutes ago";
527
+			return round($diff / 60)." minutes ago";
528 528
 		} elseif ($diff < 86400) { // first day
529
-			return round($diff / 3600) . " hours ago";
529
+			return round($diff / 3600)." hours ago";
530 530
 		} elseif ($diff < 604800) { //first week
531
-			return round($diff / 86400) . " days ago";
531
+			return round($diff / 86400)." days ago";
532 532
 		} elseif ($diff < 2419200) { //first month
533
-			return round($diff / 604800) . " weeks ago";
533
+			return round($diff / 604800)." weeks ago";
534 534
 		} elseif ($diff < 29030400) { // first year
535
-			return round($diff / 2419200) . " months ago";
535
+			return round($diff / 2419200)." months ago";
536 536
 		} else {
537
-			return round($diff / 29030400) . " years ago";
537
+			return round($diff / 29030400)." years ago";
538 538
 		}
539 539
 
540 540
 	}
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 	 * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
546 546
 	 */
547 547
 	private static function getAllVersions($uid) {
548
-		$view = new View('/' . $uid . '/');
548
+		$view = new View('/'.$uid.'/');
549 549
 		$dirs = array(self::VERSIONS_ROOT);
550 550
 		$versions = array();
551 551
 
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
 
556 556
 			foreach ($files as $file) {
557 557
 				$fileData = $file->getData();
558
-				$filePath = $dir . '/' . $fileData['name'];
558
+				$filePath = $dir.'/'.$fileData['name'];
559 559
 				if ($file['type'] === 'dir') {
560 560
 					array_push($dirs, $filePath);
561 561
 				} else {
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
 					$relPathStart = strlen(self::VERSIONS_ROOT);
564 564
 					$version = substr($filePath, $versionsBegin + 2);
565 565
 					$relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
566
-					$key = $version . '#' . $relpath;
566
+					$key = $version.'#'.$relpath;
567 567
 					$versions[$key] = array('path' => $relpath, 'timestamp' => $version);
568 568
 				}
569 569
 			}
@@ -604,13 +604,13 @@  discard block
 block discarded – undo
604 604
 			list($toDelete, $size) = self::getAutoExpireList($time, $versions);
605 605
 		} else {
606 606
 			$size = 0;
607
-			$toDelete = [];  // versions we want to delete
607
+			$toDelete = []; // versions we want to delete
608 608
 		}
609 609
 
610 610
 		foreach ($versions as $key => $version) {
611 611
 			if ($expiration->isExpired($version['version'], $quotaExceeded) && !isset($toDelete[$key])) {
612 612
 				$size += $version['size'];
613
-				$toDelete[$key] = $version['path'] . '.v' . $version['version'];
613
+				$toDelete[$key] = $version['path'].'.v'.$version['version'];
614 614
 			}
615 615
 		}
616 616
 
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
 	 */
626 626
 	protected static function getAutoExpireList($time, $versions) {
627 627
 		$size = 0;
628
-		$toDelete = array();  // versions we want to delete
628
+		$toDelete = array(); // versions we want to delete
629 629
 
630 630
 		$interval = 1;
631 631
 		$step = Storage::$max_versions_per_interval[$interval]['step'];
@@ -647,9 +647,9 @@  discard block
 block discarded – undo
647 647
 				if ($nextInterval == -1 || $prevTimestamp > $nextInterval) {
648 648
 					if ($version['version'] > $nextVersion) {
649 649
 						//distance between two version too small, mark to delete
650
-						$toDelete[$key] = $version['path'] . '.v' . $version['version'];
650
+						$toDelete[$key] = $version['path'].'.v'.$version['version'];
651 651
 						$size += $version['size'];
652
-						\OCP\Util::writeLog('files_versions', 'Mark to expire '. $version['path'] .' next version should be ' . $nextVersion . " or smaller. (prevTimestamp: " . $prevTimestamp . "; step: " . $step, \OCP\Util::INFO);
652
+						\OCP\Util::writeLog('files_versions', 'Mark to expire '.$version['path'].' next version should be '.$nextVersion." or smaller. (prevTimestamp: ".$prevTimestamp."; step: ".$step, \OCP\Util::INFO);
653 653
 					} else {
654 654
 						$nextVersion = $version['version'] - $step;
655 655
 						$prevTimestamp = $version['version'];
@@ -701,12 +701,12 @@  discard block
 block discarded – undo
701 701
 		$config = \OC::$server->getConfig();
702 702
 		$expiration = self::getExpiration();
703 703
 
704
-		if($config->getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true' && $expiration->isEnabled()) {
704
+		if ($config->getSystemValue('files_versions', Storage::DEFAULTENABLED) == 'true' && $expiration->isEnabled()) {
705 705
 			// get available disk space for user
706 706
 			$user = \OC::$server->getUserManager()->get($uid);
707 707
 			if (is_null($user)) {
708
-				\OCP\Util::writeLog('files_versions', 'Backends provided no user object for ' . $uid, \OCP\Util::ERROR);
709
-				throw new \OC\User\NoUserException('Backends provided no user object for ' . $uid);
708
+				\OCP\Util::writeLog('files_versions', 'Backends provided no user object for '.$uid, \OCP\Util::ERROR);
709
+				throw new \OC\User\NoUserException('Backends provided no user object for '.$uid);
710 710
 			}
711 711
 
712 712
 			\OC_Util::setupFS($uid);
@@ -723,7 +723,7 @@  discard block
 block discarded – undo
723 723
 
724 724
 			$softQuota = true;
725 725
 			$quota = $user->getQuota();
726
-			if ( $quota === null || $quota === 'none' ) {
726
+			if ($quota === null || $quota === 'none') {
727 727
 				$quota = Filesystem::free_space('/');
728 728
 				$softQuota = false;
729 729
 			} else {
@@ -737,7 +737,7 @@  discard block
 block discarded – undo
737 737
 			// subtract size of files and current versions size from quota
738 738
 			if ($quota >= 0) {
739 739
 				if ($softQuota) {
740
-					$files_view = new View('/' . $uid . '/files');
740
+					$files_view = new View('/'.$uid.'/files');
741 741
 					$rootInfo = $files_view->getFileInfo('/', false);
742 742
 					$free = $quota - $rootInfo['size']; // remaining free space for user
743 743
 					if ($free > 0) {
@@ -774,18 +774,18 @@  discard block
 block discarded – undo
774 774
 				$versionsSize = $versionsSize - $sizeOfDeletedVersions;
775 775
 			}
776 776
 
777
-			foreach($toDelete as $key => $path) {
777
+			foreach ($toDelete as $key => $path) {
778 778
 				\OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
779 779
 				self::deleteVersion($versionsFileview, $path);
780 780
 				\OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
781 781
 				unset($allVersions[$key]); // update array with the versions we keep
782
-				\OCP\Util::writeLog('files_versions', "Expire: " . $path, \OCP\Util::INFO);
782
+				\OCP\Util::writeLog('files_versions', "Expire: ".$path, \OCP\Util::INFO);
783 783
 			}
784 784
 
785 785
 			// Check if enough space is available after versions are rearranged.
786 786
 			// If not we delete the oldest versions until we meet the size limit for versions,
787 787
 			// but always keep the two latest versions
788
-			$numOfVersions = count($allVersions) -2 ;
788
+			$numOfVersions = count($allVersions) - 2;
789 789
 			$i = 0;
790 790
 			// sort oldest first and make sure that we start at the first element
791 791
 			ksort($allVersions);
@@ -793,9 +793,9 @@  discard block
 block discarded – undo
793 793
 			while ($availableSpace < 0 && $i < $numOfVersions) {
794 794
 				$version = current($allVersions);
795 795
 				\OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
796
-				self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
796
+				self::deleteVersion($versionsFileview, $version['path'].'.v'.$version['version']);
797 797
 				\OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
798
-				\OCP\Util::writeLog('files_versions', 'running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'] , \OCP\Util::INFO);
798
+				\OCP\Util::writeLog('files_versions', 'running out of space! Delete oldest version: '.$version['path'].'.v'.$version['version'], \OCP\Util::INFO);
799 799
 				$versionsSize -= $version['size'];
800 800
 				$availableSpace += $version['size'];
801 801
 				next($allVersions);
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
 		$dirParts = explode('/', $dirname);
822 822
 		$dir = "/files_versions";
823 823
 		foreach ($dirParts as $part) {
824
-			$dir = $dir . '/' . $part;
824
+			$dir = $dir.'/'.$part;
825 825
 			if (!$view->file_exists($dir)) {
826 826
 				$view->mkdir($dir);
827 827
 			}
@@ -832,7 +832,7 @@  discard block
 block discarded – undo
832 832
 	 * Static workaround
833 833
 	 * @return Expiration
834 834
 	 */
835
-	protected static function getExpiration(){
835
+	protected static function getExpiration() {
836 836
 		if (is_null(self::$application)) {
837 837
 			self::$application = new Application();
838 838
 		}
Please login to merge, or discard this patch.
apps/user_ldap/lib/Configuration.php 1 patch
Indentation   +463 added lines, -463 removed lines patch added patch discarded remove patch
@@ -36,492 +36,492 @@
 block discarded – undo
36 36
  */
37 37
 class Configuration {
38 38
 
39
-	protected $configPrefix = null;
40
-	protected $configRead = false;
39
+    protected $configPrefix = null;
40
+    protected $configRead = false;
41 41
 
42
-	//settings
43
-	protected $config = array(
44
-		'ldapHost' => null,
45
-		'ldapPort' => null,
46
-		'ldapBackupHost' => null,
47
-		'ldapBackupPort' => null,
48
-		'ldapBase' => null,
49
-		'ldapBaseUsers' => null,
50
-		'ldapBaseGroups' => null,
51
-		'ldapAgentName' => null,
52
-		'ldapAgentPassword' => null,
53
-		'ldapTLS' => null,
54
-		'turnOffCertCheck' => null,
55
-		'ldapIgnoreNamingRules' => null,
56
-		'ldapUserDisplayName' => null,
57
-		'ldapUserDisplayName2' => null,
58
-		'ldapGidNumber' => null,
59
-		'ldapUserFilterObjectclass' => null,
60
-		'ldapUserFilterGroups' => null,
61
-		'ldapUserFilter' => null,
62
-		'ldapUserFilterMode' => null,
63
-		'ldapGroupFilter' => null,
64
-		'ldapGroupFilterMode' => null,
65
-		'ldapGroupFilterObjectclass' => null,
66
-		'ldapGroupFilterGroups' => null,
67
-		'ldapGroupDisplayName' => null,
68
-		'ldapGroupMemberAssocAttr' => null,
69
-		'ldapLoginFilter' => null,
70
-		'ldapLoginFilterMode' => null,
71
-		'ldapLoginFilterEmail' => null,
72
-		'ldapLoginFilterUsername' => null,
73
-		'ldapLoginFilterAttributes' => null,
74
-		'ldapQuotaAttribute' => null,
75
-		'ldapQuotaDefault' => null,
76
-		'ldapEmailAttribute' => null,
77
-		'ldapCacheTTL' => null,
78
-		'ldapUuidUserAttribute' => 'auto',
79
-		'ldapUuidGroupAttribute' => 'auto',
80
-		'ldapOverrideMainServer' => false,
81
-		'ldapConfigurationActive' => false,
82
-		'ldapAttributesForUserSearch' => null,
83
-		'ldapAttributesForGroupSearch' => null,
84
-		'ldapExperiencedAdmin' => false,
85
-		'homeFolderNamingRule' => null,
86
-		'hasPagedResultSupport' => false,
87
-		'hasMemberOfFilterSupport' => false,
88
-		'useMemberOfToDetectMembership' => true,
89
-		'ldapExpertUsernameAttr' => null,
90
-		'ldapExpertUUIDUserAttr' => null,
91
-		'ldapExpertUUIDGroupAttr' => null,
92
-		'lastJpegPhotoLookup' => null,
93
-		'ldapNestedGroups' => false,
94
-		'ldapPagingSize' => null,
95
-		'turnOnPasswordChange' => false,
96
-		'ldapDynamicGroupMemberURL' => null,
97
-		'ldapDefaultPPolicyDN' => null,
98
-	);
42
+    //settings
43
+    protected $config = array(
44
+        'ldapHost' => null,
45
+        'ldapPort' => null,
46
+        'ldapBackupHost' => null,
47
+        'ldapBackupPort' => null,
48
+        'ldapBase' => null,
49
+        'ldapBaseUsers' => null,
50
+        'ldapBaseGroups' => null,
51
+        'ldapAgentName' => null,
52
+        'ldapAgentPassword' => null,
53
+        'ldapTLS' => null,
54
+        'turnOffCertCheck' => null,
55
+        'ldapIgnoreNamingRules' => null,
56
+        'ldapUserDisplayName' => null,
57
+        'ldapUserDisplayName2' => null,
58
+        'ldapGidNumber' => null,
59
+        'ldapUserFilterObjectclass' => null,
60
+        'ldapUserFilterGroups' => null,
61
+        'ldapUserFilter' => null,
62
+        'ldapUserFilterMode' => null,
63
+        'ldapGroupFilter' => null,
64
+        'ldapGroupFilterMode' => null,
65
+        'ldapGroupFilterObjectclass' => null,
66
+        'ldapGroupFilterGroups' => null,
67
+        'ldapGroupDisplayName' => null,
68
+        'ldapGroupMemberAssocAttr' => null,
69
+        'ldapLoginFilter' => null,
70
+        'ldapLoginFilterMode' => null,
71
+        'ldapLoginFilterEmail' => null,
72
+        'ldapLoginFilterUsername' => null,
73
+        'ldapLoginFilterAttributes' => null,
74
+        'ldapQuotaAttribute' => null,
75
+        'ldapQuotaDefault' => null,
76
+        'ldapEmailAttribute' => null,
77
+        'ldapCacheTTL' => null,
78
+        'ldapUuidUserAttribute' => 'auto',
79
+        'ldapUuidGroupAttribute' => 'auto',
80
+        'ldapOverrideMainServer' => false,
81
+        'ldapConfigurationActive' => false,
82
+        'ldapAttributesForUserSearch' => null,
83
+        'ldapAttributesForGroupSearch' => null,
84
+        'ldapExperiencedAdmin' => false,
85
+        'homeFolderNamingRule' => null,
86
+        'hasPagedResultSupport' => false,
87
+        'hasMemberOfFilterSupport' => false,
88
+        'useMemberOfToDetectMembership' => true,
89
+        'ldapExpertUsernameAttr' => null,
90
+        'ldapExpertUUIDUserAttr' => null,
91
+        'ldapExpertUUIDGroupAttr' => null,
92
+        'lastJpegPhotoLookup' => null,
93
+        'ldapNestedGroups' => false,
94
+        'ldapPagingSize' => null,
95
+        'turnOnPasswordChange' => false,
96
+        'ldapDynamicGroupMemberURL' => null,
97
+        'ldapDefaultPPolicyDN' => null,
98
+    );
99 99
 
100
-	/**
101
-	 * @param string $configPrefix
102
-	 * @param bool $autoRead
103
-	 */
104
-	public function __construct($configPrefix, $autoRead = true) {
105
-		$this->configPrefix = $configPrefix;
106
-		if($autoRead) {
107
-			$this->readConfiguration();
108
-		}
109
-	}
100
+    /**
101
+     * @param string $configPrefix
102
+     * @param bool $autoRead
103
+     */
104
+    public function __construct($configPrefix, $autoRead = true) {
105
+        $this->configPrefix = $configPrefix;
106
+        if($autoRead) {
107
+            $this->readConfiguration();
108
+        }
109
+    }
110 110
 
111
-	/**
112
-	 * @param string $name
113
-	 * @return mixed|null
114
-	 */
115
-	public function __get($name) {
116
-		if(isset($this->config[$name])) {
117
-			return $this->config[$name];
118
-		}
119
-		return null;
120
-	}
111
+    /**
112
+     * @param string $name
113
+     * @return mixed|null
114
+     */
115
+    public function __get($name) {
116
+        if(isset($this->config[$name])) {
117
+            return $this->config[$name];
118
+        }
119
+        return null;
120
+    }
121 121
 
122
-	/**
123
-	 * @param string $name
124
-	 * @param mixed $value
125
-	 */
126
-	public function __set($name, $value) {
127
-		$this->setConfiguration(array($name => $value));
128
-	}
122
+    /**
123
+     * @param string $name
124
+     * @param mixed $value
125
+     */
126
+    public function __set($name, $value) {
127
+        $this->setConfiguration(array($name => $value));
128
+    }
129 129
 
130
-	/**
131
-	 * @return array
132
-	 */
133
-	public function getConfiguration() {
134
-		return $this->config;
135
-	}
130
+    /**
131
+     * @return array
132
+     */
133
+    public function getConfiguration() {
134
+        return $this->config;
135
+    }
136 136
 
137
-	/**
138
-	 * set LDAP configuration with values delivered by an array, not read
139
-	 * from configuration. It does not save the configuration! To do so, you
140
-	 * must call saveConfiguration afterwards.
141
-	 * @param array $config array that holds the config parameters in an associated
142
-	 * array
143
-	 * @param array &$applied optional; array where the set fields will be given to
144
-	 * @return false|null
145
-	 */
146
-	public function setConfiguration($config, &$applied = null) {
147
-		if(!is_array($config)) {
148
-			return false;
149
-		}
137
+    /**
138
+     * set LDAP configuration with values delivered by an array, not read
139
+     * from configuration. It does not save the configuration! To do so, you
140
+     * must call saveConfiguration afterwards.
141
+     * @param array $config array that holds the config parameters in an associated
142
+     * array
143
+     * @param array &$applied optional; array where the set fields will be given to
144
+     * @return false|null
145
+     */
146
+    public function setConfiguration($config, &$applied = null) {
147
+        if(!is_array($config)) {
148
+            return false;
149
+        }
150 150
 
151
-		$cta = $this->getConfigTranslationArray();
152
-		foreach($config as $inputKey => $val) {
153
-			if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
154
-				$key = $cta[$inputKey];
155
-			} elseif(array_key_exists($inputKey, $this->config)) {
156
-				$key = $inputKey;
157
-			} else {
158
-				continue;
159
-			}
151
+        $cta = $this->getConfigTranslationArray();
152
+        foreach($config as $inputKey => $val) {
153
+            if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
154
+                $key = $cta[$inputKey];
155
+            } elseif(array_key_exists($inputKey, $this->config)) {
156
+                $key = $inputKey;
157
+            } else {
158
+                continue;
159
+            }
160 160
 
161
-			$setMethod = 'setValue';
162
-			switch($key) {
163
-				case 'ldapAgentPassword':
164
-					$setMethod = 'setRawValue';
165
-					break;
166
-				case 'homeFolderNamingRule':
167
-					$trimmedVal = trim($val);
168
-					if ($trimmedVal !== '' && strpos($val, 'attr:') === false) {
169
-						$val = 'attr:'.$trimmedVal;
170
-					}
171
-					break;
172
-				case 'ldapBase':
173
-				case 'ldapBaseUsers':
174
-				case 'ldapBaseGroups':
175
-				case 'ldapAttributesForUserSearch':
176
-				case 'ldapAttributesForGroupSearch':
177
-				case 'ldapUserFilterObjectclass':
178
-				case 'ldapUserFilterGroups':
179
-				case 'ldapGroupFilterObjectclass':
180
-				case 'ldapGroupFilterGroups':
181
-				case 'ldapLoginFilterAttributes':
182
-					$setMethod = 'setMultiLine';
183
-					break;
184
-			}
185
-			$this->$setMethod($key, $val);
186
-			if(is_array($applied)) {
187
-				$applied[] = $inputKey;
188
-			}
189
-		}
190
-		return null;
191
-	}
161
+            $setMethod = 'setValue';
162
+            switch($key) {
163
+                case 'ldapAgentPassword':
164
+                    $setMethod = 'setRawValue';
165
+                    break;
166
+                case 'homeFolderNamingRule':
167
+                    $trimmedVal = trim($val);
168
+                    if ($trimmedVal !== '' && strpos($val, 'attr:') === false) {
169
+                        $val = 'attr:'.$trimmedVal;
170
+                    }
171
+                    break;
172
+                case 'ldapBase':
173
+                case 'ldapBaseUsers':
174
+                case 'ldapBaseGroups':
175
+                case 'ldapAttributesForUserSearch':
176
+                case 'ldapAttributesForGroupSearch':
177
+                case 'ldapUserFilterObjectclass':
178
+                case 'ldapUserFilterGroups':
179
+                case 'ldapGroupFilterObjectclass':
180
+                case 'ldapGroupFilterGroups':
181
+                case 'ldapLoginFilterAttributes':
182
+                    $setMethod = 'setMultiLine';
183
+                    break;
184
+            }
185
+            $this->$setMethod($key, $val);
186
+            if(is_array($applied)) {
187
+                $applied[] = $inputKey;
188
+            }
189
+        }
190
+        return null;
191
+    }
192 192
 
193
-	public function readConfiguration() {
194
-		if(!$this->configRead && !is_null($this->configPrefix)) {
195
-			$cta = array_flip($this->getConfigTranslationArray());
196
-			foreach($this->config as $key => $val) {
197
-				if(!isset($cta[$key])) {
198
-					//some are determined
199
-					continue;
200
-				}
201
-				$dbKey = $cta[$key];
202
-				switch($key) {
203
-					case 'ldapBase':
204
-					case 'ldapBaseUsers':
205
-					case 'ldapBaseGroups':
206
-					case 'ldapAttributesForUserSearch':
207
-					case 'ldapAttributesForGroupSearch':
208
-					case 'ldapUserFilterObjectclass':
209
-					case 'ldapUserFilterGroups':
210
-					case 'ldapGroupFilterObjectclass':
211
-					case 'ldapGroupFilterGroups':
212
-					case 'ldapLoginFilterAttributes':
213
-						$readMethod = 'getMultiLine';
214
-						break;
215
-					case 'ldapIgnoreNamingRules':
216
-						$readMethod = 'getSystemValue';
217
-						$dbKey = $key;
218
-						break;
219
-					case 'ldapAgentPassword':
220
-						$readMethod = 'getPwd';
221
-						break;
222
-					case 'ldapUserDisplayName2':
223
-					case 'ldapGroupDisplayName':
224
-						$readMethod = 'getLcValue';
225
-						break;
226
-					case 'ldapUserDisplayName':
227
-					default:
228
-						// user display name does not lower case because
229
-						// we rely on an upper case N as indicator whether to
230
-						// auto-detect it or not. FIXME
231
-						$readMethod = 'getValue';
232
-						break;
233
-				}
234
-				$this->config[$key] = $this->$readMethod($dbKey);
235
-			}
236
-			$this->configRead = true;
237
-		}
238
-	}
193
+    public function readConfiguration() {
194
+        if(!$this->configRead && !is_null($this->configPrefix)) {
195
+            $cta = array_flip($this->getConfigTranslationArray());
196
+            foreach($this->config as $key => $val) {
197
+                if(!isset($cta[$key])) {
198
+                    //some are determined
199
+                    continue;
200
+                }
201
+                $dbKey = $cta[$key];
202
+                switch($key) {
203
+                    case 'ldapBase':
204
+                    case 'ldapBaseUsers':
205
+                    case 'ldapBaseGroups':
206
+                    case 'ldapAttributesForUserSearch':
207
+                    case 'ldapAttributesForGroupSearch':
208
+                    case 'ldapUserFilterObjectclass':
209
+                    case 'ldapUserFilterGroups':
210
+                    case 'ldapGroupFilterObjectclass':
211
+                    case 'ldapGroupFilterGroups':
212
+                    case 'ldapLoginFilterAttributes':
213
+                        $readMethod = 'getMultiLine';
214
+                        break;
215
+                    case 'ldapIgnoreNamingRules':
216
+                        $readMethod = 'getSystemValue';
217
+                        $dbKey = $key;
218
+                        break;
219
+                    case 'ldapAgentPassword':
220
+                        $readMethod = 'getPwd';
221
+                        break;
222
+                    case 'ldapUserDisplayName2':
223
+                    case 'ldapGroupDisplayName':
224
+                        $readMethod = 'getLcValue';
225
+                        break;
226
+                    case 'ldapUserDisplayName':
227
+                    default:
228
+                        // user display name does not lower case because
229
+                        // we rely on an upper case N as indicator whether to
230
+                        // auto-detect it or not. FIXME
231
+                        $readMethod = 'getValue';
232
+                        break;
233
+                }
234
+                $this->config[$key] = $this->$readMethod($dbKey);
235
+            }
236
+            $this->configRead = true;
237
+        }
238
+    }
239 239
 
240
-	/**
241
-	 * saves the current Configuration in the database
242
-	 */
243
-	public function saveConfiguration() {
244
-		$cta = array_flip($this->getConfigTranslationArray());
245
-		foreach($this->config as $key => $value) {
246
-			switch ($key) {
247
-				case 'ldapAgentPassword':
248
-					$value = base64_encode($value);
249
-					break;
250
-				case 'ldapBase':
251
-				case 'ldapBaseUsers':
252
-				case 'ldapBaseGroups':
253
-				case 'ldapAttributesForUserSearch':
254
-				case 'ldapAttributesForGroupSearch':
255
-				case 'ldapUserFilterObjectclass':
256
-				case 'ldapUserFilterGroups':
257
-				case 'ldapGroupFilterObjectclass':
258
-				case 'ldapGroupFilterGroups':
259
-				case 'ldapLoginFilterAttributes':
260
-					if(is_array($value)) {
261
-						$value = implode("\n", $value);
262
-					}
263
-					break;
264
-				//following options are not stored but detected, skip them
265
-				case 'ldapIgnoreNamingRules':
266
-				case 'hasPagedResultSupport':
267
-				case 'ldapUuidUserAttribute':
268
-				case 'ldapUuidGroupAttribute':
269
-					continue 2;
270
-			}
271
-			if(is_null($value)) {
272
-				$value = '';
273
-			}
274
-			$this->saveValue($cta[$key], $value);
275
-		}
276
-	}
240
+    /**
241
+     * saves the current Configuration in the database
242
+     */
243
+    public function saveConfiguration() {
244
+        $cta = array_flip($this->getConfigTranslationArray());
245
+        foreach($this->config as $key => $value) {
246
+            switch ($key) {
247
+                case 'ldapAgentPassword':
248
+                    $value = base64_encode($value);
249
+                    break;
250
+                case 'ldapBase':
251
+                case 'ldapBaseUsers':
252
+                case 'ldapBaseGroups':
253
+                case 'ldapAttributesForUserSearch':
254
+                case 'ldapAttributesForGroupSearch':
255
+                case 'ldapUserFilterObjectclass':
256
+                case 'ldapUserFilterGroups':
257
+                case 'ldapGroupFilterObjectclass':
258
+                case 'ldapGroupFilterGroups':
259
+                case 'ldapLoginFilterAttributes':
260
+                    if(is_array($value)) {
261
+                        $value = implode("\n", $value);
262
+                    }
263
+                    break;
264
+                //following options are not stored but detected, skip them
265
+                case 'ldapIgnoreNamingRules':
266
+                case 'hasPagedResultSupport':
267
+                case 'ldapUuidUserAttribute':
268
+                case 'ldapUuidGroupAttribute':
269
+                    continue 2;
270
+            }
271
+            if(is_null($value)) {
272
+                $value = '';
273
+            }
274
+            $this->saveValue($cta[$key], $value);
275
+        }
276
+    }
277 277
 
278
-	/**
279
-	 * @param string $varName
280
-	 * @return array|string
281
-	 */
282
-	protected function getMultiLine($varName) {
283
-		$value = $this->getValue($varName);
284
-		if(empty($value)) {
285
-			$value = '';
286
-		} else {
287
-			$value = preg_split('/\r\n|\r|\n/', $value);
288
-		}
278
+    /**
279
+     * @param string $varName
280
+     * @return array|string
281
+     */
282
+    protected function getMultiLine($varName) {
283
+        $value = $this->getValue($varName);
284
+        if(empty($value)) {
285
+            $value = '';
286
+        } else {
287
+            $value = preg_split('/\r\n|\r|\n/', $value);
288
+        }
289 289
 
290
-		return $value;
291
-	}
290
+        return $value;
291
+    }
292 292
 
293
-	/**
294
-	 * Sets multi-line values as arrays
295
-	 * 
296
-	 * @param string $varName name of config-key
297
-	 * @param array|string $value to set
298
-	 */
299
-	protected function setMultiLine($varName, $value) {
300
-		if(empty($value)) {
301
-			$value = '';
302
-		} else if (!is_array($value)) {
303
-			$value = preg_split('/\r\n|\r|\n|;/', $value);
304
-			if($value === false) {
305
-				$value = '';
306
-			}
307
-		}
293
+    /**
294
+     * Sets multi-line values as arrays
295
+     * 
296
+     * @param string $varName name of config-key
297
+     * @param array|string $value to set
298
+     */
299
+    protected function setMultiLine($varName, $value) {
300
+        if(empty($value)) {
301
+            $value = '';
302
+        } else if (!is_array($value)) {
303
+            $value = preg_split('/\r\n|\r|\n|;/', $value);
304
+            if($value === false) {
305
+                $value = '';
306
+            }
307
+        }
308 308
 
309
-		if(!is_array($value)) {
310
-			$finalValue = trim($value);
311
-		} else {
312
-			$finalValue = [];
313
-			foreach($value as $key => $val) {
314
-				if(is_string($val)) {
315
-					$val = trim($val);
316
-					if ($val !== '') {
317
-						//accidental line breaks are not wanted and can cause
318
-						// odd behaviour. Thus, away with them.
319
-						$finalValue[] = $val;
320
-					}
321
-				} else {
322
-					$finalValue[] = $val;
323
-				}
324
-			}
325
-		}
309
+        if(!is_array($value)) {
310
+            $finalValue = trim($value);
311
+        } else {
312
+            $finalValue = [];
313
+            foreach($value as $key => $val) {
314
+                if(is_string($val)) {
315
+                    $val = trim($val);
316
+                    if ($val !== '') {
317
+                        //accidental line breaks are not wanted and can cause
318
+                        // odd behaviour. Thus, away with them.
319
+                        $finalValue[] = $val;
320
+                    }
321
+                } else {
322
+                    $finalValue[] = $val;
323
+                }
324
+            }
325
+        }
326 326
 
327
-		$this->setRawValue($varName, $finalValue);
328
-	}
327
+        $this->setRawValue($varName, $finalValue);
328
+    }
329 329
 
330
-	/**
331
-	 * @param string $varName
332
-	 * @return string
333
-	 */
334
-	protected function getPwd($varName) {
335
-		return base64_decode($this->getValue($varName));
336
-	}
330
+    /**
331
+     * @param string $varName
332
+     * @return string
333
+     */
334
+    protected function getPwd($varName) {
335
+        return base64_decode($this->getValue($varName));
336
+    }
337 337
 
338
-	/**
339
-	 * @param string $varName
340
-	 * @return string
341
-	 */
342
-	protected function getLcValue($varName) {
343
-		return mb_strtolower($this->getValue($varName), 'UTF-8');
344
-	}
338
+    /**
339
+     * @param string $varName
340
+     * @return string
341
+     */
342
+    protected function getLcValue($varName) {
343
+        return mb_strtolower($this->getValue($varName), 'UTF-8');
344
+    }
345 345
 
346
-	/**
347
-	 * @param string $varName
348
-	 * @return string
349
-	 */
350
-	protected function getSystemValue($varName) {
351
-		//FIXME: if another system value is added, softcode the default value
352
-		return \OC::$server->getConfig()->getSystemValue($varName, false);
353
-	}
346
+    /**
347
+     * @param string $varName
348
+     * @return string
349
+     */
350
+    protected function getSystemValue($varName) {
351
+        //FIXME: if another system value is added, softcode the default value
352
+        return \OC::$server->getConfig()->getSystemValue($varName, false);
353
+    }
354 354
 
355
-	/**
356
-	 * @param string $varName
357
-	 * @return string
358
-	 */
359
-	protected function getValue($varName) {
360
-		static $defaults;
361
-		if(is_null($defaults)) {
362
-			$defaults = $this->getDefaults();
363
-		}
364
-		return \OCP\Config::getAppValue('user_ldap',
365
-										$this->configPrefix.$varName,
366
-										$defaults[$varName]);
367
-	}
355
+    /**
356
+     * @param string $varName
357
+     * @return string
358
+     */
359
+    protected function getValue($varName) {
360
+        static $defaults;
361
+        if(is_null($defaults)) {
362
+            $defaults = $this->getDefaults();
363
+        }
364
+        return \OCP\Config::getAppValue('user_ldap',
365
+                                        $this->configPrefix.$varName,
366
+                                        $defaults[$varName]);
367
+    }
368 368
 
369
-	/**
370
-	 * Sets a scalar value.
371
-	 * 
372
-	 * @param string $varName name of config key
373
-	 * @param mixed $value to set
374
-	 */
375
-	protected function setValue($varName, $value) {
376
-		if(is_string($value)) {
377
-			$value = trim($value);
378
-		}
379
-		$this->config[$varName] = $value;
380
-	}
369
+    /**
370
+     * Sets a scalar value.
371
+     * 
372
+     * @param string $varName name of config key
373
+     * @param mixed $value to set
374
+     */
375
+    protected function setValue($varName, $value) {
376
+        if(is_string($value)) {
377
+            $value = trim($value);
378
+        }
379
+        $this->config[$varName] = $value;
380
+    }
381 381
 
382
-	/**
383
-	 * Sets a scalar value without trimming.
384
-	 *
385
-	 * @param string $varName name of config key
386
-	 * @param mixed $value to set
387
-	 */
388
-	protected function setRawValue($varName, $value) {
389
-		$this->config[$varName] = $value;
390
-	}
382
+    /**
383
+     * Sets a scalar value without trimming.
384
+     *
385
+     * @param string $varName name of config key
386
+     * @param mixed $value to set
387
+     */
388
+    protected function setRawValue($varName, $value) {
389
+        $this->config[$varName] = $value;
390
+    }
391 391
 
392
-	/**
393
-	 * @param string $varName
394
-	 * @param string $value
395
-	 * @return bool
396
-	 */
397
-	protected function saveValue($varName, $value) {
398
-		\OC::$server->getConfig()->setAppValue(
399
-			'user_ldap',
400
-			$this->configPrefix.$varName,
401
-			$value
402
-		);
403
-		return true;
404
-	}
392
+    /**
393
+     * @param string $varName
394
+     * @param string $value
395
+     * @return bool
396
+     */
397
+    protected function saveValue($varName, $value) {
398
+        \OC::$server->getConfig()->setAppValue(
399
+            'user_ldap',
400
+            $this->configPrefix.$varName,
401
+            $value
402
+        );
403
+        return true;
404
+    }
405 405
 
406
-	/**
407
-	 * @return array an associative array with the default values. Keys are correspond
408
-	 * to config-value entries in the database table
409
-	 */
410
-	public function getDefaults() {
411
-		return array(
412
-			'ldap_host'                         => '',
413
-			'ldap_port'                         => '',
414
-			'ldap_backup_host'                  => '',
415
-			'ldap_backup_port'                  => '',
416
-			'ldap_override_main_server'         => '',
417
-			'ldap_dn'                           => '',
418
-			'ldap_agent_password'               => '',
419
-			'ldap_base'                         => '',
420
-			'ldap_base_users'                   => '',
421
-			'ldap_base_groups'                  => '',
422
-			'ldap_userlist_filter'              => '',
423
-			'ldap_user_filter_mode'             => 0,
424
-			'ldap_userfilter_objectclass'       => '',
425
-			'ldap_userfilter_groups'            => '',
426
-			'ldap_login_filter'                 => '',
427
-			'ldap_login_filter_mode'            => 0,
428
-			'ldap_loginfilter_email'            => 0,
429
-			'ldap_loginfilter_username'         => 1,
430
-			'ldap_loginfilter_attributes'       => '',
431
-			'ldap_group_filter'                 => '',
432
-			'ldap_group_filter_mode'            => 0,
433
-			'ldap_groupfilter_objectclass'      => '',
434
-			'ldap_groupfilter_groups'           => '',
435
-			'ldap_gid_number'                   => 'gidNumber',
436
-			'ldap_display_name'                 => 'displayName',
437
-			'ldap_user_display_name_2'			=> '',
438
-			'ldap_group_display_name'           => 'cn',
439
-			'ldap_tls'                          => 0,
440
-			'ldap_quota_def'                    => '',
441
-			'ldap_quota_attr'                   => '',
442
-			'ldap_email_attr'                   => '',
443
-			'ldap_group_member_assoc_attribute' => 'uniqueMember',
444
-			'ldap_cache_ttl'                    => 600,
445
-			'ldap_uuid_user_attribute'          => 'auto',
446
-			'ldap_uuid_group_attribute'         => 'auto',
447
-			'home_folder_naming_rule'           => '',
448
-			'ldap_turn_off_cert_check'          => 0,
449
-			'ldap_configuration_active'         => 0,
450
-			'ldap_attributes_for_user_search'   => '',
451
-			'ldap_attributes_for_group_search'  => '',
452
-			'ldap_expert_username_attr'         => '',
453
-			'ldap_expert_uuid_user_attr'        => '',
454
-			'ldap_expert_uuid_group_attr'       => '',
455
-			'has_memberof_filter_support'       => 0,
456
-			'use_memberof_to_detect_membership' => 1,
457
-			'last_jpegPhoto_lookup'             => 0,
458
-			'ldap_nested_groups'                => 0,
459
-			'ldap_paging_size'                  => 500,
460
-			'ldap_turn_on_pwd_change'           => 0,
461
-			'ldap_experienced_admin'            => 0,
462
-			'ldap_dynamic_group_member_url'     => '',
463
-			'ldap_default_ppolicy_dn'           => '',
464
-		);
465
-	}
406
+    /**
407
+     * @return array an associative array with the default values. Keys are correspond
408
+     * to config-value entries in the database table
409
+     */
410
+    public function getDefaults() {
411
+        return array(
412
+            'ldap_host'                         => '',
413
+            'ldap_port'                         => '',
414
+            'ldap_backup_host'                  => '',
415
+            'ldap_backup_port'                  => '',
416
+            'ldap_override_main_server'         => '',
417
+            'ldap_dn'                           => '',
418
+            'ldap_agent_password'               => '',
419
+            'ldap_base'                         => '',
420
+            'ldap_base_users'                   => '',
421
+            'ldap_base_groups'                  => '',
422
+            'ldap_userlist_filter'              => '',
423
+            'ldap_user_filter_mode'             => 0,
424
+            'ldap_userfilter_objectclass'       => '',
425
+            'ldap_userfilter_groups'            => '',
426
+            'ldap_login_filter'                 => '',
427
+            'ldap_login_filter_mode'            => 0,
428
+            'ldap_loginfilter_email'            => 0,
429
+            'ldap_loginfilter_username'         => 1,
430
+            'ldap_loginfilter_attributes'       => '',
431
+            'ldap_group_filter'                 => '',
432
+            'ldap_group_filter_mode'            => 0,
433
+            'ldap_groupfilter_objectclass'      => '',
434
+            'ldap_groupfilter_groups'           => '',
435
+            'ldap_gid_number'                   => 'gidNumber',
436
+            'ldap_display_name'                 => 'displayName',
437
+            'ldap_user_display_name_2'			=> '',
438
+            'ldap_group_display_name'           => 'cn',
439
+            'ldap_tls'                          => 0,
440
+            'ldap_quota_def'                    => '',
441
+            'ldap_quota_attr'                   => '',
442
+            'ldap_email_attr'                   => '',
443
+            'ldap_group_member_assoc_attribute' => 'uniqueMember',
444
+            'ldap_cache_ttl'                    => 600,
445
+            'ldap_uuid_user_attribute'          => 'auto',
446
+            'ldap_uuid_group_attribute'         => 'auto',
447
+            'home_folder_naming_rule'           => '',
448
+            'ldap_turn_off_cert_check'          => 0,
449
+            'ldap_configuration_active'         => 0,
450
+            'ldap_attributes_for_user_search'   => '',
451
+            'ldap_attributes_for_group_search'  => '',
452
+            'ldap_expert_username_attr'         => '',
453
+            'ldap_expert_uuid_user_attr'        => '',
454
+            'ldap_expert_uuid_group_attr'       => '',
455
+            'has_memberof_filter_support'       => 0,
456
+            'use_memberof_to_detect_membership' => 1,
457
+            'last_jpegPhoto_lookup'             => 0,
458
+            'ldap_nested_groups'                => 0,
459
+            'ldap_paging_size'                  => 500,
460
+            'ldap_turn_on_pwd_change'           => 0,
461
+            'ldap_experienced_admin'            => 0,
462
+            'ldap_dynamic_group_member_url'     => '',
463
+            'ldap_default_ppolicy_dn'           => '',
464
+        );
465
+    }
466 466
 
467
-	/**
468
-	 * @return array that maps internal variable names to database fields
469
-	 */
470
-	public function getConfigTranslationArray() {
471
-		//TODO: merge them into one representation
472
-		static $array = array(
473
-			'ldap_host'                         => 'ldapHost',
474
-			'ldap_port'                         => 'ldapPort',
475
-			'ldap_backup_host'                  => 'ldapBackupHost',
476
-			'ldap_backup_port'                  => 'ldapBackupPort',
477
-			'ldap_override_main_server'         => 'ldapOverrideMainServer',
478
-			'ldap_dn'                           => 'ldapAgentName',
479
-			'ldap_agent_password'               => 'ldapAgentPassword',
480
-			'ldap_base'                         => 'ldapBase',
481
-			'ldap_base_users'                   => 'ldapBaseUsers',
482
-			'ldap_base_groups'                  => 'ldapBaseGroups',
483
-			'ldap_userfilter_objectclass'       => 'ldapUserFilterObjectclass',
484
-			'ldap_userfilter_groups'            => 'ldapUserFilterGroups',
485
-			'ldap_userlist_filter'              => 'ldapUserFilter',
486
-			'ldap_user_filter_mode'             => 'ldapUserFilterMode',
487
-			'ldap_login_filter'                 => 'ldapLoginFilter',
488
-			'ldap_login_filter_mode'            => 'ldapLoginFilterMode',
489
-			'ldap_loginfilter_email'            => 'ldapLoginFilterEmail',
490
-			'ldap_loginfilter_username'         => 'ldapLoginFilterUsername',
491
-			'ldap_loginfilter_attributes'       => 'ldapLoginFilterAttributes',
492
-			'ldap_group_filter'                 => 'ldapGroupFilter',
493
-			'ldap_group_filter_mode'            => 'ldapGroupFilterMode',
494
-			'ldap_groupfilter_objectclass'      => 'ldapGroupFilterObjectclass',
495
-			'ldap_groupfilter_groups'           => 'ldapGroupFilterGroups',
496
-			'ldap_gid_number'                   => 'ldapGidNumber',
497
-			'ldap_display_name'                 => 'ldapUserDisplayName',
498
-			'ldap_user_display_name_2'			=> 'ldapUserDisplayName2',
499
-			'ldap_group_display_name'           => 'ldapGroupDisplayName',
500
-			'ldap_tls'                          => 'ldapTLS',
501
-			'ldap_quota_def'                    => 'ldapQuotaDefault',
502
-			'ldap_quota_attr'                   => 'ldapQuotaAttribute',
503
-			'ldap_email_attr'                   => 'ldapEmailAttribute',
504
-			'ldap_group_member_assoc_attribute' => 'ldapGroupMemberAssocAttr',
505
-			'ldap_cache_ttl'                    => 'ldapCacheTTL',
506
-			'home_folder_naming_rule'           => 'homeFolderNamingRule',
507
-			'ldap_turn_off_cert_check'          => 'turnOffCertCheck',
508
-			'ldap_configuration_active'         => 'ldapConfigurationActive',
509
-			'ldap_attributes_for_user_search'   => 'ldapAttributesForUserSearch',
510
-			'ldap_attributes_for_group_search'  => 'ldapAttributesForGroupSearch',
511
-			'ldap_expert_username_attr'         => 'ldapExpertUsernameAttr',
512
-			'ldap_expert_uuid_user_attr'        => 'ldapExpertUUIDUserAttr',
513
-			'ldap_expert_uuid_group_attr'       => 'ldapExpertUUIDGroupAttr',
514
-			'has_memberof_filter_support'       => 'hasMemberOfFilterSupport',
515
-			'use_memberof_to_detect_membership' => 'useMemberOfToDetectMembership',
516
-			'last_jpegPhoto_lookup'             => 'lastJpegPhotoLookup',
517
-			'ldap_nested_groups'                => 'ldapNestedGroups',
518
-			'ldap_paging_size'                  => 'ldapPagingSize',
519
-			'ldap_turn_on_pwd_change'           => 'turnOnPasswordChange',
520
-			'ldap_experienced_admin'            => 'ldapExperiencedAdmin',
521
-			'ldap_dynamic_group_member_url'     => 'ldapDynamicGroupMemberURL',
522
-			'ldap_default_ppolicy_dn'           => 'ldapDefaultPPolicyDN',
523
-		);
524
-		return $array;
525
-	}
467
+    /**
468
+     * @return array that maps internal variable names to database fields
469
+     */
470
+    public function getConfigTranslationArray() {
471
+        //TODO: merge them into one representation
472
+        static $array = array(
473
+            'ldap_host'                         => 'ldapHost',
474
+            'ldap_port'                         => 'ldapPort',
475
+            'ldap_backup_host'                  => 'ldapBackupHost',
476
+            'ldap_backup_port'                  => 'ldapBackupPort',
477
+            'ldap_override_main_server'         => 'ldapOverrideMainServer',
478
+            'ldap_dn'                           => 'ldapAgentName',
479
+            'ldap_agent_password'               => 'ldapAgentPassword',
480
+            'ldap_base'                         => 'ldapBase',
481
+            'ldap_base_users'                   => 'ldapBaseUsers',
482
+            'ldap_base_groups'                  => 'ldapBaseGroups',
483
+            'ldap_userfilter_objectclass'       => 'ldapUserFilterObjectclass',
484
+            'ldap_userfilter_groups'            => 'ldapUserFilterGroups',
485
+            'ldap_userlist_filter'              => 'ldapUserFilter',
486
+            'ldap_user_filter_mode'             => 'ldapUserFilterMode',
487
+            'ldap_login_filter'                 => 'ldapLoginFilter',
488
+            'ldap_login_filter_mode'            => 'ldapLoginFilterMode',
489
+            'ldap_loginfilter_email'            => 'ldapLoginFilterEmail',
490
+            'ldap_loginfilter_username'         => 'ldapLoginFilterUsername',
491
+            'ldap_loginfilter_attributes'       => 'ldapLoginFilterAttributes',
492
+            'ldap_group_filter'                 => 'ldapGroupFilter',
493
+            'ldap_group_filter_mode'            => 'ldapGroupFilterMode',
494
+            'ldap_groupfilter_objectclass'      => 'ldapGroupFilterObjectclass',
495
+            'ldap_groupfilter_groups'           => 'ldapGroupFilterGroups',
496
+            'ldap_gid_number'                   => 'ldapGidNumber',
497
+            'ldap_display_name'                 => 'ldapUserDisplayName',
498
+            'ldap_user_display_name_2'			=> 'ldapUserDisplayName2',
499
+            'ldap_group_display_name'           => 'ldapGroupDisplayName',
500
+            'ldap_tls'                          => 'ldapTLS',
501
+            'ldap_quota_def'                    => 'ldapQuotaDefault',
502
+            'ldap_quota_attr'                   => 'ldapQuotaAttribute',
503
+            'ldap_email_attr'                   => 'ldapEmailAttribute',
504
+            'ldap_group_member_assoc_attribute' => 'ldapGroupMemberAssocAttr',
505
+            'ldap_cache_ttl'                    => 'ldapCacheTTL',
506
+            'home_folder_naming_rule'           => 'homeFolderNamingRule',
507
+            'ldap_turn_off_cert_check'          => 'turnOffCertCheck',
508
+            'ldap_configuration_active'         => 'ldapConfigurationActive',
509
+            'ldap_attributes_for_user_search'   => 'ldapAttributesForUserSearch',
510
+            'ldap_attributes_for_group_search'  => 'ldapAttributesForGroupSearch',
511
+            'ldap_expert_username_attr'         => 'ldapExpertUsernameAttr',
512
+            'ldap_expert_uuid_user_attr'        => 'ldapExpertUUIDUserAttr',
513
+            'ldap_expert_uuid_group_attr'       => 'ldapExpertUUIDGroupAttr',
514
+            'has_memberof_filter_support'       => 'hasMemberOfFilterSupport',
515
+            'use_memberof_to_detect_membership' => 'useMemberOfToDetectMembership',
516
+            'last_jpegPhoto_lookup'             => 'lastJpegPhotoLookup',
517
+            'ldap_nested_groups'                => 'ldapNestedGroups',
518
+            'ldap_paging_size'                  => 'ldapPagingSize',
519
+            'ldap_turn_on_pwd_change'           => 'turnOnPasswordChange',
520
+            'ldap_experienced_admin'            => 'ldapExperiencedAdmin',
521
+            'ldap_dynamic_group_member_url'     => 'ldapDynamicGroupMemberURL',
522
+            'ldap_default_ppolicy_dn'           => 'ldapDefaultPPolicyDN',
523
+        );
524
+        return $array;
525
+    }
526 526
 
527 527
 }
Please login to merge, or discard this patch.
apps/user_ldap/appinfo/install.php 2 patches
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@
 block discarded – undo
24 24
 $config = \OC::$server->getConfig();
25 25
 $state = $config->getSystemValue('ldapIgnoreNamingRules', 'doSet');
26 26
 if($state === 'doSet') {
27
-	OCP\Config::setSystemValue('ldapIgnoreNamingRules', false);
27
+    OCP\Config::setSystemValue('ldapIgnoreNamingRules', false);
28 28
 }
29 29
 
30 30
 $helper = new \OCA\User_LDAP\Helper($config);
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -23,7 +23,7 @@
 block discarded – undo
23 23
  */
24 24
 $config = \OC::$server->getConfig();
25 25
 $state = $config->getSystemValue('ldapIgnoreNamingRules', 'doSet');
26
-if($state === 'doSet') {
26
+if ($state === 'doSet') {
27 27
 	OCP\Config::setSystemValue('ldapIgnoreNamingRules', false);
28 28
 }
29 29
 
Please login to merge, or discard this patch.
lib/private/legacy/util.php 2 patches
Indentation   +1428 added lines, -1428 removed lines patch added patch discarded remove patch
@@ -61,1436 +61,1436 @@
 block discarded – undo
61 61
 use OCP\IUser;
62 62
 
63 63
 class OC_Util {
64
-	public static $scripts = array();
65
-	public static $styles = array();
66
-	public static $headers = array();
67
-	private static $rootMounted = false;
68
-	private static $fsSetup = false;
69
-
70
-	/** @var array Local cache of version.php */
71
-	private static $versionCache = null;
72
-
73
-	protected static function getAppManager() {
74
-		return \OC::$server->getAppManager();
75
-	}
76
-
77
-	private static function initLocalStorageRootFS() {
78
-		// mount local file backend as root
79
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
80
-		//first set up the local "root" storage
81
-		\OC\Files\Filesystem::initMountManager();
82
-		if (!self::$rootMounted) {
83
-			\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
84
-			self::$rootMounted = true;
85
-		}
86
-	}
87
-
88
-	/**
89
-	 * mounting an object storage as the root fs will in essence remove the
90
-	 * necessity of a data folder being present.
91
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
92
-	 *
93
-	 * @param array $config containing 'class' and optional 'arguments'
94
-	 */
95
-	private static function initObjectStoreRootFS($config) {
96
-		// check misconfiguration
97
-		if (empty($config['class'])) {
98
-			\OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
99
-		}
100
-		if (!isset($config['arguments'])) {
101
-			$config['arguments'] = array();
102
-		}
103
-
104
-		// instantiate object store implementation
105
-		$name = $config['class'];
106
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
107
-			$segments = explode('\\', $name);
108
-			OC_App::loadApp(strtolower($segments[1]));
109
-		}
110
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
111
-		// mount with plain / root object store implementation
112
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
113
-
114
-		// mount object storage as root
115
-		\OC\Files\Filesystem::initMountManager();
116
-		if (!self::$rootMounted) {
117
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
118
-			self::$rootMounted = true;
119
-		}
120
-	}
121
-
122
-	/**
123
-	 * mounting an object storage as the root fs will in essence remove the
124
-	 * necessity of a data folder being present.
125
-	 *
126
-	 * @param array $config containing 'class' and optional 'arguments'
127
-	 */
128
-	private static function initObjectStoreMultibucketRootFS($config) {
129
-		// check misconfiguration
130
-		if (empty($config['class'])) {
131
-			\OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
132
-		}
133
-		if (!isset($config['arguments'])) {
134
-			$config['arguments'] = array();
135
-		}
136
-
137
-		// instantiate object store implementation
138
-		$name = $config['class'];
139
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
140
-			$segments = explode('\\', $name);
141
-			OC_App::loadApp(strtolower($segments[1]));
142
-		}
143
-
144
-		if (!isset($config['arguments']['bucket'])) {
145
-			$config['arguments']['bucket'] = '';
146
-		}
147
-		// put the root FS always in first bucket for multibucket configuration
148
-		$config['arguments']['bucket'] .= '0';
149
-
150
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
151
-		// mount with plain / root object store implementation
152
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
153
-
154
-		// mount object storage as root
155
-		\OC\Files\Filesystem::initMountManager();
156
-		if (!self::$rootMounted) {
157
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
158
-			self::$rootMounted = true;
159
-		}
160
-	}
161
-
162
-	/**
163
-	 * Can be set up
164
-	 *
165
-	 * @param string $user
166
-	 * @return boolean
167
-	 * @description configure the initial filesystem based on the configuration
168
-	 */
169
-	public static function setupFS($user = '') {
170
-		//setting up the filesystem twice can only lead to trouble
171
-		if (self::$fsSetup) {
172
-			return false;
173
-		}
174
-
175
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
176
-
177
-		// If we are not forced to load a specific user we load the one that is logged in
178
-		if ($user === null) {
179
-			$user = '';
180
-		} else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
181
-			$user = OC_User::getUser();
182
-		}
183
-
184
-		// load all filesystem apps before, so no setup-hook gets lost
185
-		OC_App::loadApps(array('filesystem'));
186
-
187
-		// the filesystem will finish when $user is not empty,
188
-		// mark fs setup here to avoid doing the setup from loading
189
-		// OC_Filesystem
190
-		if ($user != '') {
191
-			self::$fsSetup = true;
192
-		}
193
-
194
-		\OC\Files\Filesystem::initMountManager();
195
-
196
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
197
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
198
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
199
-				/** @var \OC\Files\Storage\Common $storage */
200
-				$storage->setMountOptions($mount->getOptions());
201
-			}
202
-			return $storage;
203
-		});
204
-
205
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
206
-			if (!$mount->getOption('enable_sharing', true)) {
207
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
208
-					'storage' => $storage,
209
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
210
-				]);
211
-			}
212
-			return $storage;
213
-		});
214
-
215
-		// install storage availability wrapper, before most other wrappers
216
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, $storage) {
217
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
218
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
219
-			}
220
-			return $storage;
221
-		});
222
-
223
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
224
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
225
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
226
-			}
227
-			return $storage;
228
-		});
229
-
230
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
231
-			// set up quota for home storages, even for other users
232
-			// which can happen when using sharing
233
-
234
-			/**
235
-			 * @var \OC\Files\Storage\Storage $storage
236
-			 */
237
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
238
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
239
-			) {
240
-				/** @var \OC\Files\Storage\Home $storage */
241
-				if (is_object($storage->getUser())) {
242
-					$user = $storage->getUser()->getUID();
243
-					$quota = OC_Util::getUserQuota($user);
244
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
245
-						return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
246
-					}
247
-				}
248
-			}
249
-
250
-			return $storage;
251
-		});
252
-
253
-		OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
254
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
255
-
256
-		//check if we are using an object storage
257
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
258
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
259
-
260
-		// use the same order as in ObjectHomeMountProvider
261
-		if (isset($objectStoreMultibucket)) {
262
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
263
-		} elseif (isset($objectStore)) {
264
-			self::initObjectStoreRootFS($objectStore);
265
-		} else {
266
-			self::initLocalStorageRootFS();
267
-		}
268
-
269
-		if ($user != '' && !OCP\User::userExists($user)) {
270
-			\OC::$server->getEventLogger()->end('setup_fs');
271
-			return false;
272
-		}
273
-
274
-		//if we aren't logged in, there is no use to set up the filesystem
275
-		if ($user != "") {
276
-
277
-			$userDir = '/' . $user . '/files';
278
-
279
-			//jail the user into his "home" directory
280
-			\OC\Files\Filesystem::init($user, $userDir);
281
-
282
-			OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
283
-		}
284
-		\OC::$server->getEventLogger()->end('setup_fs');
285
-		return true;
286
-	}
287
-
288
-	/**
289
-	 * check if a password is required for each public link
290
-	 *
291
-	 * @return boolean
292
-	 */
293
-	public static function isPublicLinkPasswordRequired() {
294
-		$appConfig = \OC::$server->getAppConfig();
295
-		$enforcePassword = $appConfig->getValue('core', 'shareapi_enforce_links_password', 'no');
296
-		return ($enforcePassword === 'yes') ? true : false;
297
-	}
298
-
299
-	/**
300
-	 * check if sharing is disabled for the current user
301
-	 * @param IConfig $config
302
-	 * @param IGroupManager $groupManager
303
-	 * @param IUser|null $user
304
-	 * @return bool
305
-	 */
306
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
307
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
308
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
309
-			$excludedGroups = json_decode($groupsList);
310
-			if (is_null($excludedGroups)) {
311
-				$excludedGroups = explode(',', $groupsList);
312
-				$newValue = json_encode($excludedGroups);
313
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
314
-			}
315
-			$usersGroups = $groupManager->getUserGroupIds($user);
316
-			if (!empty($usersGroups)) {
317
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
318
-				// if the user is only in groups which are disabled for sharing then
319
-				// sharing is also disabled for the user
320
-				if (empty($remainingGroups)) {
321
-					return true;
322
-				}
323
-			}
324
-		}
325
-		return false;
326
-	}
327
-
328
-	/**
329
-	 * check if share API enforces a default expire date
330
-	 *
331
-	 * @return boolean
332
-	 */
333
-	public static function isDefaultExpireDateEnforced() {
334
-		$isDefaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
335
-		$enforceDefaultExpireDate = false;
336
-		if ($isDefaultExpireDateEnabled === 'yes') {
337
-			$value = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
338
-			$enforceDefaultExpireDate = ($value === 'yes') ? true : false;
339
-		}
340
-
341
-		return $enforceDefaultExpireDate;
342
-	}
343
-
344
-	/**
345
-	 * Get the quota of a user
346
-	 *
347
-	 * @param string $userId
348
-	 * @return int Quota bytes
349
-	 */
350
-	public static function getUserQuota($userId) {
351
-		$user = \OC::$server->getUserManager()->get($userId);
352
-		if (is_null($user)) {
353
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
354
-		}
355
-		$userQuota = $user->getQuota();
356
-		if($userQuota === 'none') {
357
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
358
-		}
359
-		return OC_Helper::computerFileSize($userQuota);
360
-	}
361
-
362
-	/**
363
-	 * copies the skeleton to the users /files
364
-	 *
365
-	 * @param String $userId
366
-	 * @param \OCP\Files\Folder $userDirectory
367
-	 * @throws \RuntimeException
368
-	 */
369
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
370
-
371
-		$skeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
372
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
373
-
374
-		if ($instanceId === null) {
375
-			throw new \RuntimeException('no instance id!');
376
-		}
377
-		$appdata = 'appdata_' . $instanceId;
378
-		if ($userId === $appdata) {
379
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
380
-		}
381
-
382
-		if (!empty($skeletonDirectory)) {
383
-			\OCP\Util::writeLog(
384
-				'files_skeleton',
385
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
386
-				\OCP\Util::DEBUG
387
-			);
388
-			self::copyr($skeletonDirectory, $userDirectory);
389
-			// update the file cache
390
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
391
-		}
392
-	}
393
-
394
-	/**
395
-	 * copies a directory recursively by using streams
396
-	 *
397
-	 * @param string $source
398
-	 * @param \OCP\Files\Folder $target
399
-	 * @return void
400
-	 */
401
-	public static function copyr($source, \OCP\Files\Folder $target) {
402
-		$logger = \OC::$server->getLogger();
403
-
404
-		// Verify if folder exists
405
-		$dir = opendir($source);
406
-		if($dir === false) {
407
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
408
-			return;
409
-		}
410
-
411
-		// Copy the files
412
-		while (false !== ($file = readdir($dir))) {
413
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
414
-				if (is_dir($source . '/' . $file)) {
415
-					$child = $target->newFolder($file);
416
-					self::copyr($source . '/' . $file, $child);
417
-				} else {
418
-					$child = $target->newFile($file);
419
-					$sourceStream = fopen($source . '/' . $file, 'r');
420
-					if($sourceStream === false) {
421
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
422
-						closedir($dir);
423
-						return;
424
-					}
425
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
426
-				}
427
-			}
428
-		}
429
-		closedir($dir);
430
-	}
431
-
432
-	/**
433
-	 * @return void
434
-	 */
435
-	public static function tearDownFS() {
436
-		\OC\Files\Filesystem::tearDown();
437
-		\OC::$server->getRootFolder()->clearCache();
438
-		self::$fsSetup = false;
439
-		self::$rootMounted = false;
440
-	}
441
-
442
-	/**
443
-	 * get the current installed version of ownCloud
444
-	 *
445
-	 * @return array
446
-	 */
447
-	public static function getVersion() {
448
-		OC_Util::loadVersion();
449
-		return self::$versionCache['OC_Version'];
450
-	}
451
-
452
-	/**
453
-	 * get the current installed version string of ownCloud
454
-	 *
455
-	 * @return string
456
-	 */
457
-	public static function getVersionString() {
458
-		OC_Util::loadVersion();
459
-		return self::$versionCache['OC_VersionString'];
460
-	}
461
-
462
-	/**
463
-	 * @deprecated the value is of no use anymore
464
-	 * @return string
465
-	 */
466
-	public static function getEditionString() {
467
-		return '';
468
-	}
469
-
470
-	/**
471
-	 * @description get the update channel of the current installed of ownCloud.
472
-	 * @return string
473
-	 */
474
-	public static function getChannel() {
475
-		OC_Util::loadVersion();
476
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
477
-	}
478
-
479
-	/**
480
-	 * @description get the build number of the current installed of ownCloud.
481
-	 * @return string
482
-	 */
483
-	public static function getBuild() {
484
-		OC_Util::loadVersion();
485
-		return self::$versionCache['OC_Build'];
486
-	}
487
-
488
-	/**
489
-	 * @description load the version.php into the session as cache
490
-	 */
491
-	private static function loadVersion() {
492
-		if (self::$versionCache !== null) {
493
-			return;
494
-		}
495
-
496
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
497
-		require OC::$SERVERROOT . '/version.php';
498
-		/** @var $timestamp int */
499
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
500
-		/** @var $OC_Version string */
501
-		self::$versionCache['OC_Version'] = $OC_Version;
502
-		/** @var $OC_VersionString string */
503
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
504
-		/** @var $OC_Build string */
505
-		self::$versionCache['OC_Build'] = $OC_Build;
506
-
507
-		/** @var $OC_Channel string */
508
-		self::$versionCache['OC_Channel'] = $OC_Channel;
509
-	}
510
-
511
-	/**
512
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
513
-	 *
514
-	 * @param string $application application to get the files from
515
-	 * @param string $directory directory within this application (css, js, vendor, etc)
516
-	 * @param string $file the file inside of the above folder
517
-	 * @return string the path
518
-	 */
519
-	private static function generatePath($application, $directory, $file) {
520
-		if (is_null($file)) {
521
-			$file = $application;
522
-			$application = "";
523
-		}
524
-		if (!empty($application)) {
525
-			return "$application/$directory/$file";
526
-		} else {
527
-			return "$directory/$file";
528
-		}
529
-	}
530
-
531
-	/**
532
-	 * add a javascript file
533
-	 *
534
-	 * @param string $application application id
535
-	 * @param string|null $file filename
536
-	 * @param bool $prepend prepend the Script to the beginning of the list
537
-	 * @return void
538
-	 */
539
-	public static function addScript($application, $file = null, $prepend = false) {
540
-		$path = OC_Util::generatePath($application, 'js', $file);
541
-
542
-		// core js files need separate handling
543
-		if ($application !== 'core' && $file !== null) {
544
-			self::addTranslations ( $application );
545
-		}
546
-		self::addExternalResource($application, $prepend, $path, "script");
547
-	}
548
-
549
-	/**
550
-	 * add a javascript file from the vendor sub folder
551
-	 *
552
-	 * @param string $application application id
553
-	 * @param string|null $file filename
554
-	 * @param bool $prepend prepend the Script to the beginning of the list
555
-	 * @return void
556
-	 */
557
-	public static function addVendorScript($application, $file = null, $prepend = false) {
558
-		$path = OC_Util::generatePath($application, 'vendor', $file);
559
-		self::addExternalResource($application, $prepend, $path, "script");
560
-	}
561
-
562
-	/**
563
-	 * add a translation JS file
564
-	 *
565
-	 * @param string $application application id
566
-	 * @param string $languageCode language code, defaults to the current language
567
-	 * @param bool $prepend prepend the Script to the beginning of the list
568
-	 */
569
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
570
-		if (is_null($languageCode)) {
571
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
572
-		}
573
-		if (!empty($application)) {
574
-			$path = "$application/l10n/$languageCode";
575
-		} else {
576
-			$path = "l10n/$languageCode";
577
-		}
578
-		self::addExternalResource($application, $prepend, $path, "script");
579
-	}
580
-
581
-	/**
582
-	 * add a css file
583
-	 *
584
-	 * @param string $application application id
585
-	 * @param string|null $file filename
586
-	 * @param bool $prepend prepend the Style to the beginning of the list
587
-	 * @return void
588
-	 */
589
-	public static function addStyle($application, $file = null, $prepend = false) {
590
-		$path = OC_Util::generatePath($application, 'css', $file);
591
-		self::addExternalResource($application, $prepend, $path, "style");
592
-	}
593
-
594
-	/**
595
-	 * add a css file from the vendor sub folder
596
-	 *
597
-	 * @param string $application application id
598
-	 * @param string|null $file filename
599
-	 * @param bool $prepend prepend the Style to the beginning of the list
600
-	 * @return void
601
-	 */
602
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
603
-		$path = OC_Util::generatePath($application, 'vendor', $file);
604
-		self::addExternalResource($application, $prepend, $path, "style");
605
-	}
606
-
607
-	/**
608
-	 * add an external resource css/js file
609
-	 *
610
-	 * @param string $application application id
611
-	 * @param bool $prepend prepend the file to the beginning of the list
612
-	 * @param string $path
613
-	 * @param string $type (script or style)
614
-	 * @return void
615
-	 */
616
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
617
-
618
-		if ($type === "style") {
619
-			if (!in_array($path, self::$styles)) {
620
-				if ($prepend === true) {
621
-					array_unshift ( self::$styles, $path );
622
-				} else {
623
-					self::$styles[] = $path;
624
-				}
625
-			}
626
-		} elseif ($type === "script") {
627
-			if (!in_array($path, self::$scripts)) {
628
-				if ($prepend === true) {
629
-					array_unshift ( self::$scripts, $path );
630
-				} else {
631
-					self::$scripts [] = $path;
632
-				}
633
-			}
634
-		}
635
-	}
636
-
637
-	/**
638
-	 * Add a custom element to the header
639
-	 * If $text is null then the element will be written as empty element.
640
-	 * So use "" to get a closing tag.
641
-	 * @param string $tag tag name of the element
642
-	 * @param array $attributes array of attributes for the element
643
-	 * @param string $text the text content for the element
644
-	 */
645
-	public static function addHeader($tag, $attributes, $text=null) {
646
-		self::$headers[] = array(
647
-			'tag' => $tag,
648
-			'attributes' => $attributes,
649
-			'text' => $text
650
-		);
651
-	}
652
-
653
-	/**
654
-	 * formats a timestamp in the "right" way
655
-	 *
656
-	 * @param int $timestamp
657
-	 * @param bool $dateOnly option to omit time from the result
658
-	 * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
659
-	 * @return string timestamp
660
-	 *
661
-	 * @deprecated Use \OC::$server->query('DateTimeFormatter') instead
662
-	 */
663
-	public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
664
-		if ($timeZone !== null && !$timeZone instanceof \DateTimeZone) {
665
-			$timeZone = new \DateTimeZone($timeZone);
666
-		}
667
-
668
-		/** @var \OC\DateTimeFormatter $formatter */
669
-		$formatter = \OC::$server->query('DateTimeFormatter');
670
-		if ($dateOnly) {
671
-			return $formatter->formatDate($timestamp, 'long', $timeZone);
672
-		}
673
-		return $formatter->formatDateTime($timestamp, 'long', 'long', $timeZone);
674
-	}
675
-
676
-	/**
677
-	 * check if the current server configuration is suitable for ownCloud
678
-	 *
679
-	 * @param \OC\SystemConfig $config
680
-	 * @return array arrays with error messages and hints
681
-	 */
682
-	public static function checkServer(\OC\SystemConfig $config) {
683
-		$l = \OC::$server->getL10N('lib');
684
-		$errors = array();
685
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
686
-
687
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
688
-			// this check needs to be done every time
689
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
690
-		}
691
-
692
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
693
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
694
-			return $errors;
695
-		}
696
-
697
-		$webServerRestart = false;
698
-		$setup = new \OC\Setup($config, \OC::$server->getIniWrapper(), \OC::$server->getL10N('lib'),
699
-			\OC::$server->query(\OCP\Defaults::class), \OC::$server->getLogger(), \OC::$server->getSecureRandom());
700
-
701
-		$urlGenerator = \OC::$server->getURLGenerator();
702
-
703
-		$availableDatabases = $setup->getSupportedDatabases();
704
-		if (empty($availableDatabases)) {
705
-			$errors[] = array(
706
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
707
-				'hint' => '' //TODO: sane hint
708
-			);
709
-			$webServerRestart = true;
710
-		}
711
-
712
-		// Check if config folder is writable.
713
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
714
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
715
-				$errors[] = array(
716
-					'error' => $l->t('Cannot write into "config" directory'),
717
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
718
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
719
-				);
720
-			}
721
-		}
722
-
723
-		// Check if there is a writable install folder.
724
-		if ($config->getValue('appstoreenabled', true)) {
725
-			if (OC_App::getInstallPath() === null
726
-				|| !is_writable(OC_App::getInstallPath())
727
-				|| !is_readable(OC_App::getInstallPath())
728
-			) {
729
-				$errors[] = array(
730
-					'error' => $l->t('Cannot write into "apps" directory'),
731
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
732
-						. ' or disabling the appstore in the config file. See %s',
733
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
734
-				);
735
-			}
736
-		}
737
-		// Create root dir.
738
-		if ($config->getValue('installed', false)) {
739
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
740
-				$success = @mkdir($CONFIG_DATADIRECTORY);
741
-				if ($success) {
742
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
743
-				} else {
744
-					$errors[] = [
745
-						'error' => $l->t('Cannot create "data" directory'),
746
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
747
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
748
-					];
749
-				}
750
-			} else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
751
-				//common hint for all file permissions error messages
752
-				$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
753
-					[$urlGenerator->linkToDocs('admin-dir_permissions')]);
754
-				$errors[] = [
755
-					'error' => 'Your data directory is not writable',
756
-					'hint' => $permissionsHint
757
-				];
758
-			} else {
759
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
760
-			}
761
-		}
762
-
763
-		if (!OC_Util::isSetLocaleWorking()) {
764
-			$errors[] = array(
765
-				'error' => $l->t('Setting locale to %s failed',
766
-					array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
767
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
768
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
769
-			);
770
-		}
771
-
772
-		// Contains the dependencies that should be checked against
773
-		// classes = class_exists
774
-		// functions = function_exists
775
-		// defined = defined
776
-		// ini = ini_get
777
-		// If the dependency is not found the missing module name is shown to the EndUser
778
-		// When adding new checks always verify that they pass on Travis as well
779
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
780
-		$dependencies = array(
781
-			'classes' => array(
782
-				'ZipArchive' => 'zip',
783
-				'DOMDocument' => 'dom',
784
-				'XMLWriter' => 'XMLWriter',
785
-				'XMLReader' => 'XMLReader',
786
-			),
787
-			'functions' => [
788
-				'xml_parser_create' => 'libxml',
789
-				'mb_strcut' => 'mb multibyte',
790
-				'ctype_digit' => 'ctype',
791
-				'json_encode' => 'JSON',
792
-				'gd_info' => 'GD',
793
-				'gzencode' => 'zlib',
794
-				'iconv' => 'iconv',
795
-				'simplexml_load_string' => 'SimpleXML',
796
-				'hash' => 'HASH Message Digest Framework',
797
-				'curl_init' => 'cURL',
798
-				'openssl_verify' => 'OpenSSL',
799
-			],
800
-			'defined' => array(
801
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
802
-			),
803
-			'ini' => [
804
-				'default_charset' => 'UTF-8',
805
-			],
806
-		);
807
-		$missingDependencies = array();
808
-		$invalidIniSettings = [];
809
-		$moduleHint = $l->t('Please ask your server administrator to install the module.');
810
-
811
-		/**
812
-		 * FIXME: The dependency check does not work properly on HHVM on the moment
813
-		 *        and prevents installation. Once HHVM is more compatible with our
814
-		 *        approach to check for these values we should re-enable those
815
-		 *        checks.
816
-		 */
817
-		$iniWrapper = \OC::$server->getIniWrapper();
818
-		if (!self::runningOnHhvm()) {
819
-			foreach ($dependencies['classes'] as $class => $module) {
820
-				if (!class_exists($class)) {
821
-					$missingDependencies[] = $module;
822
-				}
823
-			}
824
-			foreach ($dependencies['functions'] as $function => $module) {
825
-				if (!function_exists($function)) {
826
-					$missingDependencies[] = $module;
827
-				}
828
-			}
829
-			foreach ($dependencies['defined'] as $defined => $module) {
830
-				if (!defined($defined)) {
831
-					$missingDependencies[] = $module;
832
-				}
833
-			}
834
-			foreach ($dependencies['ini'] as $setting => $expected) {
835
-				if (is_bool($expected)) {
836
-					if ($iniWrapper->getBool($setting) !== $expected) {
837
-						$invalidIniSettings[] = [$setting, $expected];
838
-					}
839
-				}
840
-				if (is_int($expected)) {
841
-					if ($iniWrapper->getNumeric($setting) !== $expected) {
842
-						$invalidIniSettings[] = [$setting, $expected];
843
-					}
844
-				}
845
-				if (is_string($expected)) {
846
-					if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
847
-						$invalidIniSettings[] = [$setting, $expected];
848
-					}
849
-				}
850
-			}
851
-		}
852
-
853
-		foreach($missingDependencies as $missingDependency) {
854
-			$errors[] = array(
855
-				'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
856
-				'hint' => $moduleHint
857
-			);
858
-			$webServerRestart = true;
859
-		}
860
-		foreach($invalidIniSettings as $setting) {
861
-			if(is_bool($setting[1])) {
862
-				$setting[1] = ($setting[1]) ? 'on' : 'off';
863
-			}
864
-			$errors[] = [
865
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
866
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
867
-			];
868
-			$webServerRestart = true;
869
-		}
870
-
871
-		/**
872
-		 * The mbstring.func_overload check can only be performed if the mbstring
873
-		 * module is installed as it will return null if the checking setting is
874
-		 * not available and thus a check on the boolean value fails.
875
-		 *
876
-		 * TODO: Should probably be implemented in the above generic dependency
877
-		 *       check somehow in the long-term.
878
-		 */
879
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
880
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
881
-			$errors[] = array(
882
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
883
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
884
-			);
885
-		}
886
-
887
-		if(function_exists('xml_parser_create') &&
888
-			LIBXML_LOADED_VERSION < 20700 ) {
889
-			$version = LIBXML_LOADED_VERSION;
890
-			$major = floor($version/10000);
891
-			$version -= ($major * 10000);
892
-			$minor = floor($version/100);
893
-			$version -= ($minor * 100);
894
-			$patch = $version;
895
-			$errors[] = array(
896
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
897
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
898
-			);
899
-		}
900
-
901
-		if (!self::isAnnotationsWorking()) {
902
-			$errors[] = array(
903
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
904
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
905
-			);
906
-		}
907
-
908
-		if (!\OC::$CLI && $webServerRestart) {
909
-			$errors[] = array(
910
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
911
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
912
-			);
913
-		}
914
-
915
-		$errors = array_merge($errors, self::checkDatabaseVersion());
916
-
917
-		// Cache the result of this function
918
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
919
-
920
-		return $errors;
921
-	}
922
-
923
-	/**
924
-	 * Check the database version
925
-	 *
926
-	 * @return array errors array
927
-	 */
928
-	public static function checkDatabaseVersion() {
929
-		$l = \OC::$server->getL10N('lib');
930
-		$errors = array();
931
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
932
-		if ($dbType === 'pgsql') {
933
-			// check PostgreSQL version
934
-			try {
935
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
936
-				$data = $result->fetchRow();
937
-				if (isset($data['server_version'])) {
938
-					$version = $data['server_version'];
939
-					if (version_compare($version, '9.0.0', '<')) {
940
-						$errors[] = array(
941
-							'error' => $l->t('PostgreSQL >= 9 required'),
942
-							'hint' => $l->t('Please upgrade your database version')
943
-						);
944
-					}
945
-				}
946
-			} catch (\Doctrine\DBAL\DBALException $e) {
947
-				$logger = \OC::$server->getLogger();
948
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
949
-				$logger->logException($e);
950
-			}
951
-		}
952
-		return $errors;
953
-	}
954
-
955
-	/**
956
-	 * Check for correct file permissions of data directory
957
-	 *
958
-	 * @param string $dataDirectory
959
-	 * @return array arrays with error messages and hints
960
-	 */
961
-	public static function checkDataDirectoryPermissions($dataDirectory) {
962
-		$l = \OC::$server->getL10N('lib');
963
-		$errors = array();
964
-		$permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
965
-			. ' cannot be listed by other users.');
966
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
967
-		if (substr($perms, -1) !== '0') {
968
-			chmod($dataDirectory, 0770);
969
-			clearstatcache();
970
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
971
-			if ($perms[2] !== '0') {
972
-				$errors[] = [
973
-					'error' => $l->t('Your data directory is readable by other users'),
974
-					'hint' => $permissionsModHint
975
-				];
976
-			}
977
-		}
978
-		return $errors;
979
-	}
980
-
981
-	/**
982
-	 * Check that the data directory exists and is valid by
983
-	 * checking the existence of the ".ocdata" file.
984
-	 *
985
-	 * @param string $dataDirectory data directory path
986
-	 * @return array errors found
987
-	 */
988
-	public static function checkDataDirectoryValidity($dataDirectory) {
989
-		$l = \OC::$server->getL10N('lib');
990
-		$errors = [];
991
-		if ($dataDirectory[0] !== '/') {
992
-			$errors[] = [
993
-				'error' => $l->t('Your data directory must be an absolute path'),
994
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
995
-			];
996
-		}
997
-		if (!file_exists($dataDirectory . '/.ocdata')) {
998
-			$errors[] = [
999
-				'error' => $l->t('Your data directory is invalid'),
1000
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1001
-					' in the root of the data directory.')
1002
-			];
1003
-		}
1004
-		return $errors;
1005
-	}
1006
-
1007
-	/**
1008
-	 * Check if the user is logged in, redirects to home if not. With
1009
-	 * redirect URL parameter to the request URI.
1010
-	 *
1011
-	 * @return void
1012
-	 */
1013
-	public static function checkLoggedIn() {
1014
-		// Check if we are a user
1015
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1016
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1017
-						'core.login.showLoginForm',
1018
-						[
1019
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1020
-						]
1021
-					)
1022
-			);
1023
-			exit();
1024
-		}
1025
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1026
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1027
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1028
-			exit();
1029
-		}
1030
-	}
1031
-
1032
-	/**
1033
-	 * Check if the user is a admin, redirects to home if not
1034
-	 *
1035
-	 * @return void
1036
-	 */
1037
-	public static function checkAdminUser() {
1038
-		OC_Util::checkLoggedIn();
1039
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1040
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1041
-			exit();
1042
-		}
1043
-	}
1044
-
1045
-	/**
1046
-	 * Check if the user is a subadmin, redirects to home if not
1047
-	 *
1048
-	 * @return null|boolean $groups where the current user is subadmin
1049
-	 */
1050
-	public static function checkSubAdminUser() {
1051
-		OC_Util::checkLoggedIn();
1052
-		$userObject = \OC::$server->getUserSession()->getUser();
1053
-		$isSubAdmin = false;
1054
-		if($userObject !== null) {
1055
-			$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1056
-		}
1057
-
1058
-		if (!$isSubAdmin) {
1059
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1060
-			exit();
1061
-		}
1062
-		return true;
1063
-	}
1064
-
1065
-	/**
1066
-	 * Returns the URL of the default page
1067
-	 * based on the system configuration and
1068
-	 * the apps visible for the current user
1069
-	 *
1070
-	 * @return string URL
1071
-	 */
1072
-	public static function getDefaultPageUrl() {
1073
-		$urlGenerator = \OC::$server->getURLGenerator();
1074
-		// Deny the redirect if the URL contains a @
1075
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1076
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1077
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1078
-		} else {
1079
-			$defaultPage = \OC::$server->getAppConfig()->getValue('core', 'defaultpage');
1080
-			if ($defaultPage) {
1081
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1082
-			} else {
1083
-				$appId = 'files';
1084
-				$config = \OC::$server->getConfig();
1085
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1086
-				// find the first app that is enabled for the current user
1087
-				foreach ($defaultApps as $defaultApp) {
1088
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1089
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1090
-						$appId = $defaultApp;
1091
-						break;
1092
-					}
1093
-				}
1094
-
1095
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1096
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1097
-				} else {
1098
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1099
-				}
1100
-			}
1101
-		}
1102
-		return $location;
1103
-	}
1104
-
1105
-	/**
1106
-	 * Redirect to the user default page
1107
-	 *
1108
-	 * @return void
1109
-	 */
1110
-	public static function redirectToDefaultPage() {
1111
-		$location = self::getDefaultPageUrl();
1112
-		header('Location: ' . $location);
1113
-		exit();
1114
-	}
1115
-
1116
-	/**
1117
-	 * get an id unique for this instance
1118
-	 *
1119
-	 * @return string
1120
-	 */
1121
-	public static function getInstanceId() {
1122
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1123
-		if (is_null($id)) {
1124
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1125
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1126
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1127
-		}
1128
-		return $id;
1129
-	}
1130
-
1131
-	/**
1132
-	 * Public function to sanitize HTML
1133
-	 *
1134
-	 * This function is used to sanitize HTML and should be applied on any
1135
-	 * string or array of strings before displaying it on a web page.
1136
-	 *
1137
-	 * @param string|array $value
1138
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1139
-	 */
1140
-	public static function sanitizeHTML($value) {
1141
-		if (is_array($value)) {
1142
-			$value = array_map(function($value) {
1143
-				return self::sanitizeHTML($value);
1144
-			}, $value);
1145
-		} else {
1146
-			// Specify encoding for PHP<5.4
1147
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1148
-		}
1149
-		return $value;
1150
-	}
1151
-
1152
-	/**
1153
-	 * Public function to encode url parameters
1154
-	 *
1155
-	 * This function is used to encode path to file before output.
1156
-	 * Encoding is done according to RFC 3986 with one exception:
1157
-	 * Character '/' is preserved as is.
1158
-	 *
1159
-	 * @param string $component part of URI to encode
1160
-	 * @return string
1161
-	 */
1162
-	public static function encodePath($component) {
1163
-		$encoded = rawurlencode($component);
1164
-		$encoded = str_replace('%2F', '/', $encoded);
1165
-		return $encoded;
1166
-	}
1167
-
1168
-
1169
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1170
-		// php dev server does not support htaccess
1171
-		if (php_sapi_name() === 'cli-server') {
1172
-			return false;
1173
-		}
1174
-
1175
-		// testdata
1176
-		$fileName = '/htaccesstest.txt';
1177
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1178
-
1179
-		// creating a test file
1180
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1181
-
1182
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1183
-			return false;
1184
-		}
1185
-
1186
-		$fp = @fopen($testFile, 'w');
1187
-		if (!$fp) {
1188
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1189
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1190
-		}
1191
-		fwrite($fp, $testContent);
1192
-		fclose($fp);
1193
-
1194
-		return $testContent;
1195
-	}
1196
-
1197
-	/**
1198
-	 * Check if the .htaccess file is working
1199
-	 * @param \OCP\IConfig $config
1200
-	 * @return bool
1201
-	 * @throws Exception
1202
-	 * @throws \OC\HintException If the test file can't get written.
1203
-	 */
1204
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1205
-
1206
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1207
-			return true;
1208
-		}
1209
-
1210
-		$testContent = $this->createHtaccessTestFile($config);
1211
-		if ($testContent === false) {
1212
-			return false;
1213
-		}
1214
-
1215
-		$fileName = '/htaccesstest.txt';
1216
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1217
-
1218
-		// accessing the file via http
1219
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1220
-		try {
1221
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1222
-		} catch (\Exception $e) {
1223
-			$content = false;
1224
-		}
1225
-
1226
-		// cleanup
1227
-		@unlink($testFile);
1228
-
1229
-		/*
64
+    public static $scripts = array();
65
+    public static $styles = array();
66
+    public static $headers = array();
67
+    private static $rootMounted = false;
68
+    private static $fsSetup = false;
69
+
70
+    /** @var array Local cache of version.php */
71
+    private static $versionCache = null;
72
+
73
+    protected static function getAppManager() {
74
+        return \OC::$server->getAppManager();
75
+    }
76
+
77
+    private static function initLocalStorageRootFS() {
78
+        // mount local file backend as root
79
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
80
+        //first set up the local "root" storage
81
+        \OC\Files\Filesystem::initMountManager();
82
+        if (!self::$rootMounted) {
83
+            \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
84
+            self::$rootMounted = true;
85
+        }
86
+    }
87
+
88
+    /**
89
+     * mounting an object storage as the root fs will in essence remove the
90
+     * necessity of a data folder being present.
91
+     * TODO make home storage aware of this and use the object storage instead of local disk access
92
+     *
93
+     * @param array $config containing 'class' and optional 'arguments'
94
+     */
95
+    private static function initObjectStoreRootFS($config) {
96
+        // check misconfiguration
97
+        if (empty($config['class'])) {
98
+            \OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
99
+        }
100
+        if (!isset($config['arguments'])) {
101
+            $config['arguments'] = array();
102
+        }
103
+
104
+        // instantiate object store implementation
105
+        $name = $config['class'];
106
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
107
+            $segments = explode('\\', $name);
108
+            OC_App::loadApp(strtolower($segments[1]));
109
+        }
110
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
111
+        // mount with plain / root object store implementation
112
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
113
+
114
+        // mount object storage as root
115
+        \OC\Files\Filesystem::initMountManager();
116
+        if (!self::$rootMounted) {
117
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
118
+            self::$rootMounted = true;
119
+        }
120
+    }
121
+
122
+    /**
123
+     * mounting an object storage as the root fs will in essence remove the
124
+     * necessity of a data folder being present.
125
+     *
126
+     * @param array $config containing 'class' and optional 'arguments'
127
+     */
128
+    private static function initObjectStoreMultibucketRootFS($config) {
129
+        // check misconfiguration
130
+        if (empty($config['class'])) {
131
+            \OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
132
+        }
133
+        if (!isset($config['arguments'])) {
134
+            $config['arguments'] = array();
135
+        }
136
+
137
+        // instantiate object store implementation
138
+        $name = $config['class'];
139
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
140
+            $segments = explode('\\', $name);
141
+            OC_App::loadApp(strtolower($segments[1]));
142
+        }
143
+
144
+        if (!isset($config['arguments']['bucket'])) {
145
+            $config['arguments']['bucket'] = '';
146
+        }
147
+        // put the root FS always in first bucket for multibucket configuration
148
+        $config['arguments']['bucket'] .= '0';
149
+
150
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
151
+        // mount with plain / root object store implementation
152
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
153
+
154
+        // mount object storage as root
155
+        \OC\Files\Filesystem::initMountManager();
156
+        if (!self::$rootMounted) {
157
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
158
+            self::$rootMounted = true;
159
+        }
160
+    }
161
+
162
+    /**
163
+     * Can be set up
164
+     *
165
+     * @param string $user
166
+     * @return boolean
167
+     * @description configure the initial filesystem based on the configuration
168
+     */
169
+    public static function setupFS($user = '') {
170
+        //setting up the filesystem twice can only lead to trouble
171
+        if (self::$fsSetup) {
172
+            return false;
173
+        }
174
+
175
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
176
+
177
+        // If we are not forced to load a specific user we load the one that is logged in
178
+        if ($user === null) {
179
+            $user = '';
180
+        } else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
181
+            $user = OC_User::getUser();
182
+        }
183
+
184
+        // load all filesystem apps before, so no setup-hook gets lost
185
+        OC_App::loadApps(array('filesystem'));
186
+
187
+        // the filesystem will finish when $user is not empty,
188
+        // mark fs setup here to avoid doing the setup from loading
189
+        // OC_Filesystem
190
+        if ($user != '') {
191
+            self::$fsSetup = true;
192
+        }
193
+
194
+        \OC\Files\Filesystem::initMountManager();
195
+
196
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
197
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
198
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
199
+                /** @var \OC\Files\Storage\Common $storage */
200
+                $storage->setMountOptions($mount->getOptions());
201
+            }
202
+            return $storage;
203
+        });
204
+
205
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
206
+            if (!$mount->getOption('enable_sharing', true)) {
207
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
208
+                    'storage' => $storage,
209
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
210
+                ]);
211
+            }
212
+            return $storage;
213
+        });
214
+
215
+        // install storage availability wrapper, before most other wrappers
216
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, $storage) {
217
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
218
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
219
+            }
220
+            return $storage;
221
+        });
222
+
223
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
224
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
225
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
226
+            }
227
+            return $storage;
228
+        });
229
+
230
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
231
+            // set up quota for home storages, even for other users
232
+            // which can happen when using sharing
233
+
234
+            /**
235
+             * @var \OC\Files\Storage\Storage $storage
236
+             */
237
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
238
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
239
+            ) {
240
+                /** @var \OC\Files\Storage\Home $storage */
241
+                if (is_object($storage->getUser())) {
242
+                    $user = $storage->getUser()->getUID();
243
+                    $quota = OC_Util::getUserQuota($user);
244
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
245
+                        return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
246
+                    }
247
+                }
248
+            }
249
+
250
+            return $storage;
251
+        });
252
+
253
+        OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
254
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
255
+
256
+        //check if we are using an object storage
257
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
258
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
259
+
260
+        // use the same order as in ObjectHomeMountProvider
261
+        if (isset($objectStoreMultibucket)) {
262
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
263
+        } elseif (isset($objectStore)) {
264
+            self::initObjectStoreRootFS($objectStore);
265
+        } else {
266
+            self::initLocalStorageRootFS();
267
+        }
268
+
269
+        if ($user != '' && !OCP\User::userExists($user)) {
270
+            \OC::$server->getEventLogger()->end('setup_fs');
271
+            return false;
272
+        }
273
+
274
+        //if we aren't logged in, there is no use to set up the filesystem
275
+        if ($user != "") {
276
+
277
+            $userDir = '/' . $user . '/files';
278
+
279
+            //jail the user into his "home" directory
280
+            \OC\Files\Filesystem::init($user, $userDir);
281
+
282
+            OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
283
+        }
284
+        \OC::$server->getEventLogger()->end('setup_fs');
285
+        return true;
286
+    }
287
+
288
+    /**
289
+     * check if a password is required for each public link
290
+     *
291
+     * @return boolean
292
+     */
293
+    public static function isPublicLinkPasswordRequired() {
294
+        $appConfig = \OC::$server->getAppConfig();
295
+        $enforcePassword = $appConfig->getValue('core', 'shareapi_enforce_links_password', 'no');
296
+        return ($enforcePassword === 'yes') ? true : false;
297
+    }
298
+
299
+    /**
300
+     * check if sharing is disabled for the current user
301
+     * @param IConfig $config
302
+     * @param IGroupManager $groupManager
303
+     * @param IUser|null $user
304
+     * @return bool
305
+     */
306
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
307
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
308
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
309
+            $excludedGroups = json_decode($groupsList);
310
+            if (is_null($excludedGroups)) {
311
+                $excludedGroups = explode(',', $groupsList);
312
+                $newValue = json_encode($excludedGroups);
313
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
314
+            }
315
+            $usersGroups = $groupManager->getUserGroupIds($user);
316
+            if (!empty($usersGroups)) {
317
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
318
+                // if the user is only in groups which are disabled for sharing then
319
+                // sharing is also disabled for the user
320
+                if (empty($remainingGroups)) {
321
+                    return true;
322
+                }
323
+            }
324
+        }
325
+        return false;
326
+    }
327
+
328
+    /**
329
+     * check if share API enforces a default expire date
330
+     *
331
+     * @return boolean
332
+     */
333
+    public static function isDefaultExpireDateEnforced() {
334
+        $isDefaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
335
+        $enforceDefaultExpireDate = false;
336
+        if ($isDefaultExpireDateEnabled === 'yes') {
337
+            $value = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
338
+            $enforceDefaultExpireDate = ($value === 'yes') ? true : false;
339
+        }
340
+
341
+        return $enforceDefaultExpireDate;
342
+    }
343
+
344
+    /**
345
+     * Get the quota of a user
346
+     *
347
+     * @param string $userId
348
+     * @return int Quota bytes
349
+     */
350
+    public static function getUserQuota($userId) {
351
+        $user = \OC::$server->getUserManager()->get($userId);
352
+        if (is_null($user)) {
353
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
354
+        }
355
+        $userQuota = $user->getQuota();
356
+        if($userQuota === 'none') {
357
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
358
+        }
359
+        return OC_Helper::computerFileSize($userQuota);
360
+    }
361
+
362
+    /**
363
+     * copies the skeleton to the users /files
364
+     *
365
+     * @param String $userId
366
+     * @param \OCP\Files\Folder $userDirectory
367
+     * @throws \RuntimeException
368
+     */
369
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
370
+
371
+        $skeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
372
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
373
+
374
+        if ($instanceId === null) {
375
+            throw new \RuntimeException('no instance id!');
376
+        }
377
+        $appdata = 'appdata_' . $instanceId;
378
+        if ($userId === $appdata) {
379
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
380
+        }
381
+
382
+        if (!empty($skeletonDirectory)) {
383
+            \OCP\Util::writeLog(
384
+                'files_skeleton',
385
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
386
+                \OCP\Util::DEBUG
387
+            );
388
+            self::copyr($skeletonDirectory, $userDirectory);
389
+            // update the file cache
390
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
391
+        }
392
+    }
393
+
394
+    /**
395
+     * copies a directory recursively by using streams
396
+     *
397
+     * @param string $source
398
+     * @param \OCP\Files\Folder $target
399
+     * @return void
400
+     */
401
+    public static function copyr($source, \OCP\Files\Folder $target) {
402
+        $logger = \OC::$server->getLogger();
403
+
404
+        // Verify if folder exists
405
+        $dir = opendir($source);
406
+        if($dir === false) {
407
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
408
+            return;
409
+        }
410
+
411
+        // Copy the files
412
+        while (false !== ($file = readdir($dir))) {
413
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
414
+                if (is_dir($source . '/' . $file)) {
415
+                    $child = $target->newFolder($file);
416
+                    self::copyr($source . '/' . $file, $child);
417
+                } else {
418
+                    $child = $target->newFile($file);
419
+                    $sourceStream = fopen($source . '/' . $file, 'r');
420
+                    if($sourceStream === false) {
421
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
422
+                        closedir($dir);
423
+                        return;
424
+                    }
425
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
426
+                }
427
+            }
428
+        }
429
+        closedir($dir);
430
+    }
431
+
432
+    /**
433
+     * @return void
434
+     */
435
+    public static function tearDownFS() {
436
+        \OC\Files\Filesystem::tearDown();
437
+        \OC::$server->getRootFolder()->clearCache();
438
+        self::$fsSetup = false;
439
+        self::$rootMounted = false;
440
+    }
441
+
442
+    /**
443
+     * get the current installed version of ownCloud
444
+     *
445
+     * @return array
446
+     */
447
+    public static function getVersion() {
448
+        OC_Util::loadVersion();
449
+        return self::$versionCache['OC_Version'];
450
+    }
451
+
452
+    /**
453
+     * get the current installed version string of ownCloud
454
+     *
455
+     * @return string
456
+     */
457
+    public static function getVersionString() {
458
+        OC_Util::loadVersion();
459
+        return self::$versionCache['OC_VersionString'];
460
+    }
461
+
462
+    /**
463
+     * @deprecated the value is of no use anymore
464
+     * @return string
465
+     */
466
+    public static function getEditionString() {
467
+        return '';
468
+    }
469
+
470
+    /**
471
+     * @description get the update channel of the current installed of ownCloud.
472
+     * @return string
473
+     */
474
+    public static function getChannel() {
475
+        OC_Util::loadVersion();
476
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
477
+    }
478
+
479
+    /**
480
+     * @description get the build number of the current installed of ownCloud.
481
+     * @return string
482
+     */
483
+    public static function getBuild() {
484
+        OC_Util::loadVersion();
485
+        return self::$versionCache['OC_Build'];
486
+    }
487
+
488
+    /**
489
+     * @description load the version.php into the session as cache
490
+     */
491
+    private static function loadVersion() {
492
+        if (self::$versionCache !== null) {
493
+            return;
494
+        }
495
+
496
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
497
+        require OC::$SERVERROOT . '/version.php';
498
+        /** @var $timestamp int */
499
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
500
+        /** @var $OC_Version string */
501
+        self::$versionCache['OC_Version'] = $OC_Version;
502
+        /** @var $OC_VersionString string */
503
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
504
+        /** @var $OC_Build string */
505
+        self::$versionCache['OC_Build'] = $OC_Build;
506
+
507
+        /** @var $OC_Channel string */
508
+        self::$versionCache['OC_Channel'] = $OC_Channel;
509
+    }
510
+
511
+    /**
512
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
513
+     *
514
+     * @param string $application application to get the files from
515
+     * @param string $directory directory within this application (css, js, vendor, etc)
516
+     * @param string $file the file inside of the above folder
517
+     * @return string the path
518
+     */
519
+    private static function generatePath($application, $directory, $file) {
520
+        if (is_null($file)) {
521
+            $file = $application;
522
+            $application = "";
523
+        }
524
+        if (!empty($application)) {
525
+            return "$application/$directory/$file";
526
+        } else {
527
+            return "$directory/$file";
528
+        }
529
+    }
530
+
531
+    /**
532
+     * add a javascript file
533
+     *
534
+     * @param string $application application id
535
+     * @param string|null $file filename
536
+     * @param bool $prepend prepend the Script to the beginning of the list
537
+     * @return void
538
+     */
539
+    public static function addScript($application, $file = null, $prepend = false) {
540
+        $path = OC_Util::generatePath($application, 'js', $file);
541
+
542
+        // core js files need separate handling
543
+        if ($application !== 'core' && $file !== null) {
544
+            self::addTranslations ( $application );
545
+        }
546
+        self::addExternalResource($application, $prepend, $path, "script");
547
+    }
548
+
549
+    /**
550
+     * add a javascript file from the vendor sub folder
551
+     *
552
+     * @param string $application application id
553
+     * @param string|null $file filename
554
+     * @param bool $prepend prepend the Script to the beginning of the list
555
+     * @return void
556
+     */
557
+    public static function addVendorScript($application, $file = null, $prepend = false) {
558
+        $path = OC_Util::generatePath($application, 'vendor', $file);
559
+        self::addExternalResource($application, $prepend, $path, "script");
560
+    }
561
+
562
+    /**
563
+     * add a translation JS file
564
+     *
565
+     * @param string $application application id
566
+     * @param string $languageCode language code, defaults to the current language
567
+     * @param bool $prepend prepend the Script to the beginning of the list
568
+     */
569
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
570
+        if (is_null($languageCode)) {
571
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
572
+        }
573
+        if (!empty($application)) {
574
+            $path = "$application/l10n/$languageCode";
575
+        } else {
576
+            $path = "l10n/$languageCode";
577
+        }
578
+        self::addExternalResource($application, $prepend, $path, "script");
579
+    }
580
+
581
+    /**
582
+     * add a css file
583
+     *
584
+     * @param string $application application id
585
+     * @param string|null $file filename
586
+     * @param bool $prepend prepend the Style to the beginning of the list
587
+     * @return void
588
+     */
589
+    public static function addStyle($application, $file = null, $prepend = false) {
590
+        $path = OC_Util::generatePath($application, 'css', $file);
591
+        self::addExternalResource($application, $prepend, $path, "style");
592
+    }
593
+
594
+    /**
595
+     * add a css file from the vendor sub folder
596
+     *
597
+     * @param string $application application id
598
+     * @param string|null $file filename
599
+     * @param bool $prepend prepend the Style to the beginning of the list
600
+     * @return void
601
+     */
602
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
603
+        $path = OC_Util::generatePath($application, 'vendor', $file);
604
+        self::addExternalResource($application, $prepend, $path, "style");
605
+    }
606
+
607
+    /**
608
+     * add an external resource css/js file
609
+     *
610
+     * @param string $application application id
611
+     * @param bool $prepend prepend the file to the beginning of the list
612
+     * @param string $path
613
+     * @param string $type (script or style)
614
+     * @return void
615
+     */
616
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
617
+
618
+        if ($type === "style") {
619
+            if (!in_array($path, self::$styles)) {
620
+                if ($prepend === true) {
621
+                    array_unshift ( self::$styles, $path );
622
+                } else {
623
+                    self::$styles[] = $path;
624
+                }
625
+            }
626
+        } elseif ($type === "script") {
627
+            if (!in_array($path, self::$scripts)) {
628
+                if ($prepend === true) {
629
+                    array_unshift ( self::$scripts, $path );
630
+                } else {
631
+                    self::$scripts [] = $path;
632
+                }
633
+            }
634
+        }
635
+    }
636
+
637
+    /**
638
+     * Add a custom element to the header
639
+     * If $text is null then the element will be written as empty element.
640
+     * So use "" to get a closing tag.
641
+     * @param string $tag tag name of the element
642
+     * @param array $attributes array of attributes for the element
643
+     * @param string $text the text content for the element
644
+     */
645
+    public static function addHeader($tag, $attributes, $text=null) {
646
+        self::$headers[] = array(
647
+            'tag' => $tag,
648
+            'attributes' => $attributes,
649
+            'text' => $text
650
+        );
651
+    }
652
+
653
+    /**
654
+     * formats a timestamp in the "right" way
655
+     *
656
+     * @param int $timestamp
657
+     * @param bool $dateOnly option to omit time from the result
658
+     * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
659
+     * @return string timestamp
660
+     *
661
+     * @deprecated Use \OC::$server->query('DateTimeFormatter') instead
662
+     */
663
+    public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
664
+        if ($timeZone !== null && !$timeZone instanceof \DateTimeZone) {
665
+            $timeZone = new \DateTimeZone($timeZone);
666
+        }
667
+
668
+        /** @var \OC\DateTimeFormatter $formatter */
669
+        $formatter = \OC::$server->query('DateTimeFormatter');
670
+        if ($dateOnly) {
671
+            return $formatter->formatDate($timestamp, 'long', $timeZone);
672
+        }
673
+        return $formatter->formatDateTime($timestamp, 'long', 'long', $timeZone);
674
+    }
675
+
676
+    /**
677
+     * check if the current server configuration is suitable for ownCloud
678
+     *
679
+     * @param \OC\SystemConfig $config
680
+     * @return array arrays with error messages and hints
681
+     */
682
+    public static function checkServer(\OC\SystemConfig $config) {
683
+        $l = \OC::$server->getL10N('lib');
684
+        $errors = array();
685
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
686
+
687
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
688
+            // this check needs to be done every time
689
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
690
+        }
691
+
692
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
693
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
694
+            return $errors;
695
+        }
696
+
697
+        $webServerRestart = false;
698
+        $setup = new \OC\Setup($config, \OC::$server->getIniWrapper(), \OC::$server->getL10N('lib'),
699
+            \OC::$server->query(\OCP\Defaults::class), \OC::$server->getLogger(), \OC::$server->getSecureRandom());
700
+
701
+        $urlGenerator = \OC::$server->getURLGenerator();
702
+
703
+        $availableDatabases = $setup->getSupportedDatabases();
704
+        if (empty($availableDatabases)) {
705
+            $errors[] = array(
706
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
707
+                'hint' => '' //TODO: sane hint
708
+            );
709
+            $webServerRestart = true;
710
+        }
711
+
712
+        // Check if config folder is writable.
713
+        if(!OC_Helper::isReadOnlyConfigEnabled()) {
714
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
715
+                $errors[] = array(
716
+                    'error' => $l->t('Cannot write into "config" directory'),
717
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
718
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
719
+                );
720
+            }
721
+        }
722
+
723
+        // Check if there is a writable install folder.
724
+        if ($config->getValue('appstoreenabled', true)) {
725
+            if (OC_App::getInstallPath() === null
726
+                || !is_writable(OC_App::getInstallPath())
727
+                || !is_readable(OC_App::getInstallPath())
728
+            ) {
729
+                $errors[] = array(
730
+                    'error' => $l->t('Cannot write into "apps" directory'),
731
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
732
+                        . ' or disabling the appstore in the config file. See %s',
733
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
734
+                );
735
+            }
736
+        }
737
+        // Create root dir.
738
+        if ($config->getValue('installed', false)) {
739
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
740
+                $success = @mkdir($CONFIG_DATADIRECTORY);
741
+                if ($success) {
742
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
743
+                } else {
744
+                    $errors[] = [
745
+                        'error' => $l->t('Cannot create "data" directory'),
746
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
747
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
748
+                    ];
749
+                }
750
+            } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
751
+                //common hint for all file permissions error messages
752
+                $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
753
+                    [$urlGenerator->linkToDocs('admin-dir_permissions')]);
754
+                $errors[] = [
755
+                    'error' => 'Your data directory is not writable',
756
+                    'hint' => $permissionsHint
757
+                ];
758
+            } else {
759
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
760
+            }
761
+        }
762
+
763
+        if (!OC_Util::isSetLocaleWorking()) {
764
+            $errors[] = array(
765
+                'error' => $l->t('Setting locale to %s failed',
766
+                    array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
767
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
768
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
769
+            );
770
+        }
771
+
772
+        // Contains the dependencies that should be checked against
773
+        // classes = class_exists
774
+        // functions = function_exists
775
+        // defined = defined
776
+        // ini = ini_get
777
+        // If the dependency is not found the missing module name is shown to the EndUser
778
+        // When adding new checks always verify that they pass on Travis as well
779
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
780
+        $dependencies = array(
781
+            'classes' => array(
782
+                'ZipArchive' => 'zip',
783
+                'DOMDocument' => 'dom',
784
+                'XMLWriter' => 'XMLWriter',
785
+                'XMLReader' => 'XMLReader',
786
+            ),
787
+            'functions' => [
788
+                'xml_parser_create' => 'libxml',
789
+                'mb_strcut' => 'mb multibyte',
790
+                'ctype_digit' => 'ctype',
791
+                'json_encode' => 'JSON',
792
+                'gd_info' => 'GD',
793
+                'gzencode' => 'zlib',
794
+                'iconv' => 'iconv',
795
+                'simplexml_load_string' => 'SimpleXML',
796
+                'hash' => 'HASH Message Digest Framework',
797
+                'curl_init' => 'cURL',
798
+                'openssl_verify' => 'OpenSSL',
799
+            ],
800
+            'defined' => array(
801
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
802
+            ),
803
+            'ini' => [
804
+                'default_charset' => 'UTF-8',
805
+            ],
806
+        );
807
+        $missingDependencies = array();
808
+        $invalidIniSettings = [];
809
+        $moduleHint = $l->t('Please ask your server administrator to install the module.');
810
+
811
+        /**
812
+         * FIXME: The dependency check does not work properly on HHVM on the moment
813
+         *        and prevents installation. Once HHVM is more compatible with our
814
+         *        approach to check for these values we should re-enable those
815
+         *        checks.
816
+         */
817
+        $iniWrapper = \OC::$server->getIniWrapper();
818
+        if (!self::runningOnHhvm()) {
819
+            foreach ($dependencies['classes'] as $class => $module) {
820
+                if (!class_exists($class)) {
821
+                    $missingDependencies[] = $module;
822
+                }
823
+            }
824
+            foreach ($dependencies['functions'] as $function => $module) {
825
+                if (!function_exists($function)) {
826
+                    $missingDependencies[] = $module;
827
+                }
828
+            }
829
+            foreach ($dependencies['defined'] as $defined => $module) {
830
+                if (!defined($defined)) {
831
+                    $missingDependencies[] = $module;
832
+                }
833
+            }
834
+            foreach ($dependencies['ini'] as $setting => $expected) {
835
+                if (is_bool($expected)) {
836
+                    if ($iniWrapper->getBool($setting) !== $expected) {
837
+                        $invalidIniSettings[] = [$setting, $expected];
838
+                    }
839
+                }
840
+                if (is_int($expected)) {
841
+                    if ($iniWrapper->getNumeric($setting) !== $expected) {
842
+                        $invalidIniSettings[] = [$setting, $expected];
843
+                    }
844
+                }
845
+                if (is_string($expected)) {
846
+                    if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
847
+                        $invalidIniSettings[] = [$setting, $expected];
848
+                    }
849
+                }
850
+            }
851
+        }
852
+
853
+        foreach($missingDependencies as $missingDependency) {
854
+            $errors[] = array(
855
+                'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
856
+                'hint' => $moduleHint
857
+            );
858
+            $webServerRestart = true;
859
+        }
860
+        foreach($invalidIniSettings as $setting) {
861
+            if(is_bool($setting[1])) {
862
+                $setting[1] = ($setting[1]) ? 'on' : 'off';
863
+            }
864
+            $errors[] = [
865
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
866
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
867
+            ];
868
+            $webServerRestart = true;
869
+        }
870
+
871
+        /**
872
+         * The mbstring.func_overload check can only be performed if the mbstring
873
+         * module is installed as it will return null if the checking setting is
874
+         * not available and thus a check on the boolean value fails.
875
+         *
876
+         * TODO: Should probably be implemented in the above generic dependency
877
+         *       check somehow in the long-term.
878
+         */
879
+        if($iniWrapper->getBool('mbstring.func_overload') !== null &&
880
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
881
+            $errors[] = array(
882
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
883
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
884
+            );
885
+        }
886
+
887
+        if(function_exists('xml_parser_create') &&
888
+            LIBXML_LOADED_VERSION < 20700 ) {
889
+            $version = LIBXML_LOADED_VERSION;
890
+            $major = floor($version/10000);
891
+            $version -= ($major * 10000);
892
+            $minor = floor($version/100);
893
+            $version -= ($minor * 100);
894
+            $patch = $version;
895
+            $errors[] = array(
896
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
897
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
898
+            );
899
+        }
900
+
901
+        if (!self::isAnnotationsWorking()) {
902
+            $errors[] = array(
903
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
904
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
905
+            );
906
+        }
907
+
908
+        if (!\OC::$CLI && $webServerRestart) {
909
+            $errors[] = array(
910
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
911
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
912
+            );
913
+        }
914
+
915
+        $errors = array_merge($errors, self::checkDatabaseVersion());
916
+
917
+        // Cache the result of this function
918
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
919
+
920
+        return $errors;
921
+    }
922
+
923
+    /**
924
+     * Check the database version
925
+     *
926
+     * @return array errors array
927
+     */
928
+    public static function checkDatabaseVersion() {
929
+        $l = \OC::$server->getL10N('lib');
930
+        $errors = array();
931
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
932
+        if ($dbType === 'pgsql') {
933
+            // check PostgreSQL version
934
+            try {
935
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
936
+                $data = $result->fetchRow();
937
+                if (isset($data['server_version'])) {
938
+                    $version = $data['server_version'];
939
+                    if (version_compare($version, '9.0.0', '<')) {
940
+                        $errors[] = array(
941
+                            'error' => $l->t('PostgreSQL >= 9 required'),
942
+                            'hint' => $l->t('Please upgrade your database version')
943
+                        );
944
+                    }
945
+                }
946
+            } catch (\Doctrine\DBAL\DBALException $e) {
947
+                $logger = \OC::$server->getLogger();
948
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
949
+                $logger->logException($e);
950
+            }
951
+        }
952
+        return $errors;
953
+    }
954
+
955
+    /**
956
+     * Check for correct file permissions of data directory
957
+     *
958
+     * @param string $dataDirectory
959
+     * @return array arrays with error messages and hints
960
+     */
961
+    public static function checkDataDirectoryPermissions($dataDirectory) {
962
+        $l = \OC::$server->getL10N('lib');
963
+        $errors = array();
964
+        $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
965
+            . ' cannot be listed by other users.');
966
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
967
+        if (substr($perms, -1) !== '0') {
968
+            chmod($dataDirectory, 0770);
969
+            clearstatcache();
970
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
971
+            if ($perms[2] !== '0') {
972
+                $errors[] = [
973
+                    'error' => $l->t('Your data directory is readable by other users'),
974
+                    'hint' => $permissionsModHint
975
+                ];
976
+            }
977
+        }
978
+        return $errors;
979
+    }
980
+
981
+    /**
982
+     * Check that the data directory exists and is valid by
983
+     * checking the existence of the ".ocdata" file.
984
+     *
985
+     * @param string $dataDirectory data directory path
986
+     * @return array errors found
987
+     */
988
+    public static function checkDataDirectoryValidity($dataDirectory) {
989
+        $l = \OC::$server->getL10N('lib');
990
+        $errors = [];
991
+        if ($dataDirectory[0] !== '/') {
992
+            $errors[] = [
993
+                'error' => $l->t('Your data directory must be an absolute path'),
994
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
995
+            ];
996
+        }
997
+        if (!file_exists($dataDirectory . '/.ocdata')) {
998
+            $errors[] = [
999
+                'error' => $l->t('Your data directory is invalid'),
1000
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1001
+                    ' in the root of the data directory.')
1002
+            ];
1003
+        }
1004
+        return $errors;
1005
+    }
1006
+
1007
+    /**
1008
+     * Check if the user is logged in, redirects to home if not. With
1009
+     * redirect URL parameter to the request URI.
1010
+     *
1011
+     * @return void
1012
+     */
1013
+    public static function checkLoggedIn() {
1014
+        // Check if we are a user
1015
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1016
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1017
+                        'core.login.showLoginForm',
1018
+                        [
1019
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1020
+                        ]
1021
+                    )
1022
+            );
1023
+            exit();
1024
+        }
1025
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1026
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1027
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1028
+            exit();
1029
+        }
1030
+    }
1031
+
1032
+    /**
1033
+     * Check if the user is a admin, redirects to home if not
1034
+     *
1035
+     * @return void
1036
+     */
1037
+    public static function checkAdminUser() {
1038
+        OC_Util::checkLoggedIn();
1039
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1040
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1041
+            exit();
1042
+        }
1043
+    }
1044
+
1045
+    /**
1046
+     * Check if the user is a subadmin, redirects to home if not
1047
+     *
1048
+     * @return null|boolean $groups where the current user is subadmin
1049
+     */
1050
+    public static function checkSubAdminUser() {
1051
+        OC_Util::checkLoggedIn();
1052
+        $userObject = \OC::$server->getUserSession()->getUser();
1053
+        $isSubAdmin = false;
1054
+        if($userObject !== null) {
1055
+            $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1056
+        }
1057
+
1058
+        if (!$isSubAdmin) {
1059
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1060
+            exit();
1061
+        }
1062
+        return true;
1063
+    }
1064
+
1065
+    /**
1066
+     * Returns the URL of the default page
1067
+     * based on the system configuration and
1068
+     * the apps visible for the current user
1069
+     *
1070
+     * @return string URL
1071
+     */
1072
+    public static function getDefaultPageUrl() {
1073
+        $urlGenerator = \OC::$server->getURLGenerator();
1074
+        // Deny the redirect if the URL contains a @
1075
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1076
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1077
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1078
+        } else {
1079
+            $defaultPage = \OC::$server->getAppConfig()->getValue('core', 'defaultpage');
1080
+            if ($defaultPage) {
1081
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1082
+            } else {
1083
+                $appId = 'files';
1084
+                $config = \OC::$server->getConfig();
1085
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1086
+                // find the first app that is enabled for the current user
1087
+                foreach ($defaultApps as $defaultApp) {
1088
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1089
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1090
+                        $appId = $defaultApp;
1091
+                        break;
1092
+                    }
1093
+                }
1094
+
1095
+                if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1096
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1097
+                } else {
1098
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1099
+                }
1100
+            }
1101
+        }
1102
+        return $location;
1103
+    }
1104
+
1105
+    /**
1106
+     * Redirect to the user default page
1107
+     *
1108
+     * @return void
1109
+     */
1110
+    public static function redirectToDefaultPage() {
1111
+        $location = self::getDefaultPageUrl();
1112
+        header('Location: ' . $location);
1113
+        exit();
1114
+    }
1115
+
1116
+    /**
1117
+     * get an id unique for this instance
1118
+     *
1119
+     * @return string
1120
+     */
1121
+    public static function getInstanceId() {
1122
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1123
+        if (is_null($id)) {
1124
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1125
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1126
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1127
+        }
1128
+        return $id;
1129
+    }
1130
+
1131
+    /**
1132
+     * Public function to sanitize HTML
1133
+     *
1134
+     * This function is used to sanitize HTML and should be applied on any
1135
+     * string or array of strings before displaying it on a web page.
1136
+     *
1137
+     * @param string|array $value
1138
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1139
+     */
1140
+    public static function sanitizeHTML($value) {
1141
+        if (is_array($value)) {
1142
+            $value = array_map(function($value) {
1143
+                return self::sanitizeHTML($value);
1144
+            }, $value);
1145
+        } else {
1146
+            // Specify encoding for PHP<5.4
1147
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1148
+        }
1149
+        return $value;
1150
+    }
1151
+
1152
+    /**
1153
+     * Public function to encode url parameters
1154
+     *
1155
+     * This function is used to encode path to file before output.
1156
+     * Encoding is done according to RFC 3986 with one exception:
1157
+     * Character '/' is preserved as is.
1158
+     *
1159
+     * @param string $component part of URI to encode
1160
+     * @return string
1161
+     */
1162
+    public static function encodePath($component) {
1163
+        $encoded = rawurlencode($component);
1164
+        $encoded = str_replace('%2F', '/', $encoded);
1165
+        return $encoded;
1166
+    }
1167
+
1168
+
1169
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1170
+        // php dev server does not support htaccess
1171
+        if (php_sapi_name() === 'cli-server') {
1172
+            return false;
1173
+        }
1174
+
1175
+        // testdata
1176
+        $fileName = '/htaccesstest.txt';
1177
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1178
+
1179
+        // creating a test file
1180
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1181
+
1182
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1183
+            return false;
1184
+        }
1185
+
1186
+        $fp = @fopen($testFile, 'w');
1187
+        if (!$fp) {
1188
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1189
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1190
+        }
1191
+        fwrite($fp, $testContent);
1192
+        fclose($fp);
1193
+
1194
+        return $testContent;
1195
+    }
1196
+
1197
+    /**
1198
+     * Check if the .htaccess file is working
1199
+     * @param \OCP\IConfig $config
1200
+     * @return bool
1201
+     * @throws Exception
1202
+     * @throws \OC\HintException If the test file can't get written.
1203
+     */
1204
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1205
+
1206
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1207
+            return true;
1208
+        }
1209
+
1210
+        $testContent = $this->createHtaccessTestFile($config);
1211
+        if ($testContent === false) {
1212
+            return false;
1213
+        }
1214
+
1215
+        $fileName = '/htaccesstest.txt';
1216
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1217
+
1218
+        // accessing the file via http
1219
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1220
+        try {
1221
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1222
+        } catch (\Exception $e) {
1223
+            $content = false;
1224
+        }
1225
+
1226
+        // cleanup
1227
+        @unlink($testFile);
1228
+
1229
+        /*
1230 1230
 		 * If the content is not equal to test content our .htaccess
1231 1231
 		 * is working as required
1232 1232
 		 */
1233
-		return $content !== $testContent;
1234
-	}
1235
-
1236
-	/**
1237
-	 * Check if the setlocal call does not work. This can happen if the right
1238
-	 * local packages are not available on the server.
1239
-	 *
1240
-	 * @return bool
1241
-	 */
1242
-	public static function isSetLocaleWorking() {
1243
-		\Patchwork\Utf8\Bootup::initLocale();
1244
-		if ('' === basename('§')) {
1245
-			return false;
1246
-		}
1247
-		return true;
1248
-	}
1249
-
1250
-	/**
1251
-	 * Check if it's possible to get the inline annotations
1252
-	 *
1253
-	 * @return bool
1254
-	 */
1255
-	public static function isAnnotationsWorking() {
1256
-		$reflection = new \ReflectionMethod(__METHOD__);
1257
-		$docs = $reflection->getDocComment();
1258
-
1259
-		return (is_string($docs) && strlen($docs) > 50);
1260
-	}
1261
-
1262
-	/**
1263
-	 * Check if the PHP module fileinfo is loaded.
1264
-	 *
1265
-	 * @return bool
1266
-	 */
1267
-	public static function fileInfoLoaded() {
1268
-		return function_exists('finfo_open');
1269
-	}
1270
-
1271
-	/**
1272
-	 * clear all levels of output buffering
1273
-	 *
1274
-	 * @return void
1275
-	 */
1276
-	public static function obEnd() {
1277
-		while (ob_get_level()) {
1278
-			ob_end_clean();
1279
-		}
1280
-	}
1281
-
1282
-	/**
1283
-	 * Checks whether the server is running on Mac OS X
1284
-	 *
1285
-	 * @return bool true if running on Mac OS X, false otherwise
1286
-	 */
1287
-	public static function runningOnMac() {
1288
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1289
-	}
1290
-
1291
-	/**
1292
-	 * Checks whether server is running on HHVM
1293
-	 *
1294
-	 * @return bool True if running on HHVM, false otherwise
1295
-	 */
1296
-	public static function runningOnHhvm() {
1297
-		return defined('HHVM_VERSION');
1298
-	}
1299
-
1300
-	/**
1301
-	 * Handles the case that there may not be a theme, then check if a "default"
1302
-	 * theme exists and take that one
1303
-	 *
1304
-	 * @return string the theme
1305
-	 */
1306
-	public static function getTheme() {
1307
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1308
-
1309
-		if ($theme === '') {
1310
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1311
-				$theme = 'default';
1312
-			}
1313
-		}
1314
-
1315
-		return $theme;
1316
-	}
1317
-
1318
-	/**
1319
-	 * Clear a single file from the opcode cache
1320
-	 * This is useful for writing to the config file
1321
-	 * in case the opcode cache does not re-validate files
1322
-	 * Returns true if successful, false if unsuccessful:
1323
-	 * caller should fall back on clearing the entire cache
1324
-	 * with clearOpcodeCache() if unsuccessful
1325
-	 *
1326
-	 * @param string $path the path of the file to clear from the cache
1327
-	 * @return bool true if underlying function returns true, otherwise false
1328
-	 */
1329
-	public static function deleteFromOpcodeCache($path) {
1330
-		$ret = false;
1331
-		if ($path) {
1332
-			// APC >= 3.1.1
1333
-			if (function_exists('apc_delete_file')) {
1334
-				$ret = @apc_delete_file($path);
1335
-			}
1336
-			// Zend OpCache >= 7.0.0, PHP >= 5.5.0
1337
-			if (function_exists('opcache_invalidate')) {
1338
-				$ret = opcache_invalidate($path);
1339
-			}
1340
-		}
1341
-		return $ret;
1342
-	}
1343
-
1344
-	/**
1345
-	 * Clear the opcode cache if one exists
1346
-	 * This is necessary for writing to the config file
1347
-	 * in case the opcode cache does not re-validate files
1348
-	 *
1349
-	 * @return void
1350
-	 */
1351
-	public static function clearOpcodeCache() {
1352
-		// APC
1353
-		if (function_exists('apc_clear_cache')) {
1354
-			apc_clear_cache();
1355
-		}
1356
-		// Zend Opcache
1357
-		if (function_exists('accelerator_reset')) {
1358
-			accelerator_reset();
1359
-		}
1360
-		// XCache
1361
-		if (function_exists('xcache_clear_cache')) {
1362
-			if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1363
-				\OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OCP\Util::WARN);
1364
-			} else {
1365
-				@xcache_clear_cache(XC_TYPE_PHP, 0);
1366
-			}
1367
-		}
1368
-		// Opcache (PHP >= 5.5)
1369
-		if (function_exists('opcache_reset')) {
1370
-			opcache_reset();
1371
-		}
1372
-	}
1373
-
1374
-	/**
1375
-	 * Normalize a unicode string
1376
-	 *
1377
-	 * @param string $value a not normalized string
1378
-	 * @return bool|string
1379
-	 */
1380
-	public static function normalizeUnicode($value) {
1381
-		if(Normalizer::isNormalized($value)) {
1382
-			return $value;
1383
-		}
1384
-
1385
-		$normalizedValue = Normalizer::normalize($value);
1386
-		if ($normalizedValue === null || $normalizedValue === false) {
1387
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1388
-			return $value;
1389
-		}
1390
-
1391
-		return $normalizedValue;
1392
-	}
1393
-
1394
-	/**
1395
-	 * @param boolean|string $file
1396
-	 * @return string
1397
-	 */
1398
-	public static function basename($file) {
1399
-		$file = rtrim($file, '/');
1400
-		$t = explode('/', $file);
1401
-		return array_pop($t);
1402
-	}
1403
-
1404
-	/**
1405
-	 * A human readable string is generated based on version and build number
1406
-	 *
1407
-	 * @return string
1408
-	 */
1409
-	public static function getHumanVersion() {
1410
-		$version = OC_Util::getVersionString();
1411
-		$build = OC_Util::getBuild();
1412
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1413
-			$version .= ' Build:' . $build;
1414
-		}
1415
-		return $version;
1416
-	}
1417
-
1418
-	/**
1419
-	 * Returns whether the given file name is valid
1420
-	 *
1421
-	 * @param string $file file name to check
1422
-	 * @return bool true if the file name is valid, false otherwise
1423
-	 * @deprecated use \OC\Files\View::verifyPath()
1424
-	 */
1425
-	public static function isValidFileName($file) {
1426
-		$trimmed = trim($file);
1427
-		if ($trimmed === '') {
1428
-			return false;
1429
-		}
1430
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1431
-			return false;
1432
-		}
1433
-
1434
-		// detect part files
1435
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1436
-			return false;
1437
-		}
1438
-
1439
-		foreach (str_split($trimmed) as $char) {
1440
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1441
-				return false;
1442
-			}
1443
-		}
1444
-		return true;
1445
-	}
1446
-
1447
-	/**
1448
-	 * Check whether the instance needs to perform an upgrade,
1449
-	 * either when the core version is higher or any app requires
1450
-	 * an upgrade.
1451
-	 *
1452
-	 * @param \OC\SystemConfig $config
1453
-	 * @return bool whether the core or any app needs an upgrade
1454
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1455
-	 */
1456
-	public static function needUpgrade(\OC\SystemConfig $config) {
1457
-		if ($config->getValue('installed', false)) {
1458
-			$installedVersion = $config->getValue('version', '0.0.0');
1459
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1460
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1461
-			if ($versionDiff > 0) {
1462
-				return true;
1463
-			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1464
-				// downgrade with debug
1465
-				$installedMajor = explode('.', $installedVersion);
1466
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1467
-				$currentMajor = explode('.', $currentVersion);
1468
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1469
-				if ($installedMajor === $currentMajor) {
1470
-					// Same major, allow downgrade for developers
1471
-					return true;
1472
-				} else {
1473
-					// downgrade attempt, throw exception
1474
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1475
-				}
1476
-			} else if ($versionDiff < 0) {
1477
-				// downgrade attempt, throw exception
1478
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1479
-			}
1480
-
1481
-			// also check for upgrades for apps (independently from the user)
1482
-			$apps = \OC_App::getEnabledApps(false, true);
1483
-			$shouldUpgrade = false;
1484
-			foreach ($apps as $app) {
1485
-				if (\OC_App::shouldUpgrade($app)) {
1486
-					$shouldUpgrade = true;
1487
-					break;
1488
-				}
1489
-			}
1490
-			return $shouldUpgrade;
1491
-		} else {
1492
-			return false;
1493
-		}
1494
-	}
1233
+        return $content !== $testContent;
1234
+    }
1235
+
1236
+    /**
1237
+     * Check if the setlocal call does not work. This can happen if the right
1238
+     * local packages are not available on the server.
1239
+     *
1240
+     * @return bool
1241
+     */
1242
+    public static function isSetLocaleWorking() {
1243
+        \Patchwork\Utf8\Bootup::initLocale();
1244
+        if ('' === basename('§')) {
1245
+            return false;
1246
+        }
1247
+        return true;
1248
+    }
1249
+
1250
+    /**
1251
+     * Check if it's possible to get the inline annotations
1252
+     *
1253
+     * @return bool
1254
+     */
1255
+    public static function isAnnotationsWorking() {
1256
+        $reflection = new \ReflectionMethod(__METHOD__);
1257
+        $docs = $reflection->getDocComment();
1258
+
1259
+        return (is_string($docs) && strlen($docs) > 50);
1260
+    }
1261
+
1262
+    /**
1263
+     * Check if the PHP module fileinfo is loaded.
1264
+     *
1265
+     * @return bool
1266
+     */
1267
+    public static function fileInfoLoaded() {
1268
+        return function_exists('finfo_open');
1269
+    }
1270
+
1271
+    /**
1272
+     * clear all levels of output buffering
1273
+     *
1274
+     * @return void
1275
+     */
1276
+    public static function obEnd() {
1277
+        while (ob_get_level()) {
1278
+            ob_end_clean();
1279
+        }
1280
+    }
1281
+
1282
+    /**
1283
+     * Checks whether the server is running on Mac OS X
1284
+     *
1285
+     * @return bool true if running on Mac OS X, false otherwise
1286
+     */
1287
+    public static function runningOnMac() {
1288
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1289
+    }
1290
+
1291
+    /**
1292
+     * Checks whether server is running on HHVM
1293
+     *
1294
+     * @return bool True if running on HHVM, false otherwise
1295
+     */
1296
+    public static function runningOnHhvm() {
1297
+        return defined('HHVM_VERSION');
1298
+    }
1299
+
1300
+    /**
1301
+     * Handles the case that there may not be a theme, then check if a "default"
1302
+     * theme exists and take that one
1303
+     *
1304
+     * @return string the theme
1305
+     */
1306
+    public static function getTheme() {
1307
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1308
+
1309
+        if ($theme === '') {
1310
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1311
+                $theme = 'default';
1312
+            }
1313
+        }
1314
+
1315
+        return $theme;
1316
+    }
1317
+
1318
+    /**
1319
+     * Clear a single file from the opcode cache
1320
+     * This is useful for writing to the config file
1321
+     * in case the opcode cache does not re-validate files
1322
+     * Returns true if successful, false if unsuccessful:
1323
+     * caller should fall back on clearing the entire cache
1324
+     * with clearOpcodeCache() if unsuccessful
1325
+     *
1326
+     * @param string $path the path of the file to clear from the cache
1327
+     * @return bool true if underlying function returns true, otherwise false
1328
+     */
1329
+    public static function deleteFromOpcodeCache($path) {
1330
+        $ret = false;
1331
+        if ($path) {
1332
+            // APC >= 3.1.1
1333
+            if (function_exists('apc_delete_file')) {
1334
+                $ret = @apc_delete_file($path);
1335
+            }
1336
+            // Zend OpCache >= 7.0.0, PHP >= 5.5.0
1337
+            if (function_exists('opcache_invalidate')) {
1338
+                $ret = opcache_invalidate($path);
1339
+            }
1340
+        }
1341
+        return $ret;
1342
+    }
1343
+
1344
+    /**
1345
+     * Clear the opcode cache if one exists
1346
+     * This is necessary for writing to the config file
1347
+     * in case the opcode cache does not re-validate files
1348
+     *
1349
+     * @return void
1350
+     */
1351
+    public static function clearOpcodeCache() {
1352
+        // APC
1353
+        if (function_exists('apc_clear_cache')) {
1354
+            apc_clear_cache();
1355
+        }
1356
+        // Zend Opcache
1357
+        if (function_exists('accelerator_reset')) {
1358
+            accelerator_reset();
1359
+        }
1360
+        // XCache
1361
+        if (function_exists('xcache_clear_cache')) {
1362
+            if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1363
+                \OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OCP\Util::WARN);
1364
+            } else {
1365
+                @xcache_clear_cache(XC_TYPE_PHP, 0);
1366
+            }
1367
+        }
1368
+        // Opcache (PHP >= 5.5)
1369
+        if (function_exists('opcache_reset')) {
1370
+            opcache_reset();
1371
+        }
1372
+    }
1373
+
1374
+    /**
1375
+     * Normalize a unicode string
1376
+     *
1377
+     * @param string $value a not normalized string
1378
+     * @return bool|string
1379
+     */
1380
+    public static function normalizeUnicode($value) {
1381
+        if(Normalizer::isNormalized($value)) {
1382
+            return $value;
1383
+        }
1384
+
1385
+        $normalizedValue = Normalizer::normalize($value);
1386
+        if ($normalizedValue === null || $normalizedValue === false) {
1387
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1388
+            return $value;
1389
+        }
1390
+
1391
+        return $normalizedValue;
1392
+    }
1393
+
1394
+    /**
1395
+     * @param boolean|string $file
1396
+     * @return string
1397
+     */
1398
+    public static function basename($file) {
1399
+        $file = rtrim($file, '/');
1400
+        $t = explode('/', $file);
1401
+        return array_pop($t);
1402
+    }
1403
+
1404
+    /**
1405
+     * A human readable string is generated based on version and build number
1406
+     *
1407
+     * @return string
1408
+     */
1409
+    public static function getHumanVersion() {
1410
+        $version = OC_Util::getVersionString();
1411
+        $build = OC_Util::getBuild();
1412
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1413
+            $version .= ' Build:' . $build;
1414
+        }
1415
+        return $version;
1416
+    }
1417
+
1418
+    /**
1419
+     * Returns whether the given file name is valid
1420
+     *
1421
+     * @param string $file file name to check
1422
+     * @return bool true if the file name is valid, false otherwise
1423
+     * @deprecated use \OC\Files\View::verifyPath()
1424
+     */
1425
+    public static function isValidFileName($file) {
1426
+        $trimmed = trim($file);
1427
+        if ($trimmed === '') {
1428
+            return false;
1429
+        }
1430
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1431
+            return false;
1432
+        }
1433
+
1434
+        // detect part files
1435
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1436
+            return false;
1437
+        }
1438
+
1439
+        foreach (str_split($trimmed) as $char) {
1440
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1441
+                return false;
1442
+            }
1443
+        }
1444
+        return true;
1445
+    }
1446
+
1447
+    /**
1448
+     * Check whether the instance needs to perform an upgrade,
1449
+     * either when the core version is higher or any app requires
1450
+     * an upgrade.
1451
+     *
1452
+     * @param \OC\SystemConfig $config
1453
+     * @return bool whether the core or any app needs an upgrade
1454
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1455
+     */
1456
+    public static function needUpgrade(\OC\SystemConfig $config) {
1457
+        if ($config->getValue('installed', false)) {
1458
+            $installedVersion = $config->getValue('version', '0.0.0');
1459
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1460
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1461
+            if ($versionDiff > 0) {
1462
+                return true;
1463
+            } else if ($config->getValue('debug', false) && $versionDiff < 0) {
1464
+                // downgrade with debug
1465
+                $installedMajor = explode('.', $installedVersion);
1466
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1467
+                $currentMajor = explode('.', $currentVersion);
1468
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1469
+                if ($installedMajor === $currentMajor) {
1470
+                    // Same major, allow downgrade for developers
1471
+                    return true;
1472
+                } else {
1473
+                    // downgrade attempt, throw exception
1474
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1475
+                }
1476
+            } else if ($versionDiff < 0) {
1477
+                // downgrade attempt, throw exception
1478
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1479
+            }
1480
+
1481
+            // also check for upgrades for apps (independently from the user)
1482
+            $apps = \OC_App::getEnabledApps(false, true);
1483
+            $shouldUpgrade = false;
1484
+            foreach ($apps as $app) {
1485
+                if (\OC_App::shouldUpgrade($app)) {
1486
+                    $shouldUpgrade = true;
1487
+                    break;
1488
+                }
1489
+            }
1490
+            return $shouldUpgrade;
1491
+        } else {
1492
+            return false;
1493
+        }
1494
+    }
1495 1495
 
1496 1496
 }
Please login to merge, or discard this patch.
Spacing   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 
77 77
 	private static function initLocalStorageRootFS() {
78 78
 		// mount local file backend as root
79
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
79
+		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT."/data");
80 80
 		//first set up the local "root" storage
81 81
 		\OC\Files\Filesystem::initMountManager();
82 82
 		if (!self::$rootMounted) {
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
 		\OC\Files\Filesystem::initMountManager();
195 195
 
196 196
 		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
197
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
197
+		\OC\Files\Filesystem::addStorageWrapper('mount_options', function($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
198 198
 			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
199 199
 				/** @var \OC\Files\Storage\Common $storage */
200 200
 				$storage->setMountOptions($mount->getOptions());
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 			return $storage;
203 203
 		});
204 204
 
205
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
205
+		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
206 206
 			if (!$mount->getOption('enable_sharing', true)) {
207 207
 				return new \OC\Files\Storage\Wrapper\PermissionsMask([
208 208
 					'storage' => $storage,
@@ -213,21 +213,21 @@  discard block
 block discarded – undo
213 213
 		});
214 214
 
215 215
 		// install storage availability wrapper, before most other wrappers
216
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, $storage) {
216
+		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function($mountPoint, $storage) {
217 217
 			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
218 218
 				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
219 219
 			}
220 220
 			return $storage;
221 221
 		});
222 222
 
223
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
223
+		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
224 224
 			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
225 225
 				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
226 226
 			}
227 227
 			return $storage;
228 228
 		});
229 229
 
230
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
230
+		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function($mountPoint, $storage) {
231 231
 			// set up quota for home storages, even for other users
232 232
 			// which can happen when using sharing
233 233
 
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
 		//if we aren't logged in, there is no use to set up the filesystem
275 275
 		if ($user != "") {
276 276
 
277
-			$userDir = '/' . $user . '/files';
277
+			$userDir = '/'.$user.'/files';
278 278
 
279 279
 			//jail the user into his "home" directory
280 280
 			\OC\Files\Filesystem::init($user, $userDir);
@@ -353,7 +353,7 @@  discard block
 block discarded – undo
353 353
 			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
354 354
 		}
355 355
 		$userQuota = $user->getQuota();
356
-		if($userQuota === 'none') {
356
+		if ($userQuota === 'none') {
357 357
 			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
358 358
 		}
359 359
 		return OC_Helper::computerFileSize($userQuota);
@@ -368,15 +368,15 @@  discard block
 block discarded – undo
368 368
 	 */
369 369
 	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
370 370
 
371
-		$skeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
371
+		$skeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT.'/core/skeleton');
372 372
 		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
373 373
 
374 374
 		if ($instanceId === null) {
375 375
 			throw new \RuntimeException('no instance id!');
376 376
 		}
377
-		$appdata = 'appdata_' . $instanceId;
377
+		$appdata = 'appdata_'.$instanceId;
378 378
 		if ($userId === $appdata) {
379
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
379
+			throw new \RuntimeException('username is reserved name: '.$appdata);
380 380
 		}
381 381
 
382 382
 		if (!empty($skeletonDirectory)) {
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
 
404 404
 		// Verify if folder exists
405 405
 		$dir = opendir($source);
406
-		if($dir === false) {
406
+		if ($dir === false) {
407 407
 			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
408 408
 			return;
409 409
 		}
@@ -411,14 +411,14 @@  discard block
 block discarded – undo
411 411
 		// Copy the files
412 412
 		while (false !== ($file = readdir($dir))) {
413 413
 			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
414
-				if (is_dir($source . '/' . $file)) {
414
+				if (is_dir($source.'/'.$file)) {
415 415
 					$child = $target->newFolder($file);
416
-					self::copyr($source . '/' . $file, $child);
416
+					self::copyr($source.'/'.$file, $child);
417 417
 				} else {
418 418
 					$child = $target->newFile($file);
419
-					$sourceStream = fopen($source . '/' . $file, 'r');
420
-					if($sourceStream === false) {
421
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
419
+					$sourceStream = fopen($source.'/'.$file, 'r');
420
+					if ($sourceStream === false) {
421
+						$logger->error(sprintf('Could not fopen "%s"', $source.'/'.$file), ['app' => 'core']);
422 422
 						closedir($dir);
423 423
 						return;
424 424
 					}
@@ -493,8 +493,8 @@  discard block
 block discarded – undo
493 493
 			return;
494 494
 		}
495 495
 
496
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
497
-		require OC::$SERVERROOT . '/version.php';
496
+		$timestamp = filemtime(OC::$SERVERROOT.'/version.php');
497
+		require OC::$SERVERROOT.'/version.php';
498 498
 		/** @var $timestamp int */
499 499
 		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
500 500
 		/** @var $OC_Version string */
@@ -541,7 +541,7 @@  discard block
 block discarded – undo
541 541
 
542 542
 		// core js files need separate handling
543 543
 		if ($application !== 'core' && $file !== null) {
544
-			self::addTranslations ( $application );
544
+			self::addTranslations($application);
545 545
 		}
546 546
 		self::addExternalResource($application, $prepend, $path, "script");
547 547
 	}
@@ -618,7 +618,7 @@  discard block
 block discarded – undo
618 618
 		if ($type === "style") {
619 619
 			if (!in_array($path, self::$styles)) {
620 620
 				if ($prepend === true) {
621
-					array_unshift ( self::$styles, $path );
621
+					array_unshift(self::$styles, $path);
622 622
 				} else {
623 623
 					self::$styles[] = $path;
624 624
 				}
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
 		} elseif ($type === "script") {
627 627
 			if (!in_array($path, self::$scripts)) {
628 628
 				if ($prepend === true) {
629
-					array_unshift ( self::$scripts, $path );
629
+					array_unshift(self::$scripts, $path);
630 630
 				} else {
631 631
 					self::$scripts [] = $path;
632 632
 				}
@@ -642,7 +642,7 @@  discard block
 block discarded – undo
642 642
 	 * @param array $attributes array of attributes for the element
643 643
 	 * @param string $text the text content for the element
644 644
 	 */
645
-	public static function addHeader($tag, $attributes, $text=null) {
645
+	public static function addHeader($tag, $attributes, $text = null) {
646 646
 		self::$headers[] = array(
647 647
 			'tag' => $tag,
648 648
 			'attributes' => $attributes,
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
 	public static function checkServer(\OC\SystemConfig $config) {
683 683
 		$l = \OC::$server->getL10N('lib');
684 684
 		$errors = array();
685
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
685
+		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT.'/data');
686 686
 
687 687
 		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
688 688
 			// this check needs to be done every time
@@ -710,7 +710,7 @@  discard block
 block discarded – undo
710 710
 		}
711 711
 
712 712
 		// Check if config folder is writable.
713
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
713
+		if (!OC_Helper::isReadOnlyConfigEnabled()) {
714 714
 			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
715 715
 				$errors[] = array(
716 716
 					'error' => $l->t('Cannot write into "config" directory'),
@@ -850,15 +850,15 @@  discard block
 block discarded – undo
850 850
 			}
851 851
 		}
852 852
 
853
-		foreach($missingDependencies as $missingDependency) {
853
+		foreach ($missingDependencies as $missingDependency) {
854 854
 			$errors[] = array(
855 855
 				'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
856 856
 				'hint' => $moduleHint
857 857
 			);
858 858
 			$webServerRestart = true;
859 859
 		}
860
-		foreach($invalidIniSettings as $setting) {
861
-			if(is_bool($setting[1])) {
860
+		foreach ($invalidIniSettings as $setting) {
861
+			if (is_bool($setting[1])) {
862 862
 				$setting[1] = ($setting[1]) ? 'on' : 'off';
863 863
 			}
864 864
 			$errors[] = [
@@ -876,7 +876,7 @@  discard block
 block discarded – undo
876 876
 		 * TODO: Should probably be implemented in the above generic dependency
877 877
 		 *       check somehow in the long-term.
878 878
 		 */
879
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
879
+		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
880 880
 			$iniWrapper->getBool('mbstring.func_overload') === true) {
881 881
 			$errors[] = array(
882 882
 				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
@@ -884,16 +884,16 @@  discard block
 block discarded – undo
884 884
 			);
885 885
 		}
886 886
 
887
-		if(function_exists('xml_parser_create') &&
888
-			LIBXML_LOADED_VERSION < 20700 ) {
887
+		if (function_exists('xml_parser_create') &&
888
+			LIBXML_LOADED_VERSION < 20700) {
889 889
 			$version = LIBXML_LOADED_VERSION;
890
-			$major = floor($version/10000);
890
+			$major = floor($version / 10000);
891 891
 			$version -= ($major * 10000);
892
-			$minor = floor($version/100);
892
+			$minor = floor($version / 100);
893 893
 			$version -= ($minor * 100);
894 894
 			$patch = $version;
895 895
 			$errors[] = array(
896
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
896
+				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major.'.'.$minor.'.'.$patch]),
897 897
 				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
898 898
 			);
899 899
 		}
@@ -994,10 +994,10 @@  discard block
 block discarded – undo
994 994
 				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
995 995
 			];
996 996
 		}
997
-		if (!file_exists($dataDirectory . '/.ocdata')) {
997
+		if (!file_exists($dataDirectory.'/.ocdata')) {
998 998
 			$errors[] = [
999 999
 				'error' => $l->t('Your data directory is invalid'),
1000
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1000
+				'hint' => $l->t('Ensure there is a file called ".ocdata"'.
1001 1001
 					' in the root of the data directory.')
1002 1002
 			];
1003 1003
 		}
@@ -1013,7 +1013,7 @@  discard block
 block discarded – undo
1013 1013
 	public static function checkLoggedIn() {
1014 1014
 		// Check if we are a user
1015 1015
 		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1016
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1016
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute(
1017 1017
 						'core.login.showLoginForm',
1018 1018
 						[
1019 1019
 							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
@@ -1024,7 +1024,7 @@  discard block
 block discarded – undo
1024 1024
 		}
1025 1025
 		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1026 1026
 		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1027
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1027
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1028 1028
 			exit();
1029 1029
 		}
1030 1030
 	}
@@ -1037,7 +1037,7 @@  discard block
 block discarded – undo
1037 1037
 	public static function checkAdminUser() {
1038 1038
 		OC_Util::checkLoggedIn();
1039 1039
 		if (!OC_User::isAdminUser(OC_User::getUser())) {
1040
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1040
+			header('Location: '.\OCP\Util::linkToAbsolute('', 'index.php'));
1041 1041
 			exit();
1042 1042
 		}
1043 1043
 	}
@@ -1051,12 +1051,12 @@  discard block
 block discarded – undo
1051 1051
 		OC_Util::checkLoggedIn();
1052 1052
 		$userObject = \OC::$server->getUserSession()->getUser();
1053 1053
 		$isSubAdmin = false;
1054
-		if($userObject !== null) {
1054
+		if ($userObject !== null) {
1055 1055
 			$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1056 1056
 		}
1057 1057
 
1058 1058
 		if (!$isSubAdmin) {
1059
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1059
+			header('Location: '.\OCP\Util::linkToAbsolute('', 'index.php'));
1060 1060
 			exit();
1061 1061
 		}
1062 1062
 		return true;
@@ -1092,10 +1092,10 @@  discard block
 block discarded – undo
1092 1092
 					}
1093 1093
 				}
1094 1094
 
1095
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1096
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1095
+				if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1096
+					$location = $urlGenerator->getAbsoluteURL('/apps/'.$appId.'/');
1097 1097
 				} else {
1098
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1098
+					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/'.$appId.'/');
1099 1099
 				}
1100 1100
 			}
1101 1101
 		}
@@ -1109,7 +1109,7 @@  discard block
 block discarded – undo
1109 1109
 	 */
1110 1110
 	public static function redirectToDefaultPage() {
1111 1111
 		$location = self::getDefaultPageUrl();
1112
-		header('Location: ' . $location);
1112
+		header('Location: '.$location);
1113 1113
 		exit();
1114 1114
 	}
1115 1115
 
@@ -1122,7 +1122,7 @@  discard block
 block discarded – undo
1122 1122
 		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1123 1123
 		if (is_null($id)) {
1124 1124
 			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1125
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1125
+			$id = 'oc'.\OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1126 1126
 			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1127 1127
 		}
1128 1128
 		return $id;
@@ -1144,7 +1144,7 @@  discard block
 block discarded – undo
1144 1144
 			}, $value);
1145 1145
 		} else {
1146 1146
 			// Specify encoding for PHP<5.4
1147
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1147
+			$value = htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
1148 1148
 		}
1149 1149
 		return $value;
1150 1150
 	}
@@ -1177,7 +1177,7 @@  discard block
 block discarded – undo
1177 1177
 		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1178 1178
 
1179 1179
 		// creating a test file
1180
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1180
+		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$fileName;
1181 1181
 
1182 1182
 		if (file_exists($testFile)) {// already running this test, possible recursive call
1183 1183
 			return false;
@@ -1186,7 +1186,7 @@  discard block
 block discarded – undo
1186 1186
 		$fp = @fopen($testFile, 'w');
1187 1187
 		if (!$fp) {
1188 1188
 			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1189
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1189
+				'Make sure it is possible for the webserver to write to '.$testFile);
1190 1190
 		}
1191 1191
 		fwrite($fp, $testContent);
1192 1192
 		fclose($fp);
@@ -1213,10 +1213,10 @@  discard block
 block discarded – undo
1213 1213
 		}
1214 1214
 
1215 1215
 		$fileName = '/htaccesstest.txt';
1216
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1216
+		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$fileName;
1217 1217
 
1218 1218
 		// accessing the file via http
1219
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1219
+		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT.'/data'.$fileName);
1220 1220
 		try {
1221 1221
 			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1222 1222
 		} catch (\Exception $e) {
@@ -1307,7 +1307,7 @@  discard block
 block discarded – undo
1307 1307
 		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1308 1308
 
1309 1309
 		if ($theme === '') {
1310
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1310
+			if (is_dir(OC::$SERVERROOT.'/themes/default')) {
1311 1311
 				$theme = 'default';
1312 1312
 			}
1313 1313
 		}
@@ -1378,13 +1378,13 @@  discard block
 block discarded – undo
1378 1378
 	 * @return bool|string
1379 1379
 	 */
1380 1380
 	public static function normalizeUnicode($value) {
1381
-		if(Normalizer::isNormalized($value)) {
1381
+		if (Normalizer::isNormalized($value)) {
1382 1382
 			return $value;
1383 1383
 		}
1384 1384
 
1385 1385
 		$normalizedValue = Normalizer::normalize($value);
1386 1386
 		if ($normalizedValue === null || $normalizedValue === false) {
1387
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1387
+			\OC::$server->getLogger()->warning('normalizing failed for "'.$value.'"', ['app' => 'core']);
1388 1388
 			return $value;
1389 1389
 		}
1390 1390
 
@@ -1410,7 +1410,7 @@  discard block
 block discarded – undo
1410 1410
 		$version = OC_Util::getVersionString();
1411 1411
 		$build = OC_Util::getBuild();
1412 1412
 		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1413
-			$version .= ' Build:' . $build;
1413
+			$version .= ' Build:'.$build;
1414 1414
 		}
1415 1415
 		return $version;
1416 1416
 	}
@@ -1432,7 +1432,7 @@  discard block
 block discarded – undo
1432 1432
 		}
1433 1433
 
1434 1434
 		// detect part files
1435
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1435
+		if (preg_match('/'.\OCP\Files\FileInfo::BLACKLIST_FILES_REGEX.'/', $trimmed) !== 0) {
1436 1436
 			return false;
1437 1437
 		}
1438 1438
 
@@ -1463,19 +1463,19 @@  discard block
 block discarded – undo
1463 1463
 			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1464 1464
 				// downgrade with debug
1465 1465
 				$installedMajor = explode('.', $installedVersion);
1466
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1466
+				$installedMajor = $installedMajor[0].'.'.$installedMajor[1];
1467 1467
 				$currentMajor = explode('.', $currentVersion);
1468
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1468
+				$currentMajor = $currentMajor[0].'.'.$currentMajor[1];
1469 1469
 				if ($installedMajor === $currentMajor) {
1470 1470
 					// Same major, allow downgrade for developers
1471 1471
 					return true;
1472 1472
 				} else {
1473 1473
 					// downgrade attempt, throw exception
1474
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1474
+					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
1475 1475
 				}
1476 1476
 			} else if ($versionDiff < 0) {
1477 1477
 				// downgrade attempt, throw exception
1478
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1478
+				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
1479 1479
 			}
1480 1480
 
1481 1481
 			// also check for upgrades for apps (independently from the user)
Please login to merge, or discard this patch.
lib/private/Preview/Office.php 2 patches
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -26,80 +26,80 @@
 block discarded – undo
26 26
 namespace OC\Preview;
27 27
 
28 28
 abstract class Office extends Provider {
29
-	private $cmd;
29
+    private $cmd;
30 30
 
31
-	/**
32
-	 * {@inheritDoc}
33
-	 */
34
-	public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
35
-		$this->initCmd();
36
-		if (is_null($this->cmd)) {
37
-			return false;
38
-		}
31
+    /**
32
+     * {@inheritDoc}
33
+     */
34
+    public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
35
+        $this->initCmd();
36
+        if (is_null($this->cmd)) {
37
+            return false;
38
+        }
39 39
 
40
-		$absPath = $fileview->toTmpFile($path);
40
+        $absPath = $fileview->toTmpFile($path);
41 41
 
42
-		$tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
42
+        $tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
43 43
 
44
-		$defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to pdf --outdir ';
45
-		$clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
44
+        $defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to pdf --outdir ';
45
+        $clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
46 46
 
47
-		$exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
47
+        $exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
48 48
 
49
-		shell_exec($exec);
49
+        shell_exec($exec);
50 50
 
51
-		//create imagick object from pdf
52
-		$pdfPreview = null;
53
-		try {
54
-			list($dirname, , , $filename) = array_values(pathinfo($absPath));
55
-			$pdfPreview = $dirname . '/' . $filename . '.pdf';
51
+        //create imagick object from pdf
52
+        $pdfPreview = null;
53
+        try {
54
+            list($dirname, , , $filename) = array_values(pathinfo($absPath));
55
+            $pdfPreview = $dirname . '/' . $filename . '.pdf';
56 56
 
57
-			$pdf = new \imagick($pdfPreview . '[0]');
58
-			$pdf->setImageFormat('jpg');
59
-		} catch (\Exception $e) {
60
-			unlink($absPath);
61
-			unlink($pdfPreview);
62
-			\OCP\Util::writeLog('core', $e->getMessage(), \OCP\Util::ERROR);
63
-			return false;
64
-		}
57
+            $pdf = new \imagick($pdfPreview . '[0]');
58
+            $pdf->setImageFormat('jpg');
59
+        } catch (\Exception $e) {
60
+            unlink($absPath);
61
+            unlink($pdfPreview);
62
+            \OCP\Util::writeLog('core', $e->getMessage(), \OCP\Util::ERROR);
63
+            return false;
64
+        }
65 65
 
66
-		$image = new \OC_Image();
67
-		$image->loadFromData($pdf);
66
+        $image = new \OC_Image();
67
+        $image->loadFromData($pdf);
68 68
 
69
-		unlink($absPath);
70
-		unlink($pdfPreview);
69
+        unlink($absPath);
70
+        unlink($pdfPreview);
71 71
 
72
-		if ($image->valid()) {
73
-			$image->scaleDownToFit($maxX, $maxY);
72
+        if ($image->valid()) {
73
+            $image->scaleDownToFit($maxX, $maxY);
74 74
 
75
-			return $image;
76
-		}
77
-		return false;
75
+            return $image;
76
+        }
77
+        return false;
78 78
 
79
-	}
79
+    }
80 80
 
81
-	private function initCmd() {
82
-		$cmd = '';
81
+    private function initCmd() {
82
+        $cmd = '';
83 83
 
84
-		$libreOfficePath = \OC::$server->getConfig()->getSystemValue('preview_libreoffice_path', null);
85
-		if (is_string($libreOfficePath)) {
86
-			$cmd = $libreOfficePath;
87
-		}
84
+        $libreOfficePath = \OC::$server->getConfig()->getSystemValue('preview_libreoffice_path', null);
85
+        if (is_string($libreOfficePath)) {
86
+            $cmd = $libreOfficePath;
87
+        }
88 88
 
89
-		$whichLibreOffice = shell_exec('command -v libreoffice');
90
-		if ($cmd === '' && !empty($whichLibreOffice)) {
91
-			$cmd = 'libreoffice';
92
-		}
89
+        $whichLibreOffice = shell_exec('command -v libreoffice');
90
+        if ($cmd === '' && !empty($whichLibreOffice)) {
91
+            $cmd = 'libreoffice';
92
+        }
93 93
 
94
-		$whichOpenOffice = shell_exec('command -v openoffice');
95
-		if ($cmd === '' && !empty($whichOpenOffice)) {
96
-			$cmd = 'openoffice';
97
-		}
94
+        $whichOpenOffice = shell_exec('command -v openoffice');
95
+        if ($cmd === '' && !empty($whichOpenOffice)) {
96
+            $cmd = 'openoffice';
97
+        }
98 98
 
99
-		if ($cmd === '') {
100
-			$cmd = null;
101
-		}
99
+        if ($cmd === '') {
100
+            $cmd = null;
101
+        }
102 102
 
103
-		$this->cmd = $cmd;
104
-	}
103
+        $this->cmd = $cmd;
104
+    }
105 105
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -41,20 +41,20 @@
 block discarded – undo
41 41
 
42 42
 		$tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
43 43
 
44
-		$defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to pdf --outdir ';
44
+		$defaultParameters = ' -env:UserInstallation=file://'.escapeshellarg($tmpDir.'/owncloud-'.\OC_Util::getInstanceId().'/').' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to pdf --outdir ';
45 45
 		$clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
46 46
 
47
-		$exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
47
+		$exec = $this->cmd.$clParameters.escapeshellarg($tmpDir).' '.escapeshellarg($absPath);
48 48
 
49 49
 		shell_exec($exec);
50 50
 
51 51
 		//create imagick object from pdf
52 52
 		$pdfPreview = null;
53 53
 		try {
54
-			list($dirname, , , $filename) = array_values(pathinfo($absPath));
55
-			$pdfPreview = $dirname . '/' . $filename . '.pdf';
54
+			list($dirname,,, $filename) = array_values(pathinfo($absPath));
55
+			$pdfPreview = $dirname.'/'.$filename.'.pdf';
56 56
 
57
-			$pdf = new \imagick($pdfPreview . '[0]');
57
+			$pdf = new \imagick($pdfPreview.'[0]');
58 58
 			$pdf->setImageFormat('jpg');
59 59
 		} catch (\Exception $e) {
60 60
 			unlink($absPath);
Please login to merge, or discard this patch.