Passed
Push — master ( 23e8ae...e8872f )
by Robin
16:16 queued 12s
created
lib/public/Files/Config/ICachedMountInfo.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -31,57 +31,57 @@
 block discarded – undo
31 31
  * @since 9.0.0
32 32
  */
33 33
 interface ICachedMountInfo {
34
-	/**
35
-	 * @return IUser
36
-	 * @since 9.0.0
37
-	 */
38
-	public function getUser(): IUser;
34
+    /**
35
+     * @return IUser
36
+     * @since 9.0.0
37
+     */
38
+    public function getUser(): IUser;
39 39
 
40
-	/**
41
-	 * @return int the numeric storage id of the mount
42
-	 * @since 9.0.0
43
-	 */
44
-	public function getStorageId(): int;
40
+    /**
41
+     * @return int the numeric storage id of the mount
42
+     * @since 9.0.0
43
+     */
44
+    public function getStorageId(): int;
45 45
 
46
-	/**
47
-	 * @return int the fileid of the root of the mount
48
-	 * @since 9.0.0
49
-	 */
50
-	public function getRootId(): int;
46
+    /**
47
+     * @return int the fileid of the root of the mount
48
+     * @since 9.0.0
49
+     */
50
+    public function getRootId(): int;
51 51
 
52
-	/**
53
-	 * @return Node|null the root node of the mount
54
-	 * @since 9.0.0
55
-	 */
56
-	public function getMountPointNode(): ?Node;
52
+    /**
53
+     * @return Node|null the root node of the mount
54
+     * @since 9.0.0
55
+     */
56
+    public function getMountPointNode(): ?Node;
57 57
 
58
-	/**
59
-	 * @return string the mount point of the mount for the user
60
-	 * @since 9.0.0
61
-	 */
62
-	public function getMountPoint(): string;
58
+    /**
59
+     * @return string the mount point of the mount for the user
60
+     * @since 9.0.0
61
+     */
62
+    public function getMountPoint(): string;
63 63
 
64
-	/**
65
-	 * Get the id of the configured mount
66
-	 *
67
-	 * @return int|null mount id or null if not applicable
68
-	 * @since 9.1.0
69
-	 */
70
-	public function getMountId(): ?int;
64
+    /**
65
+     * Get the id of the configured mount
66
+     *
67
+     * @return int|null mount id or null if not applicable
68
+     * @since 9.1.0
69
+     */
70
+    public function getMountId(): ?int;
71 71
 
72
-	/**
73
-	 * Get the internal path (within the storage) of the root of the mount
74
-	 *
75
-	 * @return string
76
-	 * @since 11.0.0
77
-	 */
78
-	public function getRootInternalPath(): string;
72
+    /**
73
+     * Get the internal path (within the storage) of the root of the mount
74
+     *
75
+     * @return string
76
+     * @since 11.0.0
77
+     */
78
+    public function getRootInternalPath(): string;
79 79
 
80
-	/**
81
-	 * Get the class of the mount provider that this mount originates from
82
-	 *
83
-	 * @return string
84
-	 * @since 24.0.0
85
-	 */
86
-	public function getMountProvider(): string;
80
+    /**
81
+     * Get the class of the mount provider that this mount originates from
82
+     *
83
+     * @return string
84
+     * @since 24.0.0
85
+     */
86
+    public function getMountProvider(): string;
87 87
 }
Please login to merge, or discard this patch.
lib/public/Files/Config/ICachedMountFileInfo.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -28,17 +28,17 @@
 block discarded – undo
28 28
  * @since 13.0.0
29 29
  */
30 30
 interface ICachedMountFileInfo extends ICachedMountInfo {
31
-	/**
32
-	 * Return the path for the file within the cached mount
33
-	 *
34
-	 * @return string
35
-	 * @since 13.0.0
36
-	 */
37
-	public function getInternalPath(): string;
31
+    /**
32
+     * Return the path for the file within the cached mount
33
+     *
34
+     * @return string
35
+     * @since 13.0.0
36
+     */
37
+    public function getInternalPath(): string;
38 38
 
39
-	/**
40
-	 * @return string
41
-	 * @since 13.0.0
42
-	 */
43
-	public function getPath(): string;
39
+    /**
40
+     * @return string
41
+     * @since 13.0.0
42
+     */
43
+    public function getPath(): string;
44 44
 }
Please login to merge, or discard this patch.
lib/public/Files/Mount/IMountManager.php 1 patch
Indentation   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -34,77 +34,77 @@
 block discarded – undo
34 34
  */
35 35
 interface IMountManager {
36 36
 
37
-	/**
38
-	 * Add a new mount
39
-	 *
40
-	 * @param IMountPoint $mount
41
-	 * @since 8.2.0
42
-	 */
43
-	public function addMount(IMountPoint $mount);
37
+    /**
38
+     * Add a new mount
39
+     *
40
+     * @param IMountPoint $mount
41
+     * @since 8.2.0
42
+     */
43
+    public function addMount(IMountPoint $mount);
44 44
 
45
-	/**
46
-	 * Remove a mount
47
-	 *
48
-	 * @param string $mountPoint
49
-	 * @since 8.2.0
50
-	 */
51
-	public function removeMount(string $mountPoint);
45
+    /**
46
+     * Remove a mount
47
+     *
48
+     * @param string $mountPoint
49
+     * @since 8.2.0
50
+     */
51
+    public function removeMount(string $mountPoint);
52 52
 
53
-	/**
54
-	 * Change the location of a mount
55
-	 *
56
-	 * @param string $mountPoint
57
-	 * @param string $target
58
-	 * @since 8.2.0
59
-	 */
60
-	public function moveMount(string $mountPoint, string $target);
53
+    /**
54
+     * Change the location of a mount
55
+     *
56
+     * @param string $mountPoint
57
+     * @param string $target
58
+     * @since 8.2.0
59
+     */
60
+    public function moveMount(string $mountPoint, string $target);
61 61
 
62
-	/**
63
-	 * Find the mount for $path
64
-	 *
65
-	 * @param string $path
66
-	 * @return IMountPoint
67
-	 * @since 8.2.0
68
-	 */
69
-	public function find(string $path): ?IMountPoint;
62
+    /**
63
+     * Find the mount for $path
64
+     *
65
+     * @param string $path
66
+     * @return IMountPoint
67
+     * @since 8.2.0
68
+     */
69
+    public function find(string $path): ?IMountPoint;
70 70
 
71
-	/**
72
-	 * Find all mounts in $path
73
-	 *
74
-	 * @param string $path
75
-	 * @return IMountPoint[]
76
-	 * @since 8.2.0
77
-	 */
78
-	public function findIn(string $path): array;
71
+    /**
72
+     * Find all mounts in $path
73
+     *
74
+     * @param string $path
75
+     * @return IMountPoint[]
76
+     * @since 8.2.0
77
+     */
78
+    public function findIn(string $path): array;
79 79
 
80
-	/**
81
-	 * Remove all registered mounts
82
-	 *
83
-	 * @since 8.2.0
84
-	 */
85
-	public function clear();
80
+    /**
81
+     * Remove all registered mounts
82
+     *
83
+     * @since 8.2.0
84
+     */
85
+    public function clear();
86 86
 
87
-	/**
88
-	 * Find mounts by storage id
89
-	 *
90
-	 * @param string $id
91
-	 * @return IMountPoint[]
92
-	 * @since 8.2.0
93
-	 */
94
-	public function findByStorageId(string $id): array;
87
+    /**
88
+     * Find mounts by storage id
89
+     *
90
+     * @param string $id
91
+     * @return IMountPoint[]
92
+     * @since 8.2.0
93
+     */
94
+    public function findByStorageId(string $id): array;
95 95
 
96
-	/**
97
-	 * @return IMountPoint[]
98
-	 * @since 8.2.0
99
-	 */
100
-	public function getAll(): array;
96
+    /**
97
+     * @return IMountPoint[]
98
+     * @since 8.2.0
99
+     */
100
+    public function getAll(): array;
101 101
 
102
-	/**
103
-	 * Find mounts by numeric storage id
104
-	 *
105
-	 * @param int $id
106
-	 * @return IMountPoint[]
107
-	 * @since 8.2.0
108
-	 */
109
-	public function findByNumericId(int $id): array;
102
+    /**
103
+     * Find mounts by numeric storage id
104
+     *
105
+     * @param int $id
106
+     * @return IMountPoint[]
107
+     * @since 8.2.0
108
+     */
109
+    public function findByNumericId(int $id): array;
110 110
 }
Please login to merge, or discard this patch.
lib/private/Cache/CappedMemoryCache.php 1 patch
Indentation   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -30,89 +30,89 @@
 block discarded – undo
30 30
  * @template T
31 31
  */
32 32
 class CappedMemoryCache implements ICache, \ArrayAccess {
33
-	private $capacity;
34
-	/** @var T[] */
35
-	private $cache = [];
33
+    private $capacity;
34
+    /** @var T[] */
35
+    private $cache = [];
36 36
 
37
-	public function __construct($capacity = 512) {
38
-		$this->capacity = $capacity;
39
-	}
37
+    public function __construct($capacity = 512) {
38
+        $this->capacity = $capacity;
39
+    }
40 40
 
41
-	public function hasKey($key): bool {
42
-		return isset($this->cache[$key]);
43
-	}
41
+    public function hasKey($key): bool {
42
+        return isset($this->cache[$key]);
43
+    }
44 44
 
45
-	/**
46
-	 * @return ?T
47
-	 */
48
-	public function get($key) {
49
-		return $this->cache[$key] ?? null;
50
-	}
45
+    /**
46
+     * @return ?T
47
+     */
48
+    public function get($key) {
49
+        return $this->cache[$key] ?? null;
50
+    }
51 51
 
52
-	/**
53
-	 * @param string $key
54
-	 * @param T $value
55
-	 * @param int $ttl
56
-	 * @return bool
57
-	 */
58
-	public function set($key, $value, $ttl = 0): bool {
59
-		if (is_null($key)) {
60
-			$this->cache[] = $value;
61
-		} else {
62
-			$this->cache[$key] = $value;
63
-		}
64
-		$this->garbageCollect();
65
-		return true;
66
-	}
52
+    /**
53
+     * @param string $key
54
+     * @param T $value
55
+     * @param int $ttl
56
+     * @return bool
57
+     */
58
+    public function set($key, $value, $ttl = 0): bool {
59
+        if (is_null($key)) {
60
+            $this->cache[] = $value;
61
+        } else {
62
+            $this->cache[$key] = $value;
63
+        }
64
+        $this->garbageCollect();
65
+        return true;
66
+    }
67 67
 
68
-	public function remove($key) {
69
-		unset($this->cache[$key]);
70
-		return true;
71
-	}
68
+    public function remove($key) {
69
+        unset($this->cache[$key]);
70
+        return true;
71
+    }
72 72
 
73
-	public function clear($prefix = '') {
74
-		$this->cache = [];
75
-		return true;
76
-	}
73
+    public function clear($prefix = '') {
74
+        $this->cache = [];
75
+        return true;
76
+    }
77 77
 
78
-	public function offsetExists($offset): bool {
79
-		return $this->hasKey($offset);
80
-	}
78
+    public function offsetExists($offset): bool {
79
+        return $this->hasKey($offset);
80
+    }
81 81
 
82
-	/**
83
-	 * @return T
84
-	 */
85
-	#[\ReturnTypeWillChange]
86
-	public function &offsetGet($offset) {
87
-		return $this->cache[$offset];
88
-	}
82
+    /**
83
+     * @return T
84
+     */
85
+    #[\ReturnTypeWillChange]
86
+    public function &offsetGet($offset) {
87
+        return $this->cache[$offset];
88
+    }
89 89
 
90
-	/**
91
-	 * @param string $key
92
-	 * @param T $value
93
-	 * @return void
94
-	 */
95
-	public function offsetSet($offset, $value): void {
96
-		$this->set($offset, $value);
97
-	}
90
+    /**
91
+     * @param string $key
92
+     * @param T $value
93
+     * @return void
94
+     */
95
+    public function offsetSet($offset, $value): void {
96
+        $this->set($offset, $value);
97
+    }
98 98
 
99
-	public function offsetUnset($offset): void {
100
-		$this->remove($offset);
101
-	}
99
+    public function offsetUnset($offset): void {
100
+        $this->remove($offset);
101
+    }
102 102
 
103
-	/**
104
-	 * @return T[]
105
-	 */
106
-	public function getData() {
107
-		return $this->cache;
108
-	}
103
+    /**
104
+     * @return T[]
105
+     */
106
+    public function getData() {
107
+        return $this->cache;
108
+    }
109 109
 
110 110
 
111
-	private function garbageCollect() {
112
-		while (count($this->cache) > $this->capacity) {
113
-			reset($this->cache);
114
-			$key = key($this->cache);
115
-			$this->remove($key);
116
-		}
117
-	}
111
+    private function garbageCollect() {
112
+        while (count($this->cache) > $this->capacity) {
113
+            reset($this->cache);
114
+            $key = key($this->cache);
115
+            $this->remove($key);
116
+        }
117
+    }
118 118
 }
Please login to merge, or discard this patch.
lib/private/legacy/OC_Util.php 2 patches
Indentation   +1152 added lines, -1152 removed lines patch added patch discarded remove patch
@@ -76,1159 +76,1159 @@
 block discarded – undo
76 76
 use Psr\Log\LoggerInterface;
77 77
 
78 78
 class OC_Util {
79
-	public static $scripts = [];
80
-	public static $styles = [];
81
-	public static $headers = [];
82
-
83
-	/** @var array Local cache of version.php */
84
-	private static $versionCache = null;
85
-
86
-	protected static function getAppManager() {
87
-		return \OC::$server->getAppManager();
88
-	}
89
-
90
-	/**
91
-	 * Setup the file system
92
-	 *
93
-	 * @param string|null $user
94
-	 * @return boolean
95
-	 * @description configure the initial filesystem based on the configuration
96
-	 * @suppress PhanDeprecatedFunction
97
-	 * @suppress PhanAccessMethodInternal
98
-	 */
99
-	public static function setupFS(?string $user = '') {
100
-		// If we are not forced to load a specific user we load the one that is logged in
101
-		if ($user === '') {
102
-			$userObject = \OC::$server->get(\OCP\IUserSession::class)->getUser();
103
-		} else {
104
-			$userObject = \OC::$server->get(\OCP\IUserManager::class)->get($user);
105
-		}
106
-
107
-		/** @var SetupManager $setupManager */
108
-		$setupManager = \OC::$server->get(SetupManager::class);
109
-
110
-		if ($userObject) {
111
-			$setupManager->setupForUser($userObject);
112
-		} else {
113
-			$setupManager->setupRoot();
114
-		}
115
-		return true;
116
-	}
117
-
118
-	/**
119
-	 * check if a password is required for each public link
120
-	 *
121
-	 * @return boolean
122
-	 * @suppress PhanDeprecatedFunction
123
-	 */
124
-	public static function isPublicLinkPasswordRequired() {
125
-		/** @var IManager $shareManager */
126
-		$shareManager = \OC::$server->get(IManager::class);
127
-		return $shareManager->shareApiLinkEnforcePassword();
128
-	}
129
-
130
-	/**
131
-	 * check if sharing is disabled for the current user
132
-	 * @param IConfig $config
133
-	 * @param IGroupManager $groupManager
134
-	 * @param IUser|null $user
135
-	 * @return bool
136
-	 */
137
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
138
-		/** @var IManager $shareManager */
139
-		$shareManager = \OC::$server->get(IManager::class);
140
-		$userId = $user ? $user->getUID() : null;
141
-		return $shareManager->sharingDisabledForUser($userId);
142
-	}
143
-
144
-	/**
145
-	 * check if share API enforces a default expire date
146
-	 *
147
-	 * @return boolean
148
-	 * @suppress PhanDeprecatedFunction
149
-	 */
150
-	public static function isDefaultExpireDateEnforced() {
151
-		/** @var IManager $shareManager */
152
-		$shareManager = \OC::$server->get(IManager::class);
153
-		return $shareManager->shareApiLinkDefaultExpireDateEnforced();
154
-	}
155
-
156
-	/**
157
-	 * Get the quota of a user
158
-	 *
159
-	 * @param IUser|null $user
160
-	 * @return float Quota bytes
161
-	 */
162
-	public static function getUserQuota(?IUser $user) {
163
-		if (is_null($user)) {
164
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
165
-		}
166
-		$userQuota = $user->getQuota();
167
-		if ($userQuota === 'none') {
168
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
169
-		}
170
-		return OC_Helper::computerFileSize($userQuota);
171
-	}
172
-
173
-	/**
174
-	 * copies the skeleton to the users /files
175
-	 *
176
-	 * @param string $userId
177
-	 * @param \OCP\Files\Folder $userDirectory
178
-	 * @throws \OCP\Files\NotFoundException
179
-	 * @throws \OCP\Files\NotPermittedException
180
-	 * @suppress PhanDeprecatedFunction
181
-	 */
182
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
183
-		/** @var LoggerInterface $logger */
184
-		$logger = \OC::$server->get(LoggerInterface::class);
185
-
186
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
187
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
188
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
189
-
190
-		if (!file_exists($skeletonDirectory)) {
191
-			$dialectStart = strpos($userLang, '_');
192
-			if ($dialectStart !== false) {
193
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
194
-			}
195
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
196
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
197
-			}
198
-			if (!file_exists($skeletonDirectory)) {
199
-				$skeletonDirectory = '';
200
-			}
201
-		}
202
-
203
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
204
-
205
-		if ($instanceId === null) {
206
-			throw new \RuntimeException('no instance id!');
207
-		}
208
-		$appdata = 'appdata_' . $instanceId;
209
-		if ($userId === $appdata) {
210
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
211
-		}
212
-
213
-		if (!empty($skeletonDirectory)) {
214
-			$logger->debug('copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'), ['app' => 'files_skeleton']);
215
-			self::copyr($skeletonDirectory, $userDirectory);
216
-			// update the file cache
217
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
218
-
219
-			/** @var ITemplateManager $templateManager */
220
-			$templateManager = \OC::$server->get(ITemplateManager::class);
221
-			$templateManager->initializeTemplateDirectory(null, $userId);
222
-		}
223
-	}
224
-
225
-	/**
226
-	 * copies a directory recursively by using streams
227
-	 *
228
-	 * @param string $source
229
-	 * @param \OCP\Files\Folder $target
230
-	 * @return void
231
-	 */
232
-	public static function copyr($source, \OCP\Files\Folder $target) {
233
-		$logger = \OC::$server->getLogger();
234
-
235
-		// Verify if folder exists
236
-		$dir = opendir($source);
237
-		if ($dir === false) {
238
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
239
-			return;
240
-		}
241
-
242
-		// Copy the files
243
-		while (false !== ($file = readdir($dir))) {
244
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
245
-				if (is_dir($source . '/' . $file)) {
246
-					$child = $target->newFolder($file);
247
-					self::copyr($source . '/' . $file, $child);
248
-				} else {
249
-					$child = $target->newFile($file);
250
-					$sourceStream = fopen($source . '/' . $file, 'r');
251
-					if ($sourceStream === false) {
252
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
253
-						closedir($dir);
254
-						return;
255
-					}
256
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
257
-				}
258
-			}
259
-		}
260
-		closedir($dir);
261
-	}
262
-
263
-	/**
264
-	 * @return void
265
-	 * @suppress PhanUndeclaredMethod
266
-	 */
267
-	public static function tearDownFS() {
268
-		/** @var SetupManager $setupManager */
269
-		$setupManager = \OC::$server->get(SetupManager::class);
270
-		$setupManager->tearDown();
271
-	}
272
-
273
-	/**
274
-	 * get the current installed version of ownCloud
275
-	 *
276
-	 * @return array
277
-	 */
278
-	public static function getVersion() {
279
-		OC_Util::loadVersion();
280
-		return self::$versionCache['OC_Version'];
281
-	}
282
-
283
-	/**
284
-	 * get the current installed version string of ownCloud
285
-	 *
286
-	 * @return string
287
-	 */
288
-	public static function getVersionString() {
289
-		OC_Util::loadVersion();
290
-		return self::$versionCache['OC_VersionString'];
291
-	}
292
-
293
-	/**
294
-	 * @deprecated the value is of no use anymore
295
-	 * @return string
296
-	 */
297
-	public static function getEditionString() {
298
-		return '';
299
-	}
300
-
301
-	/**
302
-	 * @description get the update channel of the current installed of ownCloud.
303
-	 * @return string
304
-	 */
305
-	public static function getChannel() {
306
-		OC_Util::loadVersion();
307
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
308
-	}
309
-
310
-	/**
311
-	 * @description get the build number of the current installed of ownCloud.
312
-	 * @return string
313
-	 */
314
-	public static function getBuild() {
315
-		OC_Util::loadVersion();
316
-		return self::$versionCache['OC_Build'];
317
-	}
318
-
319
-	/**
320
-	 * @description load the version.php into the session as cache
321
-	 * @suppress PhanUndeclaredVariable
322
-	 */
323
-	private static function loadVersion() {
324
-		if (self::$versionCache !== null) {
325
-			return;
326
-		}
327
-
328
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
329
-		require OC::$SERVERROOT . '/version.php';
330
-		/** @var int $timestamp */
331
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
332
-		/** @var string $OC_Version */
333
-		self::$versionCache['OC_Version'] = $OC_Version;
334
-		/** @var string $OC_VersionString */
335
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
336
-		/** @var string $OC_Build */
337
-		self::$versionCache['OC_Build'] = $OC_Build;
338
-
339
-		/** @var string $OC_Channel */
340
-		self::$versionCache['OC_Channel'] = $OC_Channel;
341
-	}
342
-
343
-	/**
344
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
345
-	 *
346
-	 * @param string $application application to get the files from
347
-	 * @param string $directory directory within this application (css, js, vendor, etc)
348
-	 * @param string $file the file inside of the above folder
349
-	 * @return string the path
350
-	 */
351
-	private static function generatePath($application, $directory, $file) {
352
-		if (is_null($file)) {
353
-			$file = $application;
354
-			$application = "";
355
-		}
356
-		if (!empty($application)) {
357
-			return "$application/$directory/$file";
358
-		} else {
359
-			return "$directory/$file";
360
-		}
361
-	}
362
-
363
-	/**
364
-	 * add a javascript file
365
-	 *
366
-	 * @deprecated 24.0.0 - Use \OCP\Util::addScript
367
-	 *
368
-	 * @param string $application application id
369
-	 * @param string|null $file filename
370
-	 * @param bool $prepend prepend the Script to the beginning of the list
371
-	 * @return void
372
-	 */
373
-	public static function addScript($application, $file = null, $prepend = false) {
374
-		$path = OC_Util::generatePath($application, 'js', $file);
375
-
376
-		// core js files need separate handling
377
-		if ($application !== 'core' && $file !== null) {
378
-			self::addTranslations($application);
379
-		}
380
-		self::addExternalResource($application, $prepend, $path, "script");
381
-	}
382
-
383
-	/**
384
-	 * add a javascript file from the vendor sub folder
385
-	 *
386
-	 * @param string $application application id
387
-	 * @param string|null $file filename
388
-	 * @param bool $prepend prepend the Script to the beginning of the list
389
-	 * @return void
390
-	 */
391
-	public static function addVendorScript($application, $file = null, $prepend = false) {
392
-		$path = OC_Util::generatePath($application, 'vendor', $file);
393
-		self::addExternalResource($application, $prepend, $path, "script");
394
-	}
395
-
396
-	/**
397
-	 * add a translation JS file
398
-	 *
399
-	 * @deprecated 24.0.0
400
-	 *
401
-	 * @param string $application application id
402
-	 * @param string|null $languageCode language code, defaults to the current language
403
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
404
-	 */
405
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
406
-		if (is_null($languageCode)) {
407
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
408
-		}
409
-		if (!empty($application)) {
410
-			$path = "$application/l10n/$languageCode";
411
-		} else {
412
-			$path = "l10n/$languageCode";
413
-		}
414
-		self::addExternalResource($application, $prepend, $path, "script");
415
-	}
416
-
417
-	/**
418
-	 * add a css file
419
-	 *
420
-	 * @param string $application application id
421
-	 * @param string|null $file filename
422
-	 * @param bool $prepend prepend the Style to the beginning of the list
423
-	 * @return void
424
-	 */
425
-	public static function addStyle($application, $file = null, $prepend = false) {
426
-		$path = OC_Util::generatePath($application, 'css', $file);
427
-		self::addExternalResource($application, $prepend, $path, "style");
428
-	}
429
-
430
-	/**
431
-	 * add a css file from the vendor sub folder
432
-	 *
433
-	 * @param string $application application id
434
-	 * @param string|null $file filename
435
-	 * @param bool $prepend prepend the Style to the beginning of the list
436
-	 * @return void
437
-	 */
438
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
439
-		$path = OC_Util::generatePath($application, 'vendor', $file);
440
-		self::addExternalResource($application, $prepend, $path, "style");
441
-	}
442
-
443
-	/**
444
-	 * add an external resource css/js file
445
-	 *
446
-	 * @param string $application application id
447
-	 * @param bool $prepend prepend the file to the beginning of the list
448
-	 * @param string $path
449
-	 * @param string $type (script or style)
450
-	 * @return void
451
-	 */
452
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
453
-		if ($type === "style") {
454
-			if (!in_array($path, self::$styles)) {
455
-				if ($prepend === true) {
456
-					array_unshift(self::$styles, $path);
457
-				} else {
458
-					self::$styles[] = $path;
459
-				}
460
-			}
461
-		} elseif ($type === "script") {
462
-			if (!in_array($path, self::$scripts)) {
463
-				if ($prepend === true) {
464
-					array_unshift(self::$scripts, $path);
465
-				} else {
466
-					self::$scripts [] = $path;
467
-				}
468
-			}
469
-		}
470
-	}
471
-
472
-	/**
473
-	 * Add a custom element to the header
474
-	 * If $text is null then the element will be written as empty element.
475
-	 * So use "" to get a closing tag.
476
-	 * @param string $tag tag name of the element
477
-	 * @param array $attributes array of attributes for the element
478
-	 * @param string $text the text content for the element
479
-	 * @param bool $prepend prepend the header to the beginning of the list
480
-	 */
481
-	public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
482
-		$header = [
483
-			'tag' => $tag,
484
-			'attributes' => $attributes,
485
-			'text' => $text
486
-		];
487
-		if ($prepend === true) {
488
-			array_unshift(self::$headers, $header);
489
-		} else {
490
-			self::$headers[] = $header;
491
-		}
492
-	}
493
-
494
-	/**
495
-	 * check if the current server configuration is suitable for ownCloud
496
-	 *
497
-	 * @param \OC\SystemConfig $config
498
-	 * @return array arrays with error messages and hints
499
-	 */
500
-	public static function checkServer(\OC\SystemConfig $config) {
501
-		$l = \OC::$server->getL10N('lib');
502
-		$errors = [];
503
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
504
-
505
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
506
-			// this check needs to be done every time
507
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
508
-		}
509
-
510
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
511
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
512
-			return $errors;
513
-		}
514
-
515
-		$webServerRestart = false;
516
-		$setup = new \OC\Setup(
517
-			$config,
518
-			\OC::$server->get(IniGetWrapper::class),
519
-			\OC::$server->getL10N('lib'),
520
-			\OC::$server->get(\OCP\Defaults::class),
521
-			\OC::$server->get(LoggerInterface::class),
522
-			\OC::$server->getSecureRandom(),
523
-			\OC::$server->get(\OC\Installer::class)
524
-		);
525
-
526
-		$urlGenerator = \OC::$server->getURLGenerator();
527
-
528
-		$availableDatabases = $setup->getSupportedDatabases();
529
-		if (empty($availableDatabases)) {
530
-			$errors[] = [
531
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
532
-				'hint' => '' //TODO: sane hint
533
-			];
534
-			$webServerRestart = true;
535
-		}
536
-
537
-		// Check if config folder is writable.
538
-		if (!OC_Helper::isReadOnlyConfigEnabled()) {
539
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
540
-				$errors[] = [
541
-					'error' => $l->t('Cannot write into "config" directory.'),
542
-					'hint' => $l->t('This can usually be fixed by giving the web server write access to the config directory. See %s',
543
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
544
-						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
545
-						[ $urlGenerator->linkToDocs('admin-config') ])
546
-				];
547
-			}
548
-		}
549
-
550
-		// Check if there is a writable install folder.
551
-		if ($config->getValue('appstoreenabled', true)) {
552
-			if (OC_App::getInstallPath() === null
553
-				|| !is_writable(OC_App::getInstallPath())
554
-				|| !is_readable(OC_App::getInstallPath())
555
-			) {
556
-				$errors[] = [
557
-					'error' => $l->t('Cannot write into "apps" directory.'),
558
-					'hint' => $l->t('This can usually be fixed by giving the web server write access to the apps directory'
559
-						. ' or disabling the App Store in the config file.')
560
-				];
561
-			}
562
-		}
563
-		// Create root dir.
564
-		if ($config->getValue('installed', false)) {
565
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
566
-				$success = @mkdir($CONFIG_DATADIRECTORY);
567
-				if ($success) {
568
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
569
-				} else {
570
-					$errors[] = [
571
-						'error' => $l->t('Cannot create "data" directory.'),
572
-						'hint' => $l->t('This can usually be fixed by giving the web server write access to the root directory. See %s',
573
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
574
-					];
575
-				}
576
-			} elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
577
-				// is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
578
-				$testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
579
-				$handle = fopen($testFile, 'w');
580
-				if (!$handle || fwrite($handle, 'Test write operation') === false) {
581
-					$permissionsHint = $l->t('Permissions can usually be fixed by giving the web server write access to the root directory. See %s.',
582
-						[$urlGenerator->linkToDocs('admin-dir_permissions')]);
583
-					$errors[] = [
584
-						'error' => $l->t('Your data directory is not writable.'),
585
-						'hint' => $permissionsHint
586
-					];
587
-				} else {
588
-					fclose($handle);
589
-					unlink($testFile);
590
-				}
591
-			} else {
592
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
593
-			}
594
-		}
595
-
596
-		if (!OC_Util::isSetLocaleWorking()) {
597
-			$errors[] = [
598
-				'error' => $l->t('Setting locale to %s failed.',
599
-					['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
600
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
601
-				'hint' => $l->t('Please install one of these locales on your system and restart your web server.')
602
-			];
603
-		}
604
-
605
-		// Contains the dependencies that should be checked against
606
-		// classes = class_exists
607
-		// functions = function_exists
608
-		// defined = defined
609
-		// ini = ini_get
610
-		// If the dependency is not found the missing module name is shown to the EndUser
611
-		// When adding new checks always verify that they pass on Travis as well
612
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
613
-		$dependencies = [
614
-			'classes' => [
615
-				'ZipArchive' => 'zip',
616
-				'DOMDocument' => 'dom',
617
-				'XMLWriter' => 'XMLWriter',
618
-				'XMLReader' => 'XMLReader',
619
-			],
620
-			'functions' => [
621
-				'xml_parser_create' => 'libxml',
622
-				'mb_strcut' => 'mbstring',
623
-				'ctype_digit' => 'ctype',
624
-				'json_encode' => 'JSON',
625
-				'gd_info' => 'GD',
626
-				'gzencode' => 'zlib',
627
-				'simplexml_load_string' => 'SimpleXML',
628
-				'hash' => 'HASH Message Digest Framework',
629
-				'curl_init' => 'cURL',
630
-				'openssl_verify' => 'OpenSSL',
631
-			],
632
-			'defined' => [
633
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
634
-			],
635
-			'ini' => [
636
-				'default_charset' => 'UTF-8',
637
-			],
638
-		];
639
-		$missingDependencies = [];
640
-		$invalidIniSettings = [];
641
-
642
-		$iniWrapper = \OC::$server->get(IniGetWrapper::class);
643
-		foreach ($dependencies['classes'] as $class => $module) {
644
-			if (!class_exists($class)) {
645
-				$missingDependencies[] = $module;
646
-			}
647
-		}
648
-		foreach ($dependencies['functions'] as $function => $module) {
649
-			if (!function_exists($function)) {
650
-				$missingDependencies[] = $module;
651
-			}
652
-		}
653
-		foreach ($dependencies['defined'] as $defined => $module) {
654
-			if (!defined($defined)) {
655
-				$missingDependencies[] = $module;
656
-			}
657
-		}
658
-		foreach ($dependencies['ini'] as $setting => $expected) {
659
-			if (is_bool($expected)) {
660
-				if ($iniWrapper->getBool($setting) !== $expected) {
661
-					$invalidIniSettings[] = [$setting, $expected];
662
-				}
663
-			}
664
-			if (is_int($expected)) {
665
-				if ($iniWrapper->getNumeric($setting) !== $expected) {
666
-					$invalidIniSettings[] = [$setting, $expected];
667
-				}
668
-			}
669
-			if (is_string($expected)) {
670
-				if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
671
-					$invalidIniSettings[] = [$setting, $expected];
672
-				}
673
-			}
674
-		}
675
-
676
-		foreach ($missingDependencies as $missingDependency) {
677
-			$errors[] = [
678
-				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
679
-				'hint' => $l->t('Please ask your server administrator to install the module.'),
680
-			];
681
-			$webServerRestart = true;
682
-		}
683
-		foreach ($invalidIniSettings as $setting) {
684
-			if (is_bool($setting[1])) {
685
-				$setting[1] = $setting[1] ? 'on' : 'off';
686
-			}
687
-			$errors[] = [
688
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
689
-				'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
690
-			];
691
-			$webServerRestart = true;
692
-		}
693
-
694
-		/**
695
-		 * The mbstring.func_overload check can only be performed if the mbstring
696
-		 * module is installed as it will return null if the checking setting is
697
-		 * not available and thus a check on the boolean value fails.
698
-		 *
699
-		 * TODO: Should probably be implemented in the above generic dependency
700
-		 *       check somehow in the long-term.
701
-		 */
702
-		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
703
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
704
-			$errors[] = [
705
-				'error' => $l->t('<code>mbstring.func_overload</code> is set to <code>%s</code> instead of the expected value <code>0</code>.', [$iniWrapper->getString('mbstring.func_overload')]),
706
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini.')
707
-			];
708
-		}
709
-
710
-		if (function_exists('xml_parser_create') &&
711
-			LIBXML_LOADED_VERSION < 20700) {
712
-			$version = LIBXML_LOADED_VERSION;
713
-			$major = floor($version / 10000);
714
-			$version -= ($major * 10000);
715
-			$minor = floor($version / 100);
716
-			$version -= ($minor * 100);
717
-			$patch = $version;
718
-			$errors[] = [
719
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
720
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
721
-			];
722
-		}
723
-
724
-		if (!self::isAnnotationsWorking()) {
725
-			$errors[] = [
726
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
727
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
728
-			];
729
-		}
730
-
731
-		if (!\OC::$CLI && $webServerRestart) {
732
-			$errors[] = [
733
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
734
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
735
-			];
736
-		}
737
-
738
-		$errors = array_merge($errors, self::checkDatabaseVersion());
739
-
740
-		// Cache the result of this function
741
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
742
-
743
-		return $errors;
744
-	}
745
-
746
-	/**
747
-	 * Check the database version
748
-	 *
749
-	 * @return array errors array
750
-	 */
751
-	public static function checkDatabaseVersion() {
752
-		$l = \OC::$server->getL10N('lib');
753
-		$errors = [];
754
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
755
-		if ($dbType === 'pgsql') {
756
-			// check PostgreSQL version
757
-			try {
758
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
759
-				$data = $result->fetchRow();
760
-				$result->closeCursor();
761
-				if (isset($data['server_version'])) {
762
-					$version = $data['server_version'];
763
-					if (version_compare($version, '9.0.0', '<')) {
764
-						$errors[] = [
765
-							'error' => $l->t('PostgreSQL >= 9 required.'),
766
-							'hint' => $l->t('Please upgrade your database version.')
767
-						];
768
-					}
769
-				}
770
-			} catch (\Doctrine\DBAL\Exception $e) {
771
-				$logger = \OC::$server->getLogger();
772
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
773
-				$logger->logException($e);
774
-			}
775
-		}
776
-		return $errors;
777
-	}
778
-
779
-	/**
780
-	 * Check for correct file permissions of data directory
781
-	 *
782
-	 * @param string $dataDirectory
783
-	 * @return array arrays with error messages and hints
784
-	 */
785
-	public static function checkDataDirectoryPermissions($dataDirectory) {
786
-		if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
787
-			return  [];
788
-		}
789
-
790
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
791
-		if (substr($perms, -1) !== '0') {
792
-			chmod($dataDirectory, 0770);
793
-			clearstatcache();
794
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
795
-			if ($perms[2] !== '0') {
796
-				$l = \OC::$server->getL10N('lib');
797
-				return [[
798
-					'error' => $l->t('Your data directory is readable by other users.'),
799
-					'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
800
-				]];
801
-			}
802
-		}
803
-		return [];
804
-	}
805
-
806
-	/**
807
-	 * Check that the data directory exists and is valid by
808
-	 * checking the existence of the ".ocdata" file.
809
-	 *
810
-	 * @param string $dataDirectory data directory path
811
-	 * @return array errors found
812
-	 */
813
-	public static function checkDataDirectoryValidity($dataDirectory) {
814
-		$l = \OC::$server->getL10N('lib');
815
-		$errors = [];
816
-		if ($dataDirectory[0] !== '/') {
817
-			$errors[] = [
818
-				'error' => $l->t('Your data directory must be an absolute path.'),
819
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration.')
820
-			];
821
-		}
822
-		if (!file_exists($dataDirectory . '/.ocdata')) {
823
-			$errors[] = [
824
-				'error' => $l->t('Your data directory is invalid.'),
825
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
826
-					' in the root of the data directory.')
827
-			];
828
-		}
829
-		return $errors;
830
-	}
831
-
832
-	/**
833
-	 * Check if the user is logged in, redirects to home if not. With
834
-	 * redirect URL parameter to the request URI.
835
-	 *
836
-	 * @return void
837
-	 */
838
-	public static function checkLoggedIn() {
839
-		// Check if we are a user
840
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
841
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
842
-						'core.login.showLoginForm',
843
-						[
844
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
845
-						]
846
-					)
847
-			);
848
-			exit();
849
-		}
850
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
851
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
852
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
853
-			exit();
854
-		}
855
-	}
856
-
857
-	/**
858
-	 * Check if the user is a admin, redirects to home if not
859
-	 *
860
-	 * @return void
861
-	 */
862
-	public static function checkAdminUser() {
863
-		OC_Util::checkLoggedIn();
864
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
865
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
866
-			exit();
867
-		}
868
-	}
869
-
870
-	/**
871
-	 * Returns the URL of the default page
872
-	 * based on the system configuration and
873
-	 * the apps visible for the current user
874
-	 *
875
-	 * @return string URL
876
-	 * @suppress PhanDeprecatedFunction
877
-	 */
878
-	public static function getDefaultPageUrl() {
879
-		/** @var IURLGenerator $urlGenerator */
880
-		$urlGenerator = \OC::$server->get(IURLGenerator::class);
881
-		return $urlGenerator->linkToDefaultPageUrl();
882
-	}
883
-
884
-	/**
885
-	 * Redirect to the user default page
886
-	 *
887
-	 * @return void
888
-	 */
889
-	public static function redirectToDefaultPage() {
890
-		$location = self::getDefaultPageUrl();
891
-		header('Location: ' . $location);
892
-		exit();
893
-	}
894
-
895
-	/**
896
-	 * get an id unique for this instance
897
-	 *
898
-	 * @return string
899
-	 */
900
-	public static function getInstanceId() {
901
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
902
-		if (is_null($id)) {
903
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
904
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
905
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
906
-		}
907
-		return $id;
908
-	}
909
-
910
-	/**
911
-	 * Public function to sanitize HTML
912
-	 *
913
-	 * This function is used to sanitize HTML and should be applied on any
914
-	 * string or array of strings before displaying it on a web page.
915
-	 *
916
-	 * @param string|string[] $value
917
-	 * @return string|string[] an array of sanitized strings or a single sanitized string, depends on the input parameter.
918
-	 */
919
-	public static function sanitizeHTML($value) {
920
-		if (is_array($value)) {
921
-			/** @var string[] $value */
922
-			$value = array_map(function ($value) {
923
-				return self::sanitizeHTML($value);
924
-			}, $value);
925
-		} else {
926
-			// Specify encoding for PHP<5.4
927
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
928
-		}
929
-		return $value;
930
-	}
931
-
932
-	/**
933
-	 * Public function to encode url parameters
934
-	 *
935
-	 * This function is used to encode path to file before output.
936
-	 * Encoding is done according to RFC 3986 with one exception:
937
-	 * Character '/' is preserved as is.
938
-	 *
939
-	 * @param string $component part of URI to encode
940
-	 * @return string
941
-	 */
942
-	public static function encodePath($component) {
943
-		$encoded = rawurlencode($component);
944
-		$encoded = str_replace('%2F', '/', $encoded);
945
-		return $encoded;
946
-	}
947
-
948
-
949
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
950
-		// php dev server does not support htaccess
951
-		if (php_sapi_name() === 'cli-server') {
952
-			return false;
953
-		}
954
-
955
-		// testdata
956
-		$fileName = '/htaccesstest.txt';
957
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
958
-
959
-		// creating a test file
960
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
961
-
962
-		if (file_exists($testFile)) {// already running this test, possible recursive call
963
-			return false;
964
-		}
965
-
966
-		$fp = @fopen($testFile, 'w');
967
-		if (!$fp) {
968
-			throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.',
969
-				'Make sure it is possible for the web server to write to ' . $testFile);
970
-		}
971
-		fwrite($fp, $testContent);
972
-		fclose($fp);
973
-
974
-		return $testContent;
975
-	}
976
-
977
-	/**
978
-	 * Check if the .htaccess file is working
979
-	 *
980
-	 * @param \OCP\IConfig $config
981
-	 * @return bool
982
-	 * @throws Exception
983
-	 * @throws \OCP\HintException If the test file can't get written.
984
-	 */
985
-	public function isHtaccessWorking(\OCP\IConfig $config) {
986
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
987
-			return true;
988
-		}
989
-
990
-		$testContent = $this->createHtaccessTestFile($config);
991
-		if ($testContent === false) {
992
-			return false;
993
-		}
994
-
995
-		$fileName = '/htaccesstest.txt';
996
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
997
-
998
-		// accessing the file via http
999
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1000
-		try {
1001
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1002
-		} catch (\Exception $e) {
1003
-			$content = false;
1004
-		}
1005
-
1006
-		if (strpos($url, 'https:') === 0) {
1007
-			$url = 'http:' . substr($url, 6);
1008
-		} else {
1009
-			$url = 'https:' . substr($url, 5);
1010
-		}
1011
-
1012
-		try {
1013
-			$fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1014
-		} catch (\Exception $e) {
1015
-			$fallbackContent = false;
1016
-		}
1017
-
1018
-		// cleanup
1019
-		@unlink($testFile);
1020
-
1021
-		/*
79
+    public static $scripts = [];
80
+    public static $styles = [];
81
+    public static $headers = [];
82
+
83
+    /** @var array Local cache of version.php */
84
+    private static $versionCache = null;
85
+
86
+    protected static function getAppManager() {
87
+        return \OC::$server->getAppManager();
88
+    }
89
+
90
+    /**
91
+     * Setup the file system
92
+     *
93
+     * @param string|null $user
94
+     * @return boolean
95
+     * @description configure the initial filesystem based on the configuration
96
+     * @suppress PhanDeprecatedFunction
97
+     * @suppress PhanAccessMethodInternal
98
+     */
99
+    public static function setupFS(?string $user = '') {
100
+        // If we are not forced to load a specific user we load the one that is logged in
101
+        if ($user === '') {
102
+            $userObject = \OC::$server->get(\OCP\IUserSession::class)->getUser();
103
+        } else {
104
+            $userObject = \OC::$server->get(\OCP\IUserManager::class)->get($user);
105
+        }
106
+
107
+        /** @var SetupManager $setupManager */
108
+        $setupManager = \OC::$server->get(SetupManager::class);
109
+
110
+        if ($userObject) {
111
+            $setupManager->setupForUser($userObject);
112
+        } else {
113
+            $setupManager->setupRoot();
114
+        }
115
+        return true;
116
+    }
117
+
118
+    /**
119
+     * check if a password is required for each public link
120
+     *
121
+     * @return boolean
122
+     * @suppress PhanDeprecatedFunction
123
+     */
124
+    public static function isPublicLinkPasswordRequired() {
125
+        /** @var IManager $shareManager */
126
+        $shareManager = \OC::$server->get(IManager::class);
127
+        return $shareManager->shareApiLinkEnforcePassword();
128
+    }
129
+
130
+    /**
131
+     * check if sharing is disabled for the current user
132
+     * @param IConfig $config
133
+     * @param IGroupManager $groupManager
134
+     * @param IUser|null $user
135
+     * @return bool
136
+     */
137
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
138
+        /** @var IManager $shareManager */
139
+        $shareManager = \OC::$server->get(IManager::class);
140
+        $userId = $user ? $user->getUID() : null;
141
+        return $shareManager->sharingDisabledForUser($userId);
142
+    }
143
+
144
+    /**
145
+     * check if share API enforces a default expire date
146
+     *
147
+     * @return boolean
148
+     * @suppress PhanDeprecatedFunction
149
+     */
150
+    public static function isDefaultExpireDateEnforced() {
151
+        /** @var IManager $shareManager */
152
+        $shareManager = \OC::$server->get(IManager::class);
153
+        return $shareManager->shareApiLinkDefaultExpireDateEnforced();
154
+    }
155
+
156
+    /**
157
+     * Get the quota of a user
158
+     *
159
+     * @param IUser|null $user
160
+     * @return float Quota bytes
161
+     */
162
+    public static function getUserQuota(?IUser $user) {
163
+        if (is_null($user)) {
164
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
165
+        }
166
+        $userQuota = $user->getQuota();
167
+        if ($userQuota === 'none') {
168
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
169
+        }
170
+        return OC_Helper::computerFileSize($userQuota);
171
+    }
172
+
173
+    /**
174
+     * copies the skeleton to the users /files
175
+     *
176
+     * @param string $userId
177
+     * @param \OCP\Files\Folder $userDirectory
178
+     * @throws \OCP\Files\NotFoundException
179
+     * @throws \OCP\Files\NotPermittedException
180
+     * @suppress PhanDeprecatedFunction
181
+     */
182
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
183
+        /** @var LoggerInterface $logger */
184
+        $logger = \OC::$server->get(LoggerInterface::class);
185
+
186
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
187
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
188
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
189
+
190
+        if (!file_exists($skeletonDirectory)) {
191
+            $dialectStart = strpos($userLang, '_');
192
+            if ($dialectStart !== false) {
193
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
194
+            }
195
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
196
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
197
+            }
198
+            if (!file_exists($skeletonDirectory)) {
199
+                $skeletonDirectory = '';
200
+            }
201
+        }
202
+
203
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
204
+
205
+        if ($instanceId === null) {
206
+            throw new \RuntimeException('no instance id!');
207
+        }
208
+        $appdata = 'appdata_' . $instanceId;
209
+        if ($userId === $appdata) {
210
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
211
+        }
212
+
213
+        if (!empty($skeletonDirectory)) {
214
+            $logger->debug('copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'), ['app' => 'files_skeleton']);
215
+            self::copyr($skeletonDirectory, $userDirectory);
216
+            // update the file cache
217
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
218
+
219
+            /** @var ITemplateManager $templateManager */
220
+            $templateManager = \OC::$server->get(ITemplateManager::class);
221
+            $templateManager->initializeTemplateDirectory(null, $userId);
222
+        }
223
+    }
224
+
225
+    /**
226
+     * copies a directory recursively by using streams
227
+     *
228
+     * @param string $source
229
+     * @param \OCP\Files\Folder $target
230
+     * @return void
231
+     */
232
+    public static function copyr($source, \OCP\Files\Folder $target) {
233
+        $logger = \OC::$server->getLogger();
234
+
235
+        // Verify if folder exists
236
+        $dir = opendir($source);
237
+        if ($dir === false) {
238
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
239
+            return;
240
+        }
241
+
242
+        // Copy the files
243
+        while (false !== ($file = readdir($dir))) {
244
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
245
+                if (is_dir($source . '/' . $file)) {
246
+                    $child = $target->newFolder($file);
247
+                    self::copyr($source . '/' . $file, $child);
248
+                } else {
249
+                    $child = $target->newFile($file);
250
+                    $sourceStream = fopen($source . '/' . $file, 'r');
251
+                    if ($sourceStream === false) {
252
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
253
+                        closedir($dir);
254
+                        return;
255
+                    }
256
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
257
+                }
258
+            }
259
+        }
260
+        closedir($dir);
261
+    }
262
+
263
+    /**
264
+     * @return void
265
+     * @suppress PhanUndeclaredMethod
266
+     */
267
+    public static function tearDownFS() {
268
+        /** @var SetupManager $setupManager */
269
+        $setupManager = \OC::$server->get(SetupManager::class);
270
+        $setupManager->tearDown();
271
+    }
272
+
273
+    /**
274
+     * get the current installed version of ownCloud
275
+     *
276
+     * @return array
277
+     */
278
+    public static function getVersion() {
279
+        OC_Util::loadVersion();
280
+        return self::$versionCache['OC_Version'];
281
+    }
282
+
283
+    /**
284
+     * get the current installed version string of ownCloud
285
+     *
286
+     * @return string
287
+     */
288
+    public static function getVersionString() {
289
+        OC_Util::loadVersion();
290
+        return self::$versionCache['OC_VersionString'];
291
+    }
292
+
293
+    /**
294
+     * @deprecated the value is of no use anymore
295
+     * @return string
296
+     */
297
+    public static function getEditionString() {
298
+        return '';
299
+    }
300
+
301
+    /**
302
+     * @description get the update channel of the current installed of ownCloud.
303
+     * @return string
304
+     */
305
+    public static function getChannel() {
306
+        OC_Util::loadVersion();
307
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
308
+    }
309
+
310
+    /**
311
+     * @description get the build number of the current installed of ownCloud.
312
+     * @return string
313
+     */
314
+    public static function getBuild() {
315
+        OC_Util::loadVersion();
316
+        return self::$versionCache['OC_Build'];
317
+    }
318
+
319
+    /**
320
+     * @description load the version.php into the session as cache
321
+     * @suppress PhanUndeclaredVariable
322
+     */
323
+    private static function loadVersion() {
324
+        if (self::$versionCache !== null) {
325
+            return;
326
+        }
327
+
328
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
329
+        require OC::$SERVERROOT . '/version.php';
330
+        /** @var int $timestamp */
331
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
332
+        /** @var string $OC_Version */
333
+        self::$versionCache['OC_Version'] = $OC_Version;
334
+        /** @var string $OC_VersionString */
335
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
336
+        /** @var string $OC_Build */
337
+        self::$versionCache['OC_Build'] = $OC_Build;
338
+
339
+        /** @var string $OC_Channel */
340
+        self::$versionCache['OC_Channel'] = $OC_Channel;
341
+    }
342
+
343
+    /**
344
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
345
+     *
346
+     * @param string $application application to get the files from
347
+     * @param string $directory directory within this application (css, js, vendor, etc)
348
+     * @param string $file the file inside of the above folder
349
+     * @return string the path
350
+     */
351
+    private static function generatePath($application, $directory, $file) {
352
+        if (is_null($file)) {
353
+            $file = $application;
354
+            $application = "";
355
+        }
356
+        if (!empty($application)) {
357
+            return "$application/$directory/$file";
358
+        } else {
359
+            return "$directory/$file";
360
+        }
361
+    }
362
+
363
+    /**
364
+     * add a javascript file
365
+     *
366
+     * @deprecated 24.0.0 - Use \OCP\Util::addScript
367
+     *
368
+     * @param string $application application id
369
+     * @param string|null $file filename
370
+     * @param bool $prepend prepend the Script to the beginning of the list
371
+     * @return void
372
+     */
373
+    public static function addScript($application, $file = null, $prepend = false) {
374
+        $path = OC_Util::generatePath($application, 'js', $file);
375
+
376
+        // core js files need separate handling
377
+        if ($application !== 'core' && $file !== null) {
378
+            self::addTranslations($application);
379
+        }
380
+        self::addExternalResource($application, $prepend, $path, "script");
381
+    }
382
+
383
+    /**
384
+     * add a javascript file from the vendor sub folder
385
+     *
386
+     * @param string $application application id
387
+     * @param string|null $file filename
388
+     * @param bool $prepend prepend the Script to the beginning of the list
389
+     * @return void
390
+     */
391
+    public static function addVendorScript($application, $file = null, $prepend = false) {
392
+        $path = OC_Util::generatePath($application, 'vendor', $file);
393
+        self::addExternalResource($application, $prepend, $path, "script");
394
+    }
395
+
396
+    /**
397
+     * add a translation JS file
398
+     *
399
+     * @deprecated 24.0.0
400
+     *
401
+     * @param string $application application id
402
+     * @param string|null $languageCode language code, defaults to the current language
403
+     * @param bool|null $prepend prepend the Script to the beginning of the list
404
+     */
405
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
406
+        if (is_null($languageCode)) {
407
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
408
+        }
409
+        if (!empty($application)) {
410
+            $path = "$application/l10n/$languageCode";
411
+        } else {
412
+            $path = "l10n/$languageCode";
413
+        }
414
+        self::addExternalResource($application, $prepend, $path, "script");
415
+    }
416
+
417
+    /**
418
+     * add a css file
419
+     *
420
+     * @param string $application application id
421
+     * @param string|null $file filename
422
+     * @param bool $prepend prepend the Style to the beginning of the list
423
+     * @return void
424
+     */
425
+    public static function addStyle($application, $file = null, $prepend = false) {
426
+        $path = OC_Util::generatePath($application, 'css', $file);
427
+        self::addExternalResource($application, $prepend, $path, "style");
428
+    }
429
+
430
+    /**
431
+     * add a css file from the vendor sub folder
432
+     *
433
+     * @param string $application application id
434
+     * @param string|null $file filename
435
+     * @param bool $prepend prepend the Style to the beginning of the list
436
+     * @return void
437
+     */
438
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
439
+        $path = OC_Util::generatePath($application, 'vendor', $file);
440
+        self::addExternalResource($application, $prepend, $path, "style");
441
+    }
442
+
443
+    /**
444
+     * add an external resource css/js file
445
+     *
446
+     * @param string $application application id
447
+     * @param bool $prepend prepend the file to the beginning of the list
448
+     * @param string $path
449
+     * @param string $type (script or style)
450
+     * @return void
451
+     */
452
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
453
+        if ($type === "style") {
454
+            if (!in_array($path, self::$styles)) {
455
+                if ($prepend === true) {
456
+                    array_unshift(self::$styles, $path);
457
+                } else {
458
+                    self::$styles[] = $path;
459
+                }
460
+            }
461
+        } elseif ($type === "script") {
462
+            if (!in_array($path, self::$scripts)) {
463
+                if ($prepend === true) {
464
+                    array_unshift(self::$scripts, $path);
465
+                } else {
466
+                    self::$scripts [] = $path;
467
+                }
468
+            }
469
+        }
470
+    }
471
+
472
+    /**
473
+     * Add a custom element to the header
474
+     * If $text is null then the element will be written as empty element.
475
+     * So use "" to get a closing tag.
476
+     * @param string $tag tag name of the element
477
+     * @param array $attributes array of attributes for the element
478
+     * @param string $text the text content for the element
479
+     * @param bool $prepend prepend the header to the beginning of the list
480
+     */
481
+    public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
482
+        $header = [
483
+            'tag' => $tag,
484
+            'attributes' => $attributes,
485
+            'text' => $text
486
+        ];
487
+        if ($prepend === true) {
488
+            array_unshift(self::$headers, $header);
489
+        } else {
490
+            self::$headers[] = $header;
491
+        }
492
+    }
493
+
494
+    /**
495
+     * check if the current server configuration is suitable for ownCloud
496
+     *
497
+     * @param \OC\SystemConfig $config
498
+     * @return array arrays with error messages and hints
499
+     */
500
+    public static function checkServer(\OC\SystemConfig $config) {
501
+        $l = \OC::$server->getL10N('lib');
502
+        $errors = [];
503
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
504
+
505
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
506
+            // this check needs to be done every time
507
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
508
+        }
509
+
510
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
511
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
512
+            return $errors;
513
+        }
514
+
515
+        $webServerRestart = false;
516
+        $setup = new \OC\Setup(
517
+            $config,
518
+            \OC::$server->get(IniGetWrapper::class),
519
+            \OC::$server->getL10N('lib'),
520
+            \OC::$server->get(\OCP\Defaults::class),
521
+            \OC::$server->get(LoggerInterface::class),
522
+            \OC::$server->getSecureRandom(),
523
+            \OC::$server->get(\OC\Installer::class)
524
+        );
525
+
526
+        $urlGenerator = \OC::$server->getURLGenerator();
527
+
528
+        $availableDatabases = $setup->getSupportedDatabases();
529
+        if (empty($availableDatabases)) {
530
+            $errors[] = [
531
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
532
+                'hint' => '' //TODO: sane hint
533
+            ];
534
+            $webServerRestart = true;
535
+        }
536
+
537
+        // Check if config folder is writable.
538
+        if (!OC_Helper::isReadOnlyConfigEnabled()) {
539
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
540
+                $errors[] = [
541
+                    'error' => $l->t('Cannot write into "config" directory.'),
542
+                    'hint' => $l->t('This can usually be fixed by giving the web server write access to the config directory. See %s',
543
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
544
+                        . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
545
+                        [ $urlGenerator->linkToDocs('admin-config') ])
546
+                ];
547
+            }
548
+        }
549
+
550
+        // Check if there is a writable install folder.
551
+        if ($config->getValue('appstoreenabled', true)) {
552
+            if (OC_App::getInstallPath() === null
553
+                || !is_writable(OC_App::getInstallPath())
554
+                || !is_readable(OC_App::getInstallPath())
555
+            ) {
556
+                $errors[] = [
557
+                    'error' => $l->t('Cannot write into "apps" directory.'),
558
+                    'hint' => $l->t('This can usually be fixed by giving the web server write access to the apps directory'
559
+                        . ' or disabling the App Store in the config file.')
560
+                ];
561
+            }
562
+        }
563
+        // Create root dir.
564
+        if ($config->getValue('installed', false)) {
565
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
566
+                $success = @mkdir($CONFIG_DATADIRECTORY);
567
+                if ($success) {
568
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
569
+                } else {
570
+                    $errors[] = [
571
+                        'error' => $l->t('Cannot create "data" directory.'),
572
+                        'hint' => $l->t('This can usually be fixed by giving the web server write access to the root directory. See %s',
573
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
574
+                    ];
575
+                }
576
+            } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
577
+                // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
578
+                $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
579
+                $handle = fopen($testFile, 'w');
580
+                if (!$handle || fwrite($handle, 'Test write operation') === false) {
581
+                    $permissionsHint = $l->t('Permissions can usually be fixed by giving the web server write access to the root directory. See %s.',
582
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')]);
583
+                    $errors[] = [
584
+                        'error' => $l->t('Your data directory is not writable.'),
585
+                        'hint' => $permissionsHint
586
+                    ];
587
+                } else {
588
+                    fclose($handle);
589
+                    unlink($testFile);
590
+                }
591
+            } else {
592
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
593
+            }
594
+        }
595
+
596
+        if (!OC_Util::isSetLocaleWorking()) {
597
+            $errors[] = [
598
+                'error' => $l->t('Setting locale to %s failed.',
599
+                    ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
600
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
601
+                'hint' => $l->t('Please install one of these locales on your system and restart your web server.')
602
+            ];
603
+        }
604
+
605
+        // Contains the dependencies that should be checked against
606
+        // classes = class_exists
607
+        // functions = function_exists
608
+        // defined = defined
609
+        // ini = ini_get
610
+        // If the dependency is not found the missing module name is shown to the EndUser
611
+        // When adding new checks always verify that they pass on Travis as well
612
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
613
+        $dependencies = [
614
+            'classes' => [
615
+                'ZipArchive' => 'zip',
616
+                'DOMDocument' => 'dom',
617
+                'XMLWriter' => 'XMLWriter',
618
+                'XMLReader' => 'XMLReader',
619
+            ],
620
+            'functions' => [
621
+                'xml_parser_create' => 'libxml',
622
+                'mb_strcut' => 'mbstring',
623
+                'ctype_digit' => 'ctype',
624
+                'json_encode' => 'JSON',
625
+                'gd_info' => 'GD',
626
+                'gzencode' => 'zlib',
627
+                'simplexml_load_string' => 'SimpleXML',
628
+                'hash' => 'HASH Message Digest Framework',
629
+                'curl_init' => 'cURL',
630
+                'openssl_verify' => 'OpenSSL',
631
+            ],
632
+            'defined' => [
633
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
634
+            ],
635
+            'ini' => [
636
+                'default_charset' => 'UTF-8',
637
+            ],
638
+        ];
639
+        $missingDependencies = [];
640
+        $invalidIniSettings = [];
641
+
642
+        $iniWrapper = \OC::$server->get(IniGetWrapper::class);
643
+        foreach ($dependencies['classes'] as $class => $module) {
644
+            if (!class_exists($class)) {
645
+                $missingDependencies[] = $module;
646
+            }
647
+        }
648
+        foreach ($dependencies['functions'] as $function => $module) {
649
+            if (!function_exists($function)) {
650
+                $missingDependencies[] = $module;
651
+            }
652
+        }
653
+        foreach ($dependencies['defined'] as $defined => $module) {
654
+            if (!defined($defined)) {
655
+                $missingDependencies[] = $module;
656
+            }
657
+        }
658
+        foreach ($dependencies['ini'] as $setting => $expected) {
659
+            if (is_bool($expected)) {
660
+                if ($iniWrapper->getBool($setting) !== $expected) {
661
+                    $invalidIniSettings[] = [$setting, $expected];
662
+                }
663
+            }
664
+            if (is_int($expected)) {
665
+                if ($iniWrapper->getNumeric($setting) !== $expected) {
666
+                    $invalidIniSettings[] = [$setting, $expected];
667
+                }
668
+            }
669
+            if (is_string($expected)) {
670
+                if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
671
+                    $invalidIniSettings[] = [$setting, $expected];
672
+                }
673
+            }
674
+        }
675
+
676
+        foreach ($missingDependencies as $missingDependency) {
677
+            $errors[] = [
678
+                'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
679
+                'hint' => $l->t('Please ask your server administrator to install the module.'),
680
+            ];
681
+            $webServerRestart = true;
682
+        }
683
+        foreach ($invalidIniSettings as $setting) {
684
+            if (is_bool($setting[1])) {
685
+                $setting[1] = $setting[1] ? 'on' : 'off';
686
+            }
687
+            $errors[] = [
688
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
689
+                'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
690
+            ];
691
+            $webServerRestart = true;
692
+        }
693
+
694
+        /**
695
+         * The mbstring.func_overload check can only be performed if the mbstring
696
+         * module is installed as it will return null if the checking setting is
697
+         * not available and thus a check on the boolean value fails.
698
+         *
699
+         * TODO: Should probably be implemented in the above generic dependency
700
+         *       check somehow in the long-term.
701
+         */
702
+        if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
703
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
704
+            $errors[] = [
705
+                'error' => $l->t('<code>mbstring.func_overload</code> is set to <code>%s</code> instead of the expected value <code>0</code>.', [$iniWrapper->getString('mbstring.func_overload')]),
706
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini.')
707
+            ];
708
+        }
709
+
710
+        if (function_exists('xml_parser_create') &&
711
+            LIBXML_LOADED_VERSION < 20700) {
712
+            $version = LIBXML_LOADED_VERSION;
713
+            $major = floor($version / 10000);
714
+            $version -= ($major * 10000);
715
+            $minor = floor($version / 100);
716
+            $version -= ($minor * 100);
717
+            $patch = $version;
718
+            $errors[] = [
719
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
720
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
721
+            ];
722
+        }
723
+
724
+        if (!self::isAnnotationsWorking()) {
725
+            $errors[] = [
726
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
727
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
728
+            ];
729
+        }
730
+
731
+        if (!\OC::$CLI && $webServerRestart) {
732
+            $errors[] = [
733
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
734
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
735
+            ];
736
+        }
737
+
738
+        $errors = array_merge($errors, self::checkDatabaseVersion());
739
+
740
+        // Cache the result of this function
741
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
742
+
743
+        return $errors;
744
+    }
745
+
746
+    /**
747
+     * Check the database version
748
+     *
749
+     * @return array errors array
750
+     */
751
+    public static function checkDatabaseVersion() {
752
+        $l = \OC::$server->getL10N('lib');
753
+        $errors = [];
754
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
755
+        if ($dbType === 'pgsql') {
756
+            // check PostgreSQL version
757
+            try {
758
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
759
+                $data = $result->fetchRow();
760
+                $result->closeCursor();
761
+                if (isset($data['server_version'])) {
762
+                    $version = $data['server_version'];
763
+                    if (version_compare($version, '9.0.0', '<')) {
764
+                        $errors[] = [
765
+                            'error' => $l->t('PostgreSQL >= 9 required.'),
766
+                            'hint' => $l->t('Please upgrade your database version.')
767
+                        ];
768
+                    }
769
+                }
770
+            } catch (\Doctrine\DBAL\Exception $e) {
771
+                $logger = \OC::$server->getLogger();
772
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
773
+                $logger->logException($e);
774
+            }
775
+        }
776
+        return $errors;
777
+    }
778
+
779
+    /**
780
+     * Check for correct file permissions of data directory
781
+     *
782
+     * @param string $dataDirectory
783
+     * @return array arrays with error messages and hints
784
+     */
785
+    public static function checkDataDirectoryPermissions($dataDirectory) {
786
+        if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
787
+            return  [];
788
+        }
789
+
790
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
791
+        if (substr($perms, -1) !== '0') {
792
+            chmod($dataDirectory, 0770);
793
+            clearstatcache();
794
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
795
+            if ($perms[2] !== '0') {
796
+                $l = \OC::$server->getL10N('lib');
797
+                return [[
798
+                    'error' => $l->t('Your data directory is readable by other users.'),
799
+                    'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
800
+                ]];
801
+            }
802
+        }
803
+        return [];
804
+    }
805
+
806
+    /**
807
+     * Check that the data directory exists and is valid by
808
+     * checking the existence of the ".ocdata" file.
809
+     *
810
+     * @param string $dataDirectory data directory path
811
+     * @return array errors found
812
+     */
813
+    public static function checkDataDirectoryValidity($dataDirectory) {
814
+        $l = \OC::$server->getL10N('lib');
815
+        $errors = [];
816
+        if ($dataDirectory[0] !== '/') {
817
+            $errors[] = [
818
+                'error' => $l->t('Your data directory must be an absolute path.'),
819
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration.')
820
+            ];
821
+        }
822
+        if (!file_exists($dataDirectory . '/.ocdata')) {
823
+            $errors[] = [
824
+                'error' => $l->t('Your data directory is invalid.'),
825
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
826
+                    ' in the root of the data directory.')
827
+            ];
828
+        }
829
+        return $errors;
830
+    }
831
+
832
+    /**
833
+     * Check if the user is logged in, redirects to home if not. With
834
+     * redirect URL parameter to the request URI.
835
+     *
836
+     * @return void
837
+     */
838
+    public static function checkLoggedIn() {
839
+        // Check if we are a user
840
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
841
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
842
+                        'core.login.showLoginForm',
843
+                        [
844
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
845
+                        ]
846
+                    )
847
+            );
848
+            exit();
849
+        }
850
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
851
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
852
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
853
+            exit();
854
+        }
855
+    }
856
+
857
+    /**
858
+     * Check if the user is a admin, redirects to home if not
859
+     *
860
+     * @return void
861
+     */
862
+    public static function checkAdminUser() {
863
+        OC_Util::checkLoggedIn();
864
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
865
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
866
+            exit();
867
+        }
868
+    }
869
+
870
+    /**
871
+     * Returns the URL of the default page
872
+     * based on the system configuration and
873
+     * the apps visible for the current user
874
+     *
875
+     * @return string URL
876
+     * @suppress PhanDeprecatedFunction
877
+     */
878
+    public static function getDefaultPageUrl() {
879
+        /** @var IURLGenerator $urlGenerator */
880
+        $urlGenerator = \OC::$server->get(IURLGenerator::class);
881
+        return $urlGenerator->linkToDefaultPageUrl();
882
+    }
883
+
884
+    /**
885
+     * Redirect to the user default page
886
+     *
887
+     * @return void
888
+     */
889
+    public static function redirectToDefaultPage() {
890
+        $location = self::getDefaultPageUrl();
891
+        header('Location: ' . $location);
892
+        exit();
893
+    }
894
+
895
+    /**
896
+     * get an id unique for this instance
897
+     *
898
+     * @return string
899
+     */
900
+    public static function getInstanceId() {
901
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
902
+        if (is_null($id)) {
903
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
904
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
905
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
906
+        }
907
+        return $id;
908
+    }
909
+
910
+    /**
911
+     * Public function to sanitize HTML
912
+     *
913
+     * This function is used to sanitize HTML and should be applied on any
914
+     * string or array of strings before displaying it on a web page.
915
+     *
916
+     * @param string|string[] $value
917
+     * @return string|string[] an array of sanitized strings or a single sanitized string, depends on the input parameter.
918
+     */
919
+    public static function sanitizeHTML($value) {
920
+        if (is_array($value)) {
921
+            /** @var string[] $value */
922
+            $value = array_map(function ($value) {
923
+                return self::sanitizeHTML($value);
924
+            }, $value);
925
+        } else {
926
+            // Specify encoding for PHP<5.4
927
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
928
+        }
929
+        return $value;
930
+    }
931
+
932
+    /**
933
+     * Public function to encode url parameters
934
+     *
935
+     * This function is used to encode path to file before output.
936
+     * Encoding is done according to RFC 3986 with one exception:
937
+     * Character '/' is preserved as is.
938
+     *
939
+     * @param string $component part of URI to encode
940
+     * @return string
941
+     */
942
+    public static function encodePath($component) {
943
+        $encoded = rawurlencode($component);
944
+        $encoded = str_replace('%2F', '/', $encoded);
945
+        return $encoded;
946
+    }
947
+
948
+
949
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
950
+        // php dev server does not support htaccess
951
+        if (php_sapi_name() === 'cli-server') {
952
+            return false;
953
+        }
954
+
955
+        // testdata
956
+        $fileName = '/htaccesstest.txt';
957
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
958
+
959
+        // creating a test file
960
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
961
+
962
+        if (file_exists($testFile)) {// already running this test, possible recursive call
963
+            return false;
964
+        }
965
+
966
+        $fp = @fopen($testFile, 'w');
967
+        if (!$fp) {
968
+            throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.',
969
+                'Make sure it is possible for the web server to write to ' . $testFile);
970
+        }
971
+        fwrite($fp, $testContent);
972
+        fclose($fp);
973
+
974
+        return $testContent;
975
+    }
976
+
977
+    /**
978
+     * Check if the .htaccess file is working
979
+     *
980
+     * @param \OCP\IConfig $config
981
+     * @return bool
982
+     * @throws Exception
983
+     * @throws \OCP\HintException If the test file can't get written.
984
+     */
985
+    public function isHtaccessWorking(\OCP\IConfig $config) {
986
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
987
+            return true;
988
+        }
989
+
990
+        $testContent = $this->createHtaccessTestFile($config);
991
+        if ($testContent === false) {
992
+            return false;
993
+        }
994
+
995
+        $fileName = '/htaccesstest.txt';
996
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
997
+
998
+        // accessing the file via http
999
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1000
+        try {
1001
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1002
+        } catch (\Exception $e) {
1003
+            $content = false;
1004
+        }
1005
+
1006
+        if (strpos($url, 'https:') === 0) {
1007
+            $url = 'http:' . substr($url, 6);
1008
+        } else {
1009
+            $url = 'https:' . substr($url, 5);
1010
+        }
1011
+
1012
+        try {
1013
+            $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1014
+        } catch (\Exception $e) {
1015
+            $fallbackContent = false;
1016
+        }
1017
+
1018
+        // cleanup
1019
+        @unlink($testFile);
1020
+
1021
+        /*
1022 1022
 		 * If the content is not equal to test content our .htaccess
1023 1023
 		 * is working as required
1024 1024
 		 */
1025
-		return $content !== $testContent && $fallbackContent !== $testContent;
1026
-	}
1027
-
1028
-	/**
1029
-	 * Check if current locale is non-UTF8
1030
-	 *
1031
-	 * @return bool
1032
-	 */
1033
-	private static function isNonUTF8Locale() {
1034
-		if (function_exists('escapeshellcmd')) {
1035
-			return '' === escapeshellcmd('§');
1036
-		} elseif (function_exists('escapeshellarg')) {
1037
-			return '\'\'' === escapeshellarg('§');
1038
-		} else {
1039
-			return 0 === preg_match('/utf-?8/i', setlocale(LC_CTYPE, 0));
1040
-		}
1041
-	}
1042
-
1043
-	/**
1044
-	 * Check if the setlocale call does not work. This can happen if the right
1045
-	 * local packages are not available on the server.
1046
-	 *
1047
-	 * @return bool
1048
-	 */
1049
-	public static function isSetLocaleWorking() {
1050
-		if (self::isNonUTF8Locale()) {
1051
-			// Borrowed from \Patchwork\Utf8\Bootup::initLocale
1052
-			setlocale(LC_ALL, 'C.UTF-8', 'C');
1053
-			setlocale(LC_CTYPE, 'en_US.UTF-8', 'fr_FR.UTF-8', 'es_ES.UTF-8', 'de_DE.UTF-8', 'ru_RU.UTF-8', 'pt_BR.UTF-8', 'it_IT.UTF-8', 'ja_JP.UTF-8', 'zh_CN.UTF-8', '0');
1054
-
1055
-			// Check again
1056
-			if (self::isNonUTF8Locale()) {
1057
-				return false;
1058
-			}
1059
-		}
1060
-
1061
-		return true;
1062
-	}
1063
-
1064
-	/**
1065
-	 * Check if it's possible to get the inline annotations
1066
-	 *
1067
-	 * @return bool
1068
-	 */
1069
-	public static function isAnnotationsWorking() {
1070
-		$reflection = new \ReflectionMethod(__METHOD__);
1071
-		$docs = $reflection->getDocComment();
1072
-
1073
-		return (is_string($docs) && strlen($docs) > 50);
1074
-	}
1075
-
1076
-	/**
1077
-	 * Check if the PHP module fileinfo is loaded.
1078
-	 *
1079
-	 * @return bool
1080
-	 */
1081
-	public static function fileInfoLoaded() {
1082
-		return function_exists('finfo_open');
1083
-	}
1084
-
1085
-	/**
1086
-	 * clear all levels of output buffering
1087
-	 *
1088
-	 * @return void
1089
-	 */
1090
-	public static function obEnd() {
1091
-		while (ob_get_level()) {
1092
-			ob_end_clean();
1093
-		}
1094
-	}
1095
-
1096
-	/**
1097
-	 * Checks whether the server is running on Mac OS X
1098
-	 *
1099
-	 * @return bool true if running on Mac OS X, false otherwise
1100
-	 */
1101
-	public static function runningOnMac() {
1102
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1103
-	}
1104
-
1105
-	/**
1106
-	 * Handles the case that there may not be a theme, then check if a "default"
1107
-	 * theme exists and take that one
1108
-	 *
1109
-	 * @return string the theme
1110
-	 */
1111
-	public static function getTheme() {
1112
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1113
-
1114
-		if ($theme === '') {
1115
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1116
-				$theme = 'default';
1117
-			}
1118
-		}
1119
-
1120
-		return $theme;
1121
-	}
1122
-
1123
-	/**
1124
-	 * Normalize a unicode string
1125
-	 *
1126
-	 * @param string $value a not normalized string
1127
-	 * @return bool|string
1128
-	 */
1129
-	public static function normalizeUnicode($value) {
1130
-		if (Normalizer::isNormalized($value)) {
1131
-			return $value;
1132
-		}
1133
-
1134
-		$normalizedValue = Normalizer::normalize($value);
1135
-		if ($normalizedValue === null || $normalizedValue === false) {
1136
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1137
-			return $value;
1138
-		}
1139
-
1140
-		return $normalizedValue;
1141
-	}
1142
-
1143
-	/**
1144
-	 * A human readable string is generated based on version and build number
1145
-	 *
1146
-	 * @return string
1147
-	 */
1148
-	public static function getHumanVersion() {
1149
-		$version = OC_Util::getVersionString();
1150
-		$build = OC_Util::getBuild();
1151
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1152
-			$version .= ' Build:' . $build;
1153
-		}
1154
-		return $version;
1155
-	}
1156
-
1157
-	/**
1158
-	 * Returns whether the given file name is valid
1159
-	 *
1160
-	 * @param string $file file name to check
1161
-	 * @return bool true if the file name is valid, false otherwise
1162
-	 * @deprecated use \OC\Files\View::verifyPath()
1163
-	 */
1164
-	public static function isValidFileName($file) {
1165
-		$trimmed = trim($file);
1166
-		if ($trimmed === '') {
1167
-			return false;
1168
-		}
1169
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1170
-			return false;
1171
-		}
1172
-
1173
-		// detect part files
1174
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1175
-			return false;
1176
-		}
1177
-
1178
-		foreach (str_split($trimmed) as $char) {
1179
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1180
-				return false;
1181
-			}
1182
-		}
1183
-		return true;
1184
-	}
1185
-
1186
-	/**
1187
-	 * Check whether the instance needs to perform an upgrade,
1188
-	 * either when the core version is higher or any app requires
1189
-	 * an upgrade.
1190
-	 *
1191
-	 * @param \OC\SystemConfig $config
1192
-	 * @return bool whether the core or any app needs an upgrade
1193
-	 * @throws \OCP\HintException When the upgrade from the given version is not allowed
1194
-	 */
1195
-	public static function needUpgrade(\OC\SystemConfig $config) {
1196
-		if ($config->getValue('installed', false)) {
1197
-			$installedVersion = $config->getValue('version', '0.0.0');
1198
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1199
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1200
-			if ($versionDiff > 0) {
1201
-				return true;
1202
-			} elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1203
-				// downgrade with debug
1204
-				$installedMajor = explode('.', $installedVersion);
1205
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1206
-				$currentMajor = explode('.', $currentVersion);
1207
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1208
-				if ($installedMajor === $currentMajor) {
1209
-					// Same major, allow downgrade for developers
1210
-					return true;
1211
-				} else {
1212
-					// downgrade attempt, throw exception
1213
-					throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1214
-				}
1215
-			} elseif ($versionDiff < 0) {
1216
-				// downgrade attempt, throw exception
1217
-				throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1218
-			}
1219
-
1220
-			// also check for upgrades for apps (independently from the user)
1221
-			$apps = \OC_App::getEnabledApps(false, true);
1222
-			$shouldUpgrade = false;
1223
-			foreach ($apps as $app) {
1224
-				if (\OC_App::shouldUpgrade($app)) {
1225
-					$shouldUpgrade = true;
1226
-					break;
1227
-				}
1228
-			}
1229
-			return $shouldUpgrade;
1230
-		} else {
1231
-			return false;
1232
-		}
1233
-	}
1025
+        return $content !== $testContent && $fallbackContent !== $testContent;
1026
+    }
1027
+
1028
+    /**
1029
+     * Check if current locale is non-UTF8
1030
+     *
1031
+     * @return bool
1032
+     */
1033
+    private static function isNonUTF8Locale() {
1034
+        if (function_exists('escapeshellcmd')) {
1035
+            return '' === escapeshellcmd('§');
1036
+        } elseif (function_exists('escapeshellarg')) {
1037
+            return '\'\'' === escapeshellarg('§');
1038
+        } else {
1039
+            return 0 === preg_match('/utf-?8/i', setlocale(LC_CTYPE, 0));
1040
+        }
1041
+    }
1042
+
1043
+    /**
1044
+     * Check if the setlocale call does not work. This can happen if the right
1045
+     * local packages are not available on the server.
1046
+     *
1047
+     * @return bool
1048
+     */
1049
+    public static function isSetLocaleWorking() {
1050
+        if (self::isNonUTF8Locale()) {
1051
+            // Borrowed from \Patchwork\Utf8\Bootup::initLocale
1052
+            setlocale(LC_ALL, 'C.UTF-8', 'C');
1053
+            setlocale(LC_CTYPE, 'en_US.UTF-8', 'fr_FR.UTF-8', 'es_ES.UTF-8', 'de_DE.UTF-8', 'ru_RU.UTF-8', 'pt_BR.UTF-8', 'it_IT.UTF-8', 'ja_JP.UTF-8', 'zh_CN.UTF-8', '0');
1054
+
1055
+            // Check again
1056
+            if (self::isNonUTF8Locale()) {
1057
+                return false;
1058
+            }
1059
+        }
1060
+
1061
+        return true;
1062
+    }
1063
+
1064
+    /**
1065
+     * Check if it's possible to get the inline annotations
1066
+     *
1067
+     * @return bool
1068
+     */
1069
+    public static function isAnnotationsWorking() {
1070
+        $reflection = new \ReflectionMethod(__METHOD__);
1071
+        $docs = $reflection->getDocComment();
1072
+
1073
+        return (is_string($docs) && strlen($docs) > 50);
1074
+    }
1075
+
1076
+    /**
1077
+     * Check if the PHP module fileinfo is loaded.
1078
+     *
1079
+     * @return bool
1080
+     */
1081
+    public static function fileInfoLoaded() {
1082
+        return function_exists('finfo_open');
1083
+    }
1084
+
1085
+    /**
1086
+     * clear all levels of output buffering
1087
+     *
1088
+     * @return void
1089
+     */
1090
+    public static function obEnd() {
1091
+        while (ob_get_level()) {
1092
+            ob_end_clean();
1093
+        }
1094
+    }
1095
+
1096
+    /**
1097
+     * Checks whether the server is running on Mac OS X
1098
+     *
1099
+     * @return bool true if running on Mac OS X, false otherwise
1100
+     */
1101
+    public static function runningOnMac() {
1102
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1103
+    }
1104
+
1105
+    /**
1106
+     * Handles the case that there may not be a theme, then check if a "default"
1107
+     * theme exists and take that one
1108
+     *
1109
+     * @return string the theme
1110
+     */
1111
+    public static function getTheme() {
1112
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1113
+
1114
+        if ($theme === '') {
1115
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1116
+                $theme = 'default';
1117
+            }
1118
+        }
1119
+
1120
+        return $theme;
1121
+    }
1122
+
1123
+    /**
1124
+     * Normalize a unicode string
1125
+     *
1126
+     * @param string $value a not normalized string
1127
+     * @return bool|string
1128
+     */
1129
+    public static function normalizeUnicode($value) {
1130
+        if (Normalizer::isNormalized($value)) {
1131
+            return $value;
1132
+        }
1133
+
1134
+        $normalizedValue = Normalizer::normalize($value);
1135
+        if ($normalizedValue === null || $normalizedValue === false) {
1136
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1137
+            return $value;
1138
+        }
1139
+
1140
+        return $normalizedValue;
1141
+    }
1142
+
1143
+    /**
1144
+     * A human readable string is generated based on version and build number
1145
+     *
1146
+     * @return string
1147
+     */
1148
+    public static function getHumanVersion() {
1149
+        $version = OC_Util::getVersionString();
1150
+        $build = OC_Util::getBuild();
1151
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1152
+            $version .= ' Build:' . $build;
1153
+        }
1154
+        return $version;
1155
+    }
1156
+
1157
+    /**
1158
+     * Returns whether the given file name is valid
1159
+     *
1160
+     * @param string $file file name to check
1161
+     * @return bool true if the file name is valid, false otherwise
1162
+     * @deprecated use \OC\Files\View::verifyPath()
1163
+     */
1164
+    public static function isValidFileName($file) {
1165
+        $trimmed = trim($file);
1166
+        if ($trimmed === '') {
1167
+            return false;
1168
+        }
1169
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1170
+            return false;
1171
+        }
1172
+
1173
+        // detect part files
1174
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1175
+            return false;
1176
+        }
1177
+
1178
+        foreach (str_split($trimmed) as $char) {
1179
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1180
+                return false;
1181
+            }
1182
+        }
1183
+        return true;
1184
+    }
1185
+
1186
+    /**
1187
+     * Check whether the instance needs to perform an upgrade,
1188
+     * either when the core version is higher or any app requires
1189
+     * an upgrade.
1190
+     *
1191
+     * @param \OC\SystemConfig $config
1192
+     * @return bool whether the core or any app needs an upgrade
1193
+     * @throws \OCP\HintException When the upgrade from the given version is not allowed
1194
+     */
1195
+    public static function needUpgrade(\OC\SystemConfig $config) {
1196
+        if ($config->getValue('installed', false)) {
1197
+            $installedVersion = $config->getValue('version', '0.0.0');
1198
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1199
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1200
+            if ($versionDiff > 0) {
1201
+                return true;
1202
+            } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1203
+                // downgrade with debug
1204
+                $installedMajor = explode('.', $installedVersion);
1205
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1206
+                $currentMajor = explode('.', $currentVersion);
1207
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1208
+                if ($installedMajor === $currentMajor) {
1209
+                    // Same major, allow downgrade for developers
1210
+                    return true;
1211
+                } else {
1212
+                    // downgrade attempt, throw exception
1213
+                    throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1214
+                }
1215
+            } elseif ($versionDiff < 0) {
1216
+                // downgrade attempt, throw exception
1217
+                throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1218
+            }
1219
+
1220
+            // also check for upgrades for apps (independently from the user)
1221
+            $apps = \OC_App::getEnabledApps(false, true);
1222
+            $shouldUpgrade = false;
1223
+            foreach ($apps as $app) {
1224
+                if (\OC_App::shouldUpgrade($app)) {
1225
+                    $shouldUpgrade = true;
1226
+                    break;
1227
+                }
1228
+            }
1229
+            return $shouldUpgrade;
1230
+        } else {
1231
+            return false;
1232
+        }
1233
+    }
1234 1234
 }
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 		/** @var LoggerInterface $logger */
184 184
 		$logger = \OC::$server->get(LoggerInterface::class);
185 185
 
186
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
186
+		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT.'/core/skeleton');
187 187
 		$userLang = \OC::$server->getL10NFactory()->findLanguage();
188 188
 		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
189 189
 
@@ -205,9 +205,9 @@  discard block
 block discarded – undo
205 205
 		if ($instanceId === null) {
206 206
 			throw new \RuntimeException('no instance id!');
207 207
 		}
208
-		$appdata = 'appdata_' . $instanceId;
208
+		$appdata = 'appdata_'.$instanceId;
209 209
 		if ($userId === $appdata) {
210
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
210
+			throw new \RuntimeException('username is reserved name: '.$appdata);
211 211
 		}
212 212
 
213 213
 		if (!empty($skeletonDirectory)) {
@@ -242,14 +242,14 @@  discard block
 block discarded – undo
242 242
 		// Copy the files
243 243
 		while (false !== ($file = readdir($dir))) {
244 244
 			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
245
-				if (is_dir($source . '/' . $file)) {
245
+				if (is_dir($source.'/'.$file)) {
246 246
 					$child = $target->newFolder($file);
247
-					self::copyr($source . '/' . $file, $child);
247
+					self::copyr($source.'/'.$file, $child);
248 248
 				} else {
249 249
 					$child = $target->newFile($file);
250
-					$sourceStream = fopen($source . '/' . $file, 'r');
250
+					$sourceStream = fopen($source.'/'.$file, 'r');
251 251
 					if ($sourceStream === false) {
252
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
252
+						$logger->error(sprintf('Could not fopen "%s"', $source.'/'.$file), ['app' => 'core']);
253 253
 						closedir($dir);
254 254
 						return;
255 255
 					}
@@ -325,8 +325,8 @@  discard block
 block discarded – undo
325 325
 			return;
326 326
 		}
327 327
 
328
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
329
-		require OC::$SERVERROOT . '/version.php';
328
+		$timestamp = filemtime(OC::$SERVERROOT.'/version.php');
329
+		require OC::$SERVERROOT.'/version.php';
330 330
 		/** @var int $timestamp */
331 331
 		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
332 332
 		/** @var string $OC_Version */
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
 	public static function checkServer(\OC\SystemConfig $config) {
501 501
 		$l = \OC::$server->getL10N('lib');
502 502
 		$errors = [];
503
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
503
+		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT.'/data');
504 504
 
505 505
 		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
506 506
 			// this check needs to be done every time
@@ -540,9 +540,9 @@  discard block
 block discarded – undo
540 540
 				$errors[] = [
541 541
 					'error' => $l->t('Cannot write into "config" directory.'),
542 542
 					'hint' => $l->t('This can usually be fixed by giving the web server write access to the config directory. See %s',
543
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
543
+						[$urlGenerator->linkToDocs('admin-dir_permissions')]).'. '
544 544
 						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
545
-						[ $urlGenerator->linkToDocs('admin-config') ])
545
+						[$urlGenerator->linkToDocs('admin-config')])
546 546
 				];
547 547
 			}
548 548
 		}
@@ -716,7 +716,7 @@  discard block
 block discarded – undo
716 716
 			$version -= ($minor * 100);
717 717
 			$patch = $version;
718 718
 			$errors[] = [
719
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
719
+				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major.'.'.$minor.'.'.$patch]),
720 720
 				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
721 721
 			];
722 722
 		}
@@ -819,10 +819,10 @@  discard block
 block discarded – undo
819 819
 				'hint' => $l->t('Check the value of "datadirectory" in your configuration.')
820 820
 			];
821 821
 		}
822
-		if (!file_exists($dataDirectory . '/.ocdata')) {
822
+		if (!file_exists($dataDirectory.'/.ocdata')) {
823 823
 			$errors[] = [
824 824
 				'error' => $l->t('Your data directory is invalid.'),
825
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
825
+				'hint' => $l->t('Ensure there is a file called ".ocdata"'.
826 826
 					' in the root of the data directory.')
827 827
 			];
828 828
 		}
@@ -838,7 +838,7 @@  discard block
 block discarded – undo
838 838
 	public static function checkLoggedIn() {
839 839
 		// Check if we are a user
840 840
 		if (!\OC::$server->getUserSession()->isLoggedIn()) {
841
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
841
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute(
842 842
 						'core.login.showLoginForm',
843 843
 						[
844 844
 							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
@@ -849,7 +849,7 @@  discard block
 block discarded – undo
849 849
 		}
850 850
 		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
851 851
 		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
852
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
852
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
853 853
 			exit();
854 854
 		}
855 855
 	}
@@ -862,7 +862,7 @@  discard block
 block discarded – undo
862 862
 	public static function checkAdminUser() {
863 863
 		OC_Util::checkLoggedIn();
864 864
 		if (!OC_User::isAdminUser(OC_User::getUser())) {
865
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
865
+			header('Location: '.\OCP\Util::linkToAbsolute('', 'index.php'));
866 866
 			exit();
867 867
 		}
868 868
 	}
@@ -888,7 +888,7 @@  discard block
 block discarded – undo
888 888
 	 */
889 889
 	public static function redirectToDefaultPage() {
890 890
 		$location = self::getDefaultPageUrl();
891
-		header('Location: ' . $location);
891
+		header('Location: '.$location);
892 892
 		exit();
893 893
 	}
894 894
 
@@ -901,7 +901,7 @@  discard block
 block discarded – undo
901 901
 		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
902 902
 		if (is_null($id)) {
903 903
 			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
904
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
904
+			$id = 'oc'.\OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
905 905
 			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
906 906
 		}
907 907
 		return $id;
@@ -919,12 +919,12 @@  discard block
 block discarded – undo
919 919
 	public static function sanitizeHTML($value) {
920 920
 		if (is_array($value)) {
921 921
 			/** @var string[] $value */
922
-			$value = array_map(function ($value) {
922
+			$value = array_map(function($value) {
923 923
 				return self::sanitizeHTML($value);
924 924
 			}, $value);
925 925
 		} else {
926 926
 			// Specify encoding for PHP<5.4
927
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
927
+			$value = htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
928 928
 		}
929 929
 		return $value;
930 930
 	}
@@ -957,7 +957,7 @@  discard block
 block discarded – undo
957 957
 		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
958 958
 
959 959
 		// creating a test file
960
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
960
+		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$fileName;
961 961
 
962 962
 		if (file_exists($testFile)) {// already running this test, possible recursive call
963 963
 			return false;
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
 		$fp = @fopen($testFile, 'w');
967 967
 		if (!$fp) {
968 968
 			throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.',
969
-				'Make sure it is possible for the web server to write to ' . $testFile);
969
+				'Make sure it is possible for the web server to write to '.$testFile);
970 970
 		}
971 971
 		fwrite($fp, $testContent);
972 972
 		fclose($fp);
@@ -993,10 +993,10 @@  discard block
 block discarded – undo
993 993
 		}
994 994
 
995 995
 		$fileName = '/htaccesstest.txt';
996
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
996
+		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$fileName;
997 997
 
998 998
 		// accessing the file via http
999
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
999
+		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT.'/data'.$fileName);
1000 1000
 		try {
1001 1001
 			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1002 1002
 		} catch (\Exception $e) {
@@ -1004,9 +1004,9 @@  discard block
 block discarded – undo
1004 1004
 		}
1005 1005
 
1006 1006
 		if (strpos($url, 'https:') === 0) {
1007
-			$url = 'http:' . substr($url, 6);
1007
+			$url = 'http:'.substr($url, 6);
1008 1008
 		} else {
1009
-			$url = 'https:' . substr($url, 5);
1009
+			$url = 'https:'.substr($url, 5);
1010 1010
 		}
1011 1011
 
1012 1012
 		try {
@@ -1112,7 +1112,7 @@  discard block
 block discarded – undo
1112 1112
 		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1113 1113
 
1114 1114
 		if ($theme === '') {
1115
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1115
+			if (is_dir(OC::$SERVERROOT.'/themes/default')) {
1116 1116
 				$theme = 'default';
1117 1117
 			}
1118 1118
 		}
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
 
1134 1134
 		$normalizedValue = Normalizer::normalize($value);
1135 1135
 		if ($normalizedValue === null || $normalizedValue === false) {
1136
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1136
+			\OC::$server->getLogger()->warning('normalizing failed for "'.$value.'"', ['app' => 'core']);
1137 1137
 			return $value;
1138 1138
 		}
1139 1139
 
@@ -1149,7 +1149,7 @@  discard block
 block discarded – undo
1149 1149
 		$version = OC_Util::getVersionString();
1150 1150
 		$build = OC_Util::getBuild();
1151 1151
 		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1152
-			$version .= ' Build:' . $build;
1152
+			$version .= ' Build:'.$build;
1153 1153
 		}
1154 1154
 		return $version;
1155 1155
 	}
@@ -1171,7 +1171,7 @@  discard block
 block discarded – undo
1171 1171
 		}
1172 1172
 
1173 1173
 		// detect part files
1174
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1174
+		if (preg_match('/'.\OCP\Files\FileInfo::BLACKLIST_FILES_REGEX.'/', $trimmed) !== 0) {
1175 1175
 			return false;
1176 1176
 		}
1177 1177
 
@@ -1202,19 +1202,19 @@  discard block
 block discarded – undo
1202 1202
 			} elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1203 1203
 				// downgrade with debug
1204 1204
 				$installedMajor = explode('.', $installedVersion);
1205
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1205
+				$installedMajor = $installedMajor[0].'.'.$installedMajor[1];
1206 1206
 				$currentMajor = explode('.', $currentVersion);
1207
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1207
+				$currentMajor = $currentMajor[0].'.'.$currentMajor[1];
1208 1208
 				if ($installedMajor === $currentMajor) {
1209 1209
 					// Same major, allow downgrade for developers
1210 1210
 					return true;
1211 1211
 				} else {
1212 1212
 					// downgrade attempt, throw exception
1213
-					throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1213
+					throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
1214 1214
 				}
1215 1215
 			} elseif ($versionDiff < 0) {
1216 1216
 				// downgrade attempt, throw exception
1217
-				throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1217
+				throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
1218 1218
 			}
1219 1219
 
1220 1220
 			// also check for upgrades for apps (independently from the user)
Please login to merge, or discard this patch.
lib/private/Server.php 2 patches
Indentation   +2086 added lines, -2086 removed lines patch added patch discarded remove patch
@@ -266,2095 +266,2095 @@
 block discarded – undo
266 266
  */
267 267
 class Server extends ServerContainer implements IServerContainer {
268 268
 
269
-	/** @var string */
270
-	private $webRoot;
271
-
272
-	/**
273
-	 * @param string $webRoot
274
-	 * @param \OC\Config $config
275
-	 */
276
-	public function __construct($webRoot, \OC\Config $config) {
277
-		parent::__construct();
278
-		$this->webRoot = $webRoot;
279
-
280
-		// To find out if we are running from CLI or not
281
-		$this->registerParameter('isCLI', \OC::$CLI);
282
-		$this->registerParameter('serverRoot', \OC::$SERVERROOT);
283
-
284
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
285
-			return $c;
286
-		});
287
-		$this->registerService(\OCP\IServerContainer::class, function (ContainerInterface $c) {
288
-			return $c;
289
-		});
290
-
291
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
292
-		/** @deprecated 19.0.0 */
293
-		$this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
294
-
295
-		$this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
296
-		/** @deprecated 19.0.0 */
297
-		$this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
298
-
299
-		$this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
300
-		/** @deprecated 19.0.0 */
301
-		$this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
302
-
303
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
304
-		/** @deprecated 19.0.0 */
305
-		$this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
306
-
307
-		$this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
308
-		$this->registerAlias(ITemplateManager::class, TemplateManager::class);
309
-
310
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
311
-
312
-		$this->registerService(View::class, function (Server $c) {
313
-			return new View();
314
-		}, false);
315
-
316
-		$this->registerService(IPreview::class, function (ContainerInterface $c) {
317
-			return new PreviewManager(
318
-				$c->get(\OCP\IConfig::class),
319
-				$c->get(IRootFolder::class),
320
-				new \OC\Preview\Storage\Root(
321
-					$c->get(IRootFolder::class),
322
-					$c->get(SystemConfig::class)
323
-				),
324
-				$c->get(SymfonyAdapter::class),
325
-				$c->get(GeneratorHelper::class),
326
-				$c->get(ISession::class)->get('user_id'),
327
-				$c->get(Coordinator::class),
328
-				$c->get(IServerContainer::class)
329
-			);
330
-		});
331
-		/** @deprecated 19.0.0 */
332
-		$this->registerDeprecatedAlias('PreviewManager', IPreview::class);
333
-
334
-		$this->registerService(\OC\Preview\Watcher::class, function (ContainerInterface $c) {
335
-			return new \OC\Preview\Watcher(
336
-				new \OC\Preview\Storage\Root(
337
-					$c->get(IRootFolder::class),
338
-					$c->get(SystemConfig::class)
339
-				)
340
-			);
341
-		});
342
-
343
-		$this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
344
-			$view = new View();
345
-			$util = new Encryption\Util(
346
-				$view,
347
-				$c->get(IUserManager::class),
348
-				$c->get(IGroupManager::class),
349
-				$c->get(\OCP\IConfig::class)
350
-			);
351
-			return new Encryption\Manager(
352
-				$c->get(\OCP\IConfig::class),
353
-				$c->get(ILogger::class),
354
-				$c->getL10N('core'),
355
-				new View(),
356
-				$util,
357
-				new ArrayCache()
358
-			);
359
-		});
360
-		/** @deprecated 19.0.0 */
361
-		$this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
362
-
363
-		/** @deprecated 21.0.0 */
364
-		$this->registerDeprecatedAlias('EncryptionFileHelper', IFile::class);
365
-		$this->registerService(IFile::class, function (ContainerInterface $c) {
366
-			$util = new Encryption\Util(
367
-				new View(),
368
-				$c->get(IUserManager::class),
369
-				$c->get(IGroupManager::class),
370
-				$c->get(\OCP\IConfig::class)
371
-			);
372
-			return new Encryption\File(
373
-				$util,
374
-				$c->get(IRootFolder::class),
375
-				$c->get(\OCP\Share\IManager::class)
376
-			);
377
-		});
378
-
379
-		/** @deprecated 21.0.0 */
380
-		$this->registerDeprecatedAlias('EncryptionKeyStorage', IStorage::class);
381
-		$this->registerService(IStorage::class, function (ContainerInterface $c) {
382
-			$view = new View();
383
-			$util = new Encryption\Util(
384
-				$view,
385
-				$c->get(IUserManager::class),
386
-				$c->get(IGroupManager::class),
387
-				$c->get(\OCP\IConfig::class)
388
-			);
389
-
390
-			return new Encryption\Keys\Storage(
391
-				$view,
392
-				$util,
393
-				$c->get(ICrypto::class),
394
-				$c->get(\OCP\IConfig::class)
395
-			);
396
-		});
397
-		/** @deprecated 20.0.0 */
398
-		$this->registerDeprecatedAlias('TagMapper', TagMapper::class);
399
-
400
-		$this->registerAlias(\OCP\ITagManager::class, TagManager::class);
401
-		/** @deprecated 19.0.0 */
402
-		$this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
403
-
404
-		$this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
405
-			/** @var \OCP\IConfig $config */
406
-			$config = $c->get(\OCP\IConfig::class);
407
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
408
-			return new $factoryClass($this);
409
-		});
410
-		$this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
411
-			return $c->get('SystemTagManagerFactory')->getManager();
412
-		});
413
-		/** @deprecated 19.0.0 */
414
-		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
415
-
416
-		$this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
417
-			return $c->get('SystemTagManagerFactory')->getObjectMapper();
418
-		});
419
-		$this->registerService('RootFolder', function (ContainerInterface $c) {
420
-			$manager = \OC\Files\Filesystem::getMountManager(null);
421
-			$view = new View();
422
-			$root = new Root(
423
-				$manager,
424
-				$view,
425
-				null,
426
-				$c->get(IUserMountCache::class),
427
-				$this->get(ILogger::class),
428
-				$this->get(IUserManager::class),
429
-				$this->get(IEventDispatcher::class),
430
-			);
431
-
432
-			$previewConnector = new \OC\Preview\WatcherConnector(
433
-				$root,
434
-				$c->get(SystemConfig::class)
435
-			);
436
-			$previewConnector->connectWatcher();
437
-
438
-			return $root;
439
-		});
440
-		$this->registerService(HookConnector::class, function (ContainerInterface $c) {
441
-			return new HookConnector(
442
-				$c->get(IRootFolder::class),
443
-				new View(),
444
-				$c->get(\OC\EventDispatcher\SymfonyAdapter::class),
445
-				$c->get(IEventDispatcher::class)
446
-			);
447
-		});
448
-
449
-		/** @deprecated 19.0.0 */
450
-		$this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
451
-
452
-		$this->registerService(IRootFolder::class, function (ContainerInterface $c) {
453
-			return new LazyRoot(function () use ($c) {
454
-				return $c->get('RootFolder');
455
-			});
456
-		});
457
-		/** @deprecated 19.0.0 */
458
-		$this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
459
-
460
-		/** @deprecated 19.0.0 */
461
-		$this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
462
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
463
-
464
-		$this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
465
-			$groupManager = new \OC\Group\Manager($this->get(IUserManager::class), $c->get(SymfonyAdapter::class), $this->get(ILogger::class));
466
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
467
-				/** @var IEventDispatcher $dispatcher */
468
-				$dispatcher = $this->get(IEventDispatcher::class);
469
-				$dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
470
-			});
471
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
472
-				/** @var IEventDispatcher $dispatcher */
473
-				$dispatcher = $this->get(IEventDispatcher::class);
474
-				$dispatcher->dispatchTyped(new GroupCreatedEvent($group));
475
-			});
476
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
477
-				/** @var IEventDispatcher $dispatcher */
478
-				$dispatcher = $this->get(IEventDispatcher::class);
479
-				$dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
480
-			});
481
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
482
-				/** @var IEventDispatcher $dispatcher */
483
-				$dispatcher = $this->get(IEventDispatcher::class);
484
-				$dispatcher->dispatchTyped(new GroupDeletedEvent($group));
485
-			});
486
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
487
-				/** @var IEventDispatcher $dispatcher */
488
-				$dispatcher = $this->get(IEventDispatcher::class);
489
-				$dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
490
-			});
491
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
492
-				/** @var IEventDispatcher $dispatcher */
493
-				$dispatcher = $this->get(IEventDispatcher::class);
494
-				$dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
495
-			});
496
-			$groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
497
-				/** @var IEventDispatcher $dispatcher */
498
-				$dispatcher = $this->get(IEventDispatcher::class);
499
-				$dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
500
-			});
501
-			$groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
502
-				/** @var IEventDispatcher $dispatcher */
503
-				$dispatcher = $this->get(IEventDispatcher::class);
504
-				$dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
505
-			});
506
-			return $groupManager;
507
-		});
508
-		/** @deprecated 19.0.0 */
509
-		$this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
510
-
511
-		$this->registerService(Store::class, function (ContainerInterface $c) {
512
-			$session = $c->get(ISession::class);
513
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
514
-				$tokenProvider = $c->get(IProvider::class);
515
-			} else {
516
-				$tokenProvider = null;
517
-			}
518
-			$logger = $c->get(LoggerInterface::class);
519
-			return new Store($session, $logger, $tokenProvider);
520
-		});
521
-		$this->registerAlias(IStore::class, Store::class);
522
-		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
523
-
524
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
525
-			$manager = $c->get(IUserManager::class);
526
-			$session = new \OC\Session\Memory('');
527
-			$timeFactory = new TimeFactory();
528
-			// Token providers might require a working database. This code
529
-			// might however be called when Nextcloud is not yet setup.
530
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
531
-				$provider = $c->get(IProvider::class);
532
-			} else {
533
-				$provider = null;
534
-			}
535
-
536
-			$legacyDispatcher = $c->get(SymfonyAdapter::class);
537
-
538
-			$userSession = new \OC\User\Session(
539
-				$manager,
540
-				$session,
541
-				$timeFactory,
542
-				$provider,
543
-				$c->get(\OCP\IConfig::class),
544
-				$c->get(ISecureRandom::class),
545
-				$c->getLockdownManager(),
546
-				$c->get(ILogger::class),
547
-				$c->get(IEventDispatcher::class)
548
-			);
549
-			/** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
550
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
551
-				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
552
-			});
553
-			/** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
554
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
555
-				/** @var \OC\User\User $user */
556
-				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
557
-			});
558
-			/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
559
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
560
-				/** @var \OC\User\User $user */
561
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
562
-				$legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
563
-			});
564
-			/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
565
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
566
-				/** @var \OC\User\User $user */
567
-				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
568
-			});
569
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
570
-				/** @var \OC\User\User $user */
571
-				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
572
-
573
-				/** @var IEventDispatcher $dispatcher */
574
-				$dispatcher = $this->get(IEventDispatcher::class);
575
-				$dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
576
-			});
577
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
578
-				/** @var \OC\User\User $user */
579
-				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
580
-
581
-				/** @var IEventDispatcher $dispatcher */
582
-				$dispatcher = $this->get(IEventDispatcher::class);
583
-				$dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
584
-			});
585
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
586
-				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
587
-
588
-				/** @var IEventDispatcher $dispatcher */
589
-				$dispatcher = $this->get(IEventDispatcher::class);
590
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
591
-			});
592
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
593
-				/** @var \OC\User\User $user */
594
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
595
-
596
-				/** @var IEventDispatcher $dispatcher */
597
-				$dispatcher = $this->get(IEventDispatcher::class);
598
-				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
599
-			});
600
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
601
-				/** @var IEventDispatcher $dispatcher */
602
-				$dispatcher = $this->get(IEventDispatcher::class);
603
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
604
-			});
605
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
606
-				/** @var \OC\User\User $user */
607
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
608
-
609
-				/** @var IEventDispatcher $dispatcher */
610
-				$dispatcher = $this->get(IEventDispatcher::class);
611
-				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
612
-			});
613
-			$userSession->listen('\OC\User', 'logout', function ($user) {
614
-				\OC_Hook::emit('OC_User', 'logout', []);
615
-
616
-				/** @var IEventDispatcher $dispatcher */
617
-				$dispatcher = $this->get(IEventDispatcher::class);
618
-				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
619
-			});
620
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
621
-				/** @var IEventDispatcher $dispatcher */
622
-				$dispatcher = $this->get(IEventDispatcher::class);
623
-				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
624
-			});
625
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
626
-				/** @var \OC\User\User $user */
627
-				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
628
-
629
-				/** @var IEventDispatcher $dispatcher */
630
-				$dispatcher = $this->get(IEventDispatcher::class);
631
-				$dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
632
-			});
633
-			return $userSession;
634
-		});
635
-		$this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
636
-		/** @deprecated 19.0.0 */
637
-		$this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
638
-
639
-		$this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
640
-
641
-		$this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
642
-		/** @deprecated 19.0.0 */
643
-		$this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
644
-
645
-		/** @deprecated 19.0.0 */
646
-		$this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
647
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
648
-
649
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
650
-			return new \OC\SystemConfig($config);
651
-		});
652
-		/** @deprecated 19.0.0 */
653
-		$this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
654
-
655
-		/** @deprecated 19.0.0 */
656
-		$this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
657
-		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
658
-
659
-		$this->registerService(IFactory::class, function (Server $c) {
660
-			return new \OC\L10N\Factory(
661
-				$c->get(\OCP\IConfig::class),
662
-				$c->getRequest(),
663
-				$c->get(IUserSession::class),
664
-				\OC::$SERVERROOT
665
-			);
666
-		});
667
-		/** @deprecated 19.0.0 */
668
-		$this->registerDeprecatedAlias('L10NFactory', IFactory::class);
669
-
670
-		$this->registerAlias(IURLGenerator::class, URLGenerator::class);
671
-		/** @deprecated 19.0.0 */
672
-		$this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
673
-
674
-		/** @deprecated 19.0.0 */
675
-		$this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
676
-		/** @deprecated 19.0.0 */
677
-		$this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
678
-
679
-		$this->registerService(ICache::class, function ($c) {
680
-			return new Cache\File();
681
-		});
682
-		/** @deprecated 19.0.0 */
683
-		$this->registerDeprecatedAlias('UserCache', ICache::class);
684
-
685
-		$this->registerService(Factory::class, function (Server $c) {
686
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->get(ILogger::class),
687
-				ArrayCache::class,
688
-				ArrayCache::class,
689
-				ArrayCache::class
690
-			);
691
-			/** @var \OCP\IConfig $config */
692
-			$config = $c->get(\OCP\IConfig::class);
693
-
694
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
695
-				if (!$config->getSystemValueBool('log_query')) {
696
-					$v = \OC_App::getAppVersions();
697
-				} else {
698
-					// If the log_query is enabled, we can not get the app versions
699
-					// as that does a query, which will be logged and the logging
700
-					// depends on redis and here we are back again in the same function.
701
-					$v = [
702
-						'log_query' => 'enabled',
703
-					];
704
-				}
705
-				$v['core'] = implode(',', \OC_Util::getVersion());
706
-				$version = implode(',', $v);
707
-				$instanceId = \OC_Util::getInstanceId();
708
-				$path = \OC::$SERVERROOT;
709
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
710
-				return new \OC\Memcache\Factory($prefix, $c->get(ILogger::class),
711
-					$config->getSystemValue('memcache.local', null),
712
-					$config->getSystemValue('memcache.distributed', null),
713
-					$config->getSystemValue('memcache.locking', null),
714
-					$config->getSystemValueString('redis_log_file')
715
-				);
716
-			}
717
-			return $arrayCacheFactory;
718
-		});
719
-		/** @deprecated 19.0.0 */
720
-		$this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
721
-		$this->registerAlias(ICacheFactory::class, Factory::class);
722
-
723
-		$this->registerService('RedisFactory', function (Server $c) {
724
-			$systemConfig = $c->get(SystemConfig::class);
725
-			return new RedisFactory($systemConfig, $c->getEventLogger());
726
-		});
727
-
728
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
729
-			$l10n = $this->get(IFactory::class)->get('lib');
730
-			return new \OC\Activity\Manager(
731
-				$c->getRequest(),
732
-				$c->get(IUserSession::class),
733
-				$c->get(\OCP\IConfig::class),
734
-				$c->get(IValidator::class),
735
-				$l10n
736
-			);
737
-		});
738
-		/** @deprecated 19.0.0 */
739
-		$this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
740
-
741
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
742
-			return new \OC\Activity\EventMerger(
743
-				$c->getL10N('lib')
744
-			);
745
-		});
746
-		$this->registerAlias(IValidator::class, Validator::class);
747
-
748
-		$this->registerService(AvatarManager::class, function (Server $c) {
749
-			return new AvatarManager(
750
-				$c->get(IUserSession::class),
751
-				$c->get(\OC\User\Manager::class),
752
-				$c->getAppDataDir('avatar'),
753
-				$c->getL10N('lib'),
754
-				$c->get(LoggerInterface::class),
755
-				$c->get(\OCP\IConfig::class),
756
-				$c->get(IAccountManager::class),
757
-				$c->get(KnownUserService::class)
758
-			);
759
-		});
760
-		$this->registerAlias(IAvatarManager::class, AvatarManager::class);
761
-		/** @deprecated 19.0.0 */
762
-		$this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
763
-
764
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
765
-		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
766
-
767
-		$this->registerService(\OC\Log::class, function (Server $c) {
768
-			$logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
769
-			$factory = new LogFactory($c, $this->get(SystemConfig::class));
770
-			$logger = $factory->get($logType);
771
-			$registry = $c->get(\OCP\Support\CrashReport\IRegistry::class);
772
-
773
-			return new Log($logger, $this->get(SystemConfig::class), null, $registry);
774
-		});
775
-		$this->registerAlias(ILogger::class, \OC\Log::class);
776
-		/** @deprecated 19.0.0 */
777
-		$this->registerDeprecatedAlias('Logger', \OC\Log::class);
778
-		// PSR-3 logger
779
-		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
780
-
781
-		$this->registerService(ILogFactory::class, function (Server $c) {
782
-			return new LogFactory($c, $this->get(SystemConfig::class));
783
-		});
784
-
785
-		$this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
786
-		/** @deprecated 19.0.0 */
787
-		$this->registerDeprecatedAlias('JobList', IJobList::class);
788
-
789
-		$this->registerService(Router::class, function (Server $c) {
790
-			$cacheFactory = $c->get(ICacheFactory::class);
791
-			$logger = $c->get(ILogger::class);
792
-			if ($cacheFactory->isLocalCacheAvailable()) {
793
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
794
-			} else {
795
-				$router = new \OC\Route\Router($logger);
796
-			}
797
-			return $router;
798
-		});
799
-		$this->registerAlias(IRouter::class, Router::class);
800
-		/** @deprecated 19.0.0 */
801
-		$this->registerDeprecatedAlias('Router', IRouter::class);
802
-
803
-		$this->registerAlias(ISearch::class, Search::class);
804
-		/** @deprecated 19.0.0 */
805
-		$this->registerDeprecatedAlias('Search', ISearch::class);
806
-
807
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
808
-			$cacheFactory = $c->get(ICacheFactory::class);
809
-			if ($cacheFactory->isAvailable()) {
810
-				$backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
811
-					$this->get(ICacheFactory::class),
812
-					new \OC\AppFramework\Utility\TimeFactory()
813
-				);
814
-			} else {
815
-				$backend = new \OC\Security\RateLimiting\Backend\DatabaseBackend(
816
-					$c->get(IDBConnection::class),
817
-					new \OC\AppFramework\Utility\TimeFactory()
818
-				);
819
-			}
820
-
821
-			return $backend;
822
-		});
823
-
824
-		$this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
825
-		/** @deprecated 19.0.0 */
826
-		$this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
827
-
828
-		$this->registerAlias(IVerificationToken::class, VerificationToken::class);
829
-
830
-		$this->registerAlias(ICrypto::class, Crypto::class);
831
-		/** @deprecated 19.0.0 */
832
-		$this->registerDeprecatedAlias('Crypto', ICrypto::class);
833
-
834
-		$this->registerAlias(IHasher::class, Hasher::class);
835
-		/** @deprecated 19.0.0 */
836
-		$this->registerDeprecatedAlias('Hasher', IHasher::class);
837
-
838
-		$this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
839
-		/** @deprecated 19.0.0 */
840
-		$this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
841
-
842
-		$this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
843
-		$this->registerService(Connection::class, function (Server $c) {
844
-			$systemConfig = $c->get(SystemConfig::class);
845
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
846
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
847
-			if (!$factory->isValidType($type)) {
848
-				throw new \OC\DatabaseException('Invalid database type');
849
-			}
850
-			$connectionParams = $factory->createConnectionParams();
851
-			$connection = $factory->getConnection($type, $connectionParams);
852
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
853
-			return $connection;
854
-		});
855
-		/** @deprecated 19.0.0 */
856
-		$this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
857
-
858
-		$this->registerAlias(ICertificateManager::class, CertificateManager::class);
859
-		$this->registerAlias(IClientService::class, ClientService::class);
860
-		$this->registerService(LocalAddressChecker::class, function (ContainerInterface $c) {
861
-			return new LocalAddressChecker(
862
-				$c->get(ILogger::class),
863
-			);
864
-		});
865
-		$this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
866
-			return new NegativeDnsCache(
867
-				$c->get(ICacheFactory::class),
868
-			);
869
-		});
870
-		$this->registerService(DnsPinMiddleware::class, function (ContainerInterface $c) {
871
-			return new DnsPinMiddleware(
872
-				$c->get(NegativeDnsCache::class),
873
-				$c->get(LocalAddressChecker::class)
874
-			);
875
-		});
876
-		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
877
-		$this->registerService(IEventLogger::class, function (ContainerInterface $c) {
878
-			return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
879
-		});
880
-		/** @deprecated 19.0.0 */
881
-		$this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
882
-
883
-		$this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
884
-			$queryLogger = new QueryLogger();
885
-			if ($c->get(SystemConfig::class)->getValue('debug', false)) {
886
-				// In debug mode, module is being activated by default
887
-				$queryLogger->activate();
888
-			}
889
-			return $queryLogger;
890
-		});
891
-		/** @deprecated 19.0.0 */
892
-		$this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
893
-
894
-		/** @deprecated 19.0.0 */
895
-		$this->registerDeprecatedAlias('TempManager', TempManager::class);
896
-		$this->registerAlias(ITempManager::class, TempManager::class);
897
-
898
-		$this->registerService(AppManager::class, function (ContainerInterface $c) {
899
-			// TODO: use auto-wiring
900
-			return new \OC\App\AppManager(
901
-				$c->get(IUserSession::class),
902
-				$c->get(\OCP\IConfig::class),
903
-				$c->get(\OC\AppConfig::class),
904
-				$c->get(IGroupManager::class),
905
-				$c->get(ICacheFactory::class),
906
-				$c->get(SymfonyAdapter::class),
907
-				$c->get(LoggerInterface::class)
908
-			);
909
-		});
910
-		/** @deprecated 19.0.0 */
911
-		$this->registerDeprecatedAlias('AppManager', AppManager::class);
912
-		$this->registerAlias(IAppManager::class, AppManager::class);
913
-
914
-		$this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
915
-		/** @deprecated 19.0.0 */
916
-		$this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
917
-
918
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
919
-			$language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
920
-
921
-			return new DateTimeFormatter(
922
-				$c->get(IDateTimeZone::class)->getTimeZone(),
923
-				$c->getL10N('lib', $language)
924
-			);
925
-		});
926
-		/** @deprecated 19.0.0 */
927
-		$this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
928
-
929
-		$this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
930
-			$mountCache = new UserMountCache(
931
-				$c->get(IDBConnection::class),
932
-				$c->get(IUserManager::class),
933
-				$c->get(ILogger::class)
934
-			);
935
-			$listener = new UserMountCacheListener($mountCache);
936
-			$listener->listen($c->get(IUserManager::class));
937
-			return $mountCache;
938
-		});
939
-		/** @deprecated 19.0.0 */
940
-		$this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
941
-
942
-		$this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
943
-			$loader = \OC\Files\Filesystem::getLoader();
944
-			$mountCache = $c->get(IUserMountCache::class);
945
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
946
-
947
-			// builtin providers
948
-
949
-			$config = $c->get(\OCP\IConfig::class);
950
-			$logger = $c->get(ILogger::class);
951
-			$manager->registerProvider(new CacheMountProvider($config));
952
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
953
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
954
-			$manager->registerRootProvider(new RootMountProvider($config, $c->get(LoggerInterface::class)));
955
-			$manager->registerRootProvider(new ObjectStorePreviewCacheMountProvider($logger, $config));
956
-
957
-			return $manager;
958
-		});
959
-		/** @deprecated 19.0.0 */
960
-		$this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
961
-
962
-		/** @deprecated 20.0.0 */
963
-		$this->registerDeprecatedAlias('IniWrapper', IniGetWrapper::class);
964
-		$this->registerService(IBus::class, function (ContainerInterface $c) {
965
-			$busClass = $c->get(\OCP\IConfig::class)->getSystemValue('commandbus');
966
-			if ($busClass) {
967
-				[$app, $class] = explode('::', $busClass, 2);
968
-				if ($c->get(IAppManager::class)->isInstalled($app)) {
969
-					\OC_App::loadApp($app);
970
-					return $c->get($class);
971
-				} else {
972
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
973
-				}
974
-			} else {
975
-				$jobList = $c->get(IJobList::class);
976
-				return new CronBus($jobList);
977
-			}
978
-		});
979
-		$this->registerDeprecatedAlias('AsyncCommandBus', IBus::class);
980
-		/** @deprecated 20.0.0 */
981
-		$this->registerDeprecatedAlias('TrustedDomainHelper', TrustedDomainHelper::class);
982
-		$this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
983
-		/** @deprecated 19.0.0 */
984
-		$this->registerDeprecatedAlias('Throttler', Throttler::class);
985
-		$this->registerService('IntegrityCodeChecker', function (ContainerInterface $c) {
986
-			// IConfig and IAppManager requires a working database. This code
987
-			// might however be called when ownCloud is not yet setup.
988
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
989
-				$config = $c->get(\OCP\IConfig::class);
990
-				$appManager = $c->get(IAppManager::class);
991
-			} else {
992
-				$config = null;
993
-				$appManager = null;
994
-			}
995
-
996
-			return new Checker(
997
-				new EnvironmentHelper(),
998
-				new FileAccessHelper(),
999
-				new AppLocator(),
1000
-				$config,
1001
-				$c->get(ICacheFactory::class),
1002
-				$appManager,
1003
-				$c->get(IMimeTypeDetector::class)
1004
-			);
1005
-		});
1006
-		$this->registerService(\OCP\IRequest::class, function (ContainerInterface $c) {
1007
-			if (isset($this['urlParams'])) {
1008
-				$urlParams = $this['urlParams'];
1009
-			} else {
1010
-				$urlParams = [];
1011
-			}
1012
-
1013
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
1014
-				&& in_array('fakeinput', stream_get_wrappers())
1015
-			) {
1016
-				$stream = 'fakeinput://data';
1017
-			} else {
1018
-				$stream = 'php://input';
1019
-			}
1020
-
1021
-			return new Request(
1022
-				[
1023
-					'get' => $_GET,
1024
-					'post' => $_POST,
1025
-					'files' => $_FILES,
1026
-					'server' => $_SERVER,
1027
-					'env' => $_ENV,
1028
-					'cookies' => $_COOKIE,
1029
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1030
-						? $_SERVER['REQUEST_METHOD']
1031
-						: '',
1032
-					'urlParams' => $urlParams,
1033
-				],
1034
-				$this->get(ISecureRandom::class),
1035
-				$this->get(\OCP\IConfig::class),
1036
-				$this->get(CsrfTokenManager::class),
1037
-				$stream
1038
-			);
1039
-		});
1040
-		/** @deprecated 19.0.0 */
1041
-		$this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
1042
-
1043
-		$this->registerService(IMailer::class, function (Server $c) {
1044
-			return new Mailer(
1045
-				$c->get(\OCP\IConfig::class),
1046
-				$c->get(ILogger::class),
1047
-				$c->get(Defaults::class),
1048
-				$c->get(IURLGenerator::class),
1049
-				$c->getL10N('lib'),
1050
-				$c->get(IEventDispatcher::class),
1051
-				$c->get(IFactory::class)
1052
-			);
1053
-		});
1054
-		/** @deprecated 19.0.0 */
1055
-		$this->registerDeprecatedAlias('Mailer', IMailer::class);
1056
-
1057
-		/** @deprecated 21.0.0 */
1058
-		$this->registerDeprecatedAlias('LDAPProvider', ILDAPProvider::class);
1059
-
1060
-		$this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
1061
-			$config = $c->get(\OCP\IConfig::class);
1062
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1063
-			if (is_null($factoryClass) || !class_exists($factoryClass)) {
1064
-				return new NullLDAPProviderFactory($this);
1065
-			}
1066
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1067
-			return new $factoryClass($this);
1068
-		});
1069
-		$this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
1070
-			$factory = $c->get(ILDAPProviderFactory::class);
1071
-			return $factory->getLDAPProvider();
1072
-		});
1073
-		$this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
1074
-			$ini = $c->get(IniGetWrapper::class);
1075
-			$config = $c->get(\OCP\IConfig::class);
1076
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1077
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1078
-				/** @var \OC\Memcache\Factory $memcacheFactory */
1079
-				$memcacheFactory = $c->get(ICacheFactory::class);
1080
-				$memcache = $memcacheFactory->createLocking('lock');
1081
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
1082
-					return new MemcacheLockingProvider($memcache, $ttl);
1083
-				}
1084
-				return new DBLockingProvider(
1085
-					$c->get(IDBConnection::class),
1086
-					$c->get(ILogger::class),
1087
-					new TimeFactory(),
1088
-					$ttl,
1089
-					!\OC::$CLI
1090
-				);
1091
-			}
1092
-			return new NoopLockingProvider();
1093
-		});
1094
-		/** @deprecated 19.0.0 */
1095
-		$this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1096
-
1097
-		$this->registerAlias(ILockdownManager::class, 'LockdownManager');
1098
-		$this->registerService(SetupManager::class, function ($c) {
1099
-			// create the setupmanager through the mount manager to resolve the cyclic dependency
1100
-			return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
1101
-		});
1102
-		$this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
1103
-		/** @deprecated 19.0.0 */
1104
-		$this->registerDeprecatedAlias('MountManager', IMountManager::class);
1105
-
1106
-		$this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
1107
-			return new \OC\Files\Type\Detection(
1108
-				$c->get(IURLGenerator::class),
1109
-				$c->get(ILogger::class),
1110
-				\OC::$configDir,
1111
-				\OC::$SERVERROOT . '/resources/config/'
1112
-			);
1113
-		});
1114
-		/** @deprecated 19.0.0 */
1115
-		$this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1116
-
1117
-		$this->registerAlias(IMimeTypeLoader::class, Loader::class);
1118
-		/** @deprecated 19.0.0 */
1119
-		$this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1120
-		$this->registerService(BundleFetcher::class, function () {
1121
-			return new BundleFetcher($this->getL10N('lib'));
1122
-		});
1123
-		$this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
1124
-		/** @deprecated 19.0.0 */
1125
-		$this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1126
-
1127
-		$this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
1128
-			$manager = new CapabilitiesManager($c->get(LoggerInterface::class));
1129
-			$manager->registerCapability(function () use ($c) {
1130
-				return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
1131
-			});
1132
-			$manager->registerCapability(function () use ($c) {
1133
-				return $c->get(\OC\Security\Bruteforce\Capabilities::class);
1134
-			});
1135
-			return $manager;
1136
-		});
1137
-		/** @deprecated 19.0.0 */
1138
-		$this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1139
-
1140
-		$this->registerService(ICommentsManager::class, function (Server $c) {
1141
-			$config = $c->get(\OCP\IConfig::class);
1142
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1143
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
1144
-			$factory = new $factoryClass($this);
1145
-			$manager = $factory->getManager();
1146
-
1147
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1148
-				$manager = $c->get(IUserManager::class);
1149
-				$user = $manager->get($id);
1150
-				if (is_null($user)) {
1151
-					$l = $c->getL10N('core');
1152
-					$displayName = $l->t('Unknown user');
1153
-				} else {
1154
-					$displayName = $user->getDisplayName();
1155
-				}
1156
-				return $displayName;
1157
-			});
1158
-
1159
-			return $manager;
1160
-		});
1161
-		/** @deprecated 19.0.0 */
1162
-		$this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1163
-
1164
-		$this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1165
-		$this->registerService('ThemingDefaults', function (Server $c) {
1166
-			/*
269
+    /** @var string */
270
+    private $webRoot;
271
+
272
+    /**
273
+     * @param string $webRoot
274
+     * @param \OC\Config $config
275
+     */
276
+    public function __construct($webRoot, \OC\Config $config) {
277
+        parent::__construct();
278
+        $this->webRoot = $webRoot;
279
+
280
+        // To find out if we are running from CLI or not
281
+        $this->registerParameter('isCLI', \OC::$CLI);
282
+        $this->registerParameter('serverRoot', \OC::$SERVERROOT);
283
+
284
+        $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
285
+            return $c;
286
+        });
287
+        $this->registerService(\OCP\IServerContainer::class, function (ContainerInterface $c) {
288
+            return $c;
289
+        });
290
+
291
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
292
+        /** @deprecated 19.0.0 */
293
+        $this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
294
+
295
+        $this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
296
+        /** @deprecated 19.0.0 */
297
+        $this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
298
+
299
+        $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
300
+        /** @deprecated 19.0.0 */
301
+        $this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
302
+
303
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
304
+        /** @deprecated 19.0.0 */
305
+        $this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
306
+
307
+        $this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
308
+        $this->registerAlias(ITemplateManager::class, TemplateManager::class);
309
+
310
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
311
+
312
+        $this->registerService(View::class, function (Server $c) {
313
+            return new View();
314
+        }, false);
315
+
316
+        $this->registerService(IPreview::class, function (ContainerInterface $c) {
317
+            return new PreviewManager(
318
+                $c->get(\OCP\IConfig::class),
319
+                $c->get(IRootFolder::class),
320
+                new \OC\Preview\Storage\Root(
321
+                    $c->get(IRootFolder::class),
322
+                    $c->get(SystemConfig::class)
323
+                ),
324
+                $c->get(SymfonyAdapter::class),
325
+                $c->get(GeneratorHelper::class),
326
+                $c->get(ISession::class)->get('user_id'),
327
+                $c->get(Coordinator::class),
328
+                $c->get(IServerContainer::class)
329
+            );
330
+        });
331
+        /** @deprecated 19.0.0 */
332
+        $this->registerDeprecatedAlias('PreviewManager', IPreview::class);
333
+
334
+        $this->registerService(\OC\Preview\Watcher::class, function (ContainerInterface $c) {
335
+            return new \OC\Preview\Watcher(
336
+                new \OC\Preview\Storage\Root(
337
+                    $c->get(IRootFolder::class),
338
+                    $c->get(SystemConfig::class)
339
+                )
340
+            );
341
+        });
342
+
343
+        $this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
344
+            $view = new View();
345
+            $util = new Encryption\Util(
346
+                $view,
347
+                $c->get(IUserManager::class),
348
+                $c->get(IGroupManager::class),
349
+                $c->get(\OCP\IConfig::class)
350
+            );
351
+            return new Encryption\Manager(
352
+                $c->get(\OCP\IConfig::class),
353
+                $c->get(ILogger::class),
354
+                $c->getL10N('core'),
355
+                new View(),
356
+                $util,
357
+                new ArrayCache()
358
+            );
359
+        });
360
+        /** @deprecated 19.0.0 */
361
+        $this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
362
+
363
+        /** @deprecated 21.0.0 */
364
+        $this->registerDeprecatedAlias('EncryptionFileHelper', IFile::class);
365
+        $this->registerService(IFile::class, function (ContainerInterface $c) {
366
+            $util = new Encryption\Util(
367
+                new View(),
368
+                $c->get(IUserManager::class),
369
+                $c->get(IGroupManager::class),
370
+                $c->get(\OCP\IConfig::class)
371
+            );
372
+            return new Encryption\File(
373
+                $util,
374
+                $c->get(IRootFolder::class),
375
+                $c->get(\OCP\Share\IManager::class)
376
+            );
377
+        });
378
+
379
+        /** @deprecated 21.0.0 */
380
+        $this->registerDeprecatedAlias('EncryptionKeyStorage', IStorage::class);
381
+        $this->registerService(IStorage::class, function (ContainerInterface $c) {
382
+            $view = new View();
383
+            $util = new Encryption\Util(
384
+                $view,
385
+                $c->get(IUserManager::class),
386
+                $c->get(IGroupManager::class),
387
+                $c->get(\OCP\IConfig::class)
388
+            );
389
+
390
+            return new Encryption\Keys\Storage(
391
+                $view,
392
+                $util,
393
+                $c->get(ICrypto::class),
394
+                $c->get(\OCP\IConfig::class)
395
+            );
396
+        });
397
+        /** @deprecated 20.0.0 */
398
+        $this->registerDeprecatedAlias('TagMapper', TagMapper::class);
399
+
400
+        $this->registerAlias(\OCP\ITagManager::class, TagManager::class);
401
+        /** @deprecated 19.0.0 */
402
+        $this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
403
+
404
+        $this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
405
+            /** @var \OCP\IConfig $config */
406
+            $config = $c->get(\OCP\IConfig::class);
407
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
408
+            return new $factoryClass($this);
409
+        });
410
+        $this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
411
+            return $c->get('SystemTagManagerFactory')->getManager();
412
+        });
413
+        /** @deprecated 19.0.0 */
414
+        $this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
415
+
416
+        $this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
417
+            return $c->get('SystemTagManagerFactory')->getObjectMapper();
418
+        });
419
+        $this->registerService('RootFolder', function (ContainerInterface $c) {
420
+            $manager = \OC\Files\Filesystem::getMountManager(null);
421
+            $view = new View();
422
+            $root = new Root(
423
+                $manager,
424
+                $view,
425
+                null,
426
+                $c->get(IUserMountCache::class),
427
+                $this->get(ILogger::class),
428
+                $this->get(IUserManager::class),
429
+                $this->get(IEventDispatcher::class),
430
+            );
431
+
432
+            $previewConnector = new \OC\Preview\WatcherConnector(
433
+                $root,
434
+                $c->get(SystemConfig::class)
435
+            );
436
+            $previewConnector->connectWatcher();
437
+
438
+            return $root;
439
+        });
440
+        $this->registerService(HookConnector::class, function (ContainerInterface $c) {
441
+            return new HookConnector(
442
+                $c->get(IRootFolder::class),
443
+                new View(),
444
+                $c->get(\OC\EventDispatcher\SymfonyAdapter::class),
445
+                $c->get(IEventDispatcher::class)
446
+            );
447
+        });
448
+
449
+        /** @deprecated 19.0.0 */
450
+        $this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
451
+
452
+        $this->registerService(IRootFolder::class, function (ContainerInterface $c) {
453
+            return new LazyRoot(function () use ($c) {
454
+                return $c->get('RootFolder');
455
+            });
456
+        });
457
+        /** @deprecated 19.0.0 */
458
+        $this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
459
+
460
+        /** @deprecated 19.0.0 */
461
+        $this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
462
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
463
+
464
+        $this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
465
+            $groupManager = new \OC\Group\Manager($this->get(IUserManager::class), $c->get(SymfonyAdapter::class), $this->get(ILogger::class));
466
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
467
+                /** @var IEventDispatcher $dispatcher */
468
+                $dispatcher = $this->get(IEventDispatcher::class);
469
+                $dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
470
+            });
471
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
472
+                /** @var IEventDispatcher $dispatcher */
473
+                $dispatcher = $this->get(IEventDispatcher::class);
474
+                $dispatcher->dispatchTyped(new GroupCreatedEvent($group));
475
+            });
476
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
477
+                /** @var IEventDispatcher $dispatcher */
478
+                $dispatcher = $this->get(IEventDispatcher::class);
479
+                $dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
480
+            });
481
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
482
+                /** @var IEventDispatcher $dispatcher */
483
+                $dispatcher = $this->get(IEventDispatcher::class);
484
+                $dispatcher->dispatchTyped(new GroupDeletedEvent($group));
485
+            });
486
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
487
+                /** @var IEventDispatcher $dispatcher */
488
+                $dispatcher = $this->get(IEventDispatcher::class);
489
+                $dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
490
+            });
491
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
492
+                /** @var IEventDispatcher $dispatcher */
493
+                $dispatcher = $this->get(IEventDispatcher::class);
494
+                $dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
495
+            });
496
+            $groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
497
+                /** @var IEventDispatcher $dispatcher */
498
+                $dispatcher = $this->get(IEventDispatcher::class);
499
+                $dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
500
+            });
501
+            $groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
502
+                /** @var IEventDispatcher $dispatcher */
503
+                $dispatcher = $this->get(IEventDispatcher::class);
504
+                $dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
505
+            });
506
+            return $groupManager;
507
+        });
508
+        /** @deprecated 19.0.0 */
509
+        $this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
510
+
511
+        $this->registerService(Store::class, function (ContainerInterface $c) {
512
+            $session = $c->get(ISession::class);
513
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
514
+                $tokenProvider = $c->get(IProvider::class);
515
+            } else {
516
+                $tokenProvider = null;
517
+            }
518
+            $logger = $c->get(LoggerInterface::class);
519
+            return new Store($session, $logger, $tokenProvider);
520
+        });
521
+        $this->registerAlias(IStore::class, Store::class);
522
+        $this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
523
+
524
+        $this->registerService(\OC\User\Session::class, function (Server $c) {
525
+            $manager = $c->get(IUserManager::class);
526
+            $session = new \OC\Session\Memory('');
527
+            $timeFactory = new TimeFactory();
528
+            // Token providers might require a working database. This code
529
+            // might however be called when Nextcloud is not yet setup.
530
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
531
+                $provider = $c->get(IProvider::class);
532
+            } else {
533
+                $provider = null;
534
+            }
535
+
536
+            $legacyDispatcher = $c->get(SymfonyAdapter::class);
537
+
538
+            $userSession = new \OC\User\Session(
539
+                $manager,
540
+                $session,
541
+                $timeFactory,
542
+                $provider,
543
+                $c->get(\OCP\IConfig::class),
544
+                $c->get(ISecureRandom::class),
545
+                $c->getLockdownManager(),
546
+                $c->get(ILogger::class),
547
+                $c->get(IEventDispatcher::class)
548
+            );
549
+            /** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
550
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
551
+                \OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
552
+            });
553
+            /** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
554
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
555
+                /** @var \OC\User\User $user */
556
+                \OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
557
+            });
558
+            /** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
559
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
560
+                /** @var \OC\User\User $user */
561
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
562
+                $legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
563
+            });
564
+            /** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
565
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
566
+                /** @var \OC\User\User $user */
567
+                \OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
568
+            });
569
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
570
+                /** @var \OC\User\User $user */
571
+                \OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
572
+
573
+                /** @var IEventDispatcher $dispatcher */
574
+                $dispatcher = $this->get(IEventDispatcher::class);
575
+                $dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
576
+            });
577
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
578
+                /** @var \OC\User\User $user */
579
+                \OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
580
+
581
+                /** @var IEventDispatcher $dispatcher */
582
+                $dispatcher = $this->get(IEventDispatcher::class);
583
+                $dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
584
+            });
585
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
586
+                \OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
587
+
588
+                /** @var IEventDispatcher $dispatcher */
589
+                $dispatcher = $this->get(IEventDispatcher::class);
590
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
591
+            });
592
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
593
+                /** @var \OC\User\User $user */
594
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
595
+
596
+                /** @var IEventDispatcher $dispatcher */
597
+                $dispatcher = $this->get(IEventDispatcher::class);
598
+                $dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
599
+            });
600
+            $userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
601
+                /** @var IEventDispatcher $dispatcher */
602
+                $dispatcher = $this->get(IEventDispatcher::class);
603
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
604
+            });
605
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
606
+                /** @var \OC\User\User $user */
607
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
608
+
609
+                /** @var IEventDispatcher $dispatcher */
610
+                $dispatcher = $this->get(IEventDispatcher::class);
611
+                $dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
612
+            });
613
+            $userSession->listen('\OC\User', 'logout', function ($user) {
614
+                \OC_Hook::emit('OC_User', 'logout', []);
615
+
616
+                /** @var IEventDispatcher $dispatcher */
617
+                $dispatcher = $this->get(IEventDispatcher::class);
618
+                $dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
619
+            });
620
+            $userSession->listen('\OC\User', 'postLogout', function ($user) {
621
+                /** @var IEventDispatcher $dispatcher */
622
+                $dispatcher = $this->get(IEventDispatcher::class);
623
+                $dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
624
+            });
625
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
626
+                /** @var \OC\User\User $user */
627
+                \OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
628
+
629
+                /** @var IEventDispatcher $dispatcher */
630
+                $dispatcher = $this->get(IEventDispatcher::class);
631
+                $dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
632
+            });
633
+            return $userSession;
634
+        });
635
+        $this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
636
+        /** @deprecated 19.0.0 */
637
+        $this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
638
+
639
+        $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
640
+
641
+        $this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
642
+        /** @deprecated 19.0.0 */
643
+        $this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
644
+
645
+        /** @deprecated 19.0.0 */
646
+        $this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
647
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
648
+
649
+        $this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
650
+            return new \OC\SystemConfig($config);
651
+        });
652
+        /** @deprecated 19.0.0 */
653
+        $this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
654
+
655
+        /** @deprecated 19.0.0 */
656
+        $this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
657
+        $this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
658
+
659
+        $this->registerService(IFactory::class, function (Server $c) {
660
+            return new \OC\L10N\Factory(
661
+                $c->get(\OCP\IConfig::class),
662
+                $c->getRequest(),
663
+                $c->get(IUserSession::class),
664
+                \OC::$SERVERROOT
665
+            );
666
+        });
667
+        /** @deprecated 19.0.0 */
668
+        $this->registerDeprecatedAlias('L10NFactory', IFactory::class);
669
+
670
+        $this->registerAlias(IURLGenerator::class, URLGenerator::class);
671
+        /** @deprecated 19.0.0 */
672
+        $this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
673
+
674
+        /** @deprecated 19.0.0 */
675
+        $this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
676
+        /** @deprecated 19.0.0 */
677
+        $this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
678
+
679
+        $this->registerService(ICache::class, function ($c) {
680
+            return new Cache\File();
681
+        });
682
+        /** @deprecated 19.0.0 */
683
+        $this->registerDeprecatedAlias('UserCache', ICache::class);
684
+
685
+        $this->registerService(Factory::class, function (Server $c) {
686
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->get(ILogger::class),
687
+                ArrayCache::class,
688
+                ArrayCache::class,
689
+                ArrayCache::class
690
+            );
691
+            /** @var \OCP\IConfig $config */
692
+            $config = $c->get(\OCP\IConfig::class);
693
+
694
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
695
+                if (!$config->getSystemValueBool('log_query')) {
696
+                    $v = \OC_App::getAppVersions();
697
+                } else {
698
+                    // If the log_query is enabled, we can not get the app versions
699
+                    // as that does a query, which will be logged and the logging
700
+                    // depends on redis and here we are back again in the same function.
701
+                    $v = [
702
+                        'log_query' => 'enabled',
703
+                    ];
704
+                }
705
+                $v['core'] = implode(',', \OC_Util::getVersion());
706
+                $version = implode(',', $v);
707
+                $instanceId = \OC_Util::getInstanceId();
708
+                $path = \OC::$SERVERROOT;
709
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
710
+                return new \OC\Memcache\Factory($prefix, $c->get(ILogger::class),
711
+                    $config->getSystemValue('memcache.local', null),
712
+                    $config->getSystemValue('memcache.distributed', null),
713
+                    $config->getSystemValue('memcache.locking', null),
714
+                    $config->getSystemValueString('redis_log_file')
715
+                );
716
+            }
717
+            return $arrayCacheFactory;
718
+        });
719
+        /** @deprecated 19.0.0 */
720
+        $this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
721
+        $this->registerAlias(ICacheFactory::class, Factory::class);
722
+
723
+        $this->registerService('RedisFactory', function (Server $c) {
724
+            $systemConfig = $c->get(SystemConfig::class);
725
+            return new RedisFactory($systemConfig, $c->getEventLogger());
726
+        });
727
+
728
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
729
+            $l10n = $this->get(IFactory::class)->get('lib');
730
+            return new \OC\Activity\Manager(
731
+                $c->getRequest(),
732
+                $c->get(IUserSession::class),
733
+                $c->get(\OCP\IConfig::class),
734
+                $c->get(IValidator::class),
735
+                $l10n
736
+            );
737
+        });
738
+        /** @deprecated 19.0.0 */
739
+        $this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
740
+
741
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
742
+            return new \OC\Activity\EventMerger(
743
+                $c->getL10N('lib')
744
+            );
745
+        });
746
+        $this->registerAlias(IValidator::class, Validator::class);
747
+
748
+        $this->registerService(AvatarManager::class, function (Server $c) {
749
+            return new AvatarManager(
750
+                $c->get(IUserSession::class),
751
+                $c->get(\OC\User\Manager::class),
752
+                $c->getAppDataDir('avatar'),
753
+                $c->getL10N('lib'),
754
+                $c->get(LoggerInterface::class),
755
+                $c->get(\OCP\IConfig::class),
756
+                $c->get(IAccountManager::class),
757
+                $c->get(KnownUserService::class)
758
+            );
759
+        });
760
+        $this->registerAlias(IAvatarManager::class, AvatarManager::class);
761
+        /** @deprecated 19.0.0 */
762
+        $this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
763
+
764
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
765
+        $this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
766
+
767
+        $this->registerService(\OC\Log::class, function (Server $c) {
768
+            $logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
769
+            $factory = new LogFactory($c, $this->get(SystemConfig::class));
770
+            $logger = $factory->get($logType);
771
+            $registry = $c->get(\OCP\Support\CrashReport\IRegistry::class);
772
+
773
+            return new Log($logger, $this->get(SystemConfig::class), null, $registry);
774
+        });
775
+        $this->registerAlias(ILogger::class, \OC\Log::class);
776
+        /** @deprecated 19.0.0 */
777
+        $this->registerDeprecatedAlias('Logger', \OC\Log::class);
778
+        // PSR-3 logger
779
+        $this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
780
+
781
+        $this->registerService(ILogFactory::class, function (Server $c) {
782
+            return new LogFactory($c, $this->get(SystemConfig::class));
783
+        });
784
+
785
+        $this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
786
+        /** @deprecated 19.0.0 */
787
+        $this->registerDeprecatedAlias('JobList', IJobList::class);
788
+
789
+        $this->registerService(Router::class, function (Server $c) {
790
+            $cacheFactory = $c->get(ICacheFactory::class);
791
+            $logger = $c->get(ILogger::class);
792
+            if ($cacheFactory->isLocalCacheAvailable()) {
793
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
794
+            } else {
795
+                $router = new \OC\Route\Router($logger);
796
+            }
797
+            return $router;
798
+        });
799
+        $this->registerAlias(IRouter::class, Router::class);
800
+        /** @deprecated 19.0.0 */
801
+        $this->registerDeprecatedAlias('Router', IRouter::class);
802
+
803
+        $this->registerAlias(ISearch::class, Search::class);
804
+        /** @deprecated 19.0.0 */
805
+        $this->registerDeprecatedAlias('Search', ISearch::class);
806
+
807
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
808
+            $cacheFactory = $c->get(ICacheFactory::class);
809
+            if ($cacheFactory->isAvailable()) {
810
+                $backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
811
+                    $this->get(ICacheFactory::class),
812
+                    new \OC\AppFramework\Utility\TimeFactory()
813
+                );
814
+            } else {
815
+                $backend = new \OC\Security\RateLimiting\Backend\DatabaseBackend(
816
+                    $c->get(IDBConnection::class),
817
+                    new \OC\AppFramework\Utility\TimeFactory()
818
+                );
819
+            }
820
+
821
+            return $backend;
822
+        });
823
+
824
+        $this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
825
+        /** @deprecated 19.0.0 */
826
+        $this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
827
+
828
+        $this->registerAlias(IVerificationToken::class, VerificationToken::class);
829
+
830
+        $this->registerAlias(ICrypto::class, Crypto::class);
831
+        /** @deprecated 19.0.0 */
832
+        $this->registerDeprecatedAlias('Crypto', ICrypto::class);
833
+
834
+        $this->registerAlias(IHasher::class, Hasher::class);
835
+        /** @deprecated 19.0.0 */
836
+        $this->registerDeprecatedAlias('Hasher', IHasher::class);
837
+
838
+        $this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
839
+        /** @deprecated 19.0.0 */
840
+        $this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
841
+
842
+        $this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
843
+        $this->registerService(Connection::class, function (Server $c) {
844
+            $systemConfig = $c->get(SystemConfig::class);
845
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
846
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
847
+            if (!$factory->isValidType($type)) {
848
+                throw new \OC\DatabaseException('Invalid database type');
849
+            }
850
+            $connectionParams = $factory->createConnectionParams();
851
+            $connection = $factory->getConnection($type, $connectionParams);
852
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
853
+            return $connection;
854
+        });
855
+        /** @deprecated 19.0.0 */
856
+        $this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
857
+
858
+        $this->registerAlias(ICertificateManager::class, CertificateManager::class);
859
+        $this->registerAlias(IClientService::class, ClientService::class);
860
+        $this->registerService(LocalAddressChecker::class, function (ContainerInterface $c) {
861
+            return new LocalAddressChecker(
862
+                $c->get(ILogger::class),
863
+            );
864
+        });
865
+        $this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
866
+            return new NegativeDnsCache(
867
+                $c->get(ICacheFactory::class),
868
+            );
869
+        });
870
+        $this->registerService(DnsPinMiddleware::class, function (ContainerInterface $c) {
871
+            return new DnsPinMiddleware(
872
+                $c->get(NegativeDnsCache::class),
873
+                $c->get(LocalAddressChecker::class)
874
+            );
875
+        });
876
+        $this->registerDeprecatedAlias('HttpClientService', IClientService::class);
877
+        $this->registerService(IEventLogger::class, function (ContainerInterface $c) {
878
+            return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
879
+        });
880
+        /** @deprecated 19.0.0 */
881
+        $this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
882
+
883
+        $this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
884
+            $queryLogger = new QueryLogger();
885
+            if ($c->get(SystemConfig::class)->getValue('debug', false)) {
886
+                // In debug mode, module is being activated by default
887
+                $queryLogger->activate();
888
+            }
889
+            return $queryLogger;
890
+        });
891
+        /** @deprecated 19.0.0 */
892
+        $this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
893
+
894
+        /** @deprecated 19.0.0 */
895
+        $this->registerDeprecatedAlias('TempManager', TempManager::class);
896
+        $this->registerAlias(ITempManager::class, TempManager::class);
897
+
898
+        $this->registerService(AppManager::class, function (ContainerInterface $c) {
899
+            // TODO: use auto-wiring
900
+            return new \OC\App\AppManager(
901
+                $c->get(IUserSession::class),
902
+                $c->get(\OCP\IConfig::class),
903
+                $c->get(\OC\AppConfig::class),
904
+                $c->get(IGroupManager::class),
905
+                $c->get(ICacheFactory::class),
906
+                $c->get(SymfonyAdapter::class),
907
+                $c->get(LoggerInterface::class)
908
+            );
909
+        });
910
+        /** @deprecated 19.0.0 */
911
+        $this->registerDeprecatedAlias('AppManager', AppManager::class);
912
+        $this->registerAlias(IAppManager::class, AppManager::class);
913
+
914
+        $this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
915
+        /** @deprecated 19.0.0 */
916
+        $this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
917
+
918
+        $this->registerService(IDateTimeFormatter::class, function (Server $c) {
919
+            $language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
920
+
921
+            return new DateTimeFormatter(
922
+                $c->get(IDateTimeZone::class)->getTimeZone(),
923
+                $c->getL10N('lib', $language)
924
+            );
925
+        });
926
+        /** @deprecated 19.0.0 */
927
+        $this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
928
+
929
+        $this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
930
+            $mountCache = new UserMountCache(
931
+                $c->get(IDBConnection::class),
932
+                $c->get(IUserManager::class),
933
+                $c->get(ILogger::class)
934
+            );
935
+            $listener = new UserMountCacheListener($mountCache);
936
+            $listener->listen($c->get(IUserManager::class));
937
+            return $mountCache;
938
+        });
939
+        /** @deprecated 19.0.0 */
940
+        $this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
941
+
942
+        $this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
943
+            $loader = \OC\Files\Filesystem::getLoader();
944
+            $mountCache = $c->get(IUserMountCache::class);
945
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
946
+
947
+            // builtin providers
948
+
949
+            $config = $c->get(\OCP\IConfig::class);
950
+            $logger = $c->get(ILogger::class);
951
+            $manager->registerProvider(new CacheMountProvider($config));
952
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
953
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
954
+            $manager->registerRootProvider(new RootMountProvider($config, $c->get(LoggerInterface::class)));
955
+            $manager->registerRootProvider(new ObjectStorePreviewCacheMountProvider($logger, $config));
956
+
957
+            return $manager;
958
+        });
959
+        /** @deprecated 19.0.0 */
960
+        $this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
961
+
962
+        /** @deprecated 20.0.0 */
963
+        $this->registerDeprecatedAlias('IniWrapper', IniGetWrapper::class);
964
+        $this->registerService(IBus::class, function (ContainerInterface $c) {
965
+            $busClass = $c->get(\OCP\IConfig::class)->getSystemValue('commandbus');
966
+            if ($busClass) {
967
+                [$app, $class] = explode('::', $busClass, 2);
968
+                if ($c->get(IAppManager::class)->isInstalled($app)) {
969
+                    \OC_App::loadApp($app);
970
+                    return $c->get($class);
971
+                } else {
972
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
973
+                }
974
+            } else {
975
+                $jobList = $c->get(IJobList::class);
976
+                return new CronBus($jobList);
977
+            }
978
+        });
979
+        $this->registerDeprecatedAlias('AsyncCommandBus', IBus::class);
980
+        /** @deprecated 20.0.0 */
981
+        $this->registerDeprecatedAlias('TrustedDomainHelper', TrustedDomainHelper::class);
982
+        $this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
983
+        /** @deprecated 19.0.0 */
984
+        $this->registerDeprecatedAlias('Throttler', Throttler::class);
985
+        $this->registerService('IntegrityCodeChecker', function (ContainerInterface $c) {
986
+            // IConfig and IAppManager requires a working database. This code
987
+            // might however be called when ownCloud is not yet setup.
988
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
989
+                $config = $c->get(\OCP\IConfig::class);
990
+                $appManager = $c->get(IAppManager::class);
991
+            } else {
992
+                $config = null;
993
+                $appManager = null;
994
+            }
995
+
996
+            return new Checker(
997
+                new EnvironmentHelper(),
998
+                new FileAccessHelper(),
999
+                new AppLocator(),
1000
+                $config,
1001
+                $c->get(ICacheFactory::class),
1002
+                $appManager,
1003
+                $c->get(IMimeTypeDetector::class)
1004
+            );
1005
+        });
1006
+        $this->registerService(\OCP\IRequest::class, function (ContainerInterface $c) {
1007
+            if (isset($this['urlParams'])) {
1008
+                $urlParams = $this['urlParams'];
1009
+            } else {
1010
+                $urlParams = [];
1011
+            }
1012
+
1013
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
1014
+                && in_array('fakeinput', stream_get_wrappers())
1015
+            ) {
1016
+                $stream = 'fakeinput://data';
1017
+            } else {
1018
+                $stream = 'php://input';
1019
+            }
1020
+
1021
+            return new Request(
1022
+                [
1023
+                    'get' => $_GET,
1024
+                    'post' => $_POST,
1025
+                    'files' => $_FILES,
1026
+                    'server' => $_SERVER,
1027
+                    'env' => $_ENV,
1028
+                    'cookies' => $_COOKIE,
1029
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1030
+                        ? $_SERVER['REQUEST_METHOD']
1031
+                        : '',
1032
+                    'urlParams' => $urlParams,
1033
+                ],
1034
+                $this->get(ISecureRandom::class),
1035
+                $this->get(\OCP\IConfig::class),
1036
+                $this->get(CsrfTokenManager::class),
1037
+                $stream
1038
+            );
1039
+        });
1040
+        /** @deprecated 19.0.0 */
1041
+        $this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
1042
+
1043
+        $this->registerService(IMailer::class, function (Server $c) {
1044
+            return new Mailer(
1045
+                $c->get(\OCP\IConfig::class),
1046
+                $c->get(ILogger::class),
1047
+                $c->get(Defaults::class),
1048
+                $c->get(IURLGenerator::class),
1049
+                $c->getL10N('lib'),
1050
+                $c->get(IEventDispatcher::class),
1051
+                $c->get(IFactory::class)
1052
+            );
1053
+        });
1054
+        /** @deprecated 19.0.0 */
1055
+        $this->registerDeprecatedAlias('Mailer', IMailer::class);
1056
+
1057
+        /** @deprecated 21.0.0 */
1058
+        $this->registerDeprecatedAlias('LDAPProvider', ILDAPProvider::class);
1059
+
1060
+        $this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
1061
+            $config = $c->get(\OCP\IConfig::class);
1062
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1063
+            if (is_null($factoryClass) || !class_exists($factoryClass)) {
1064
+                return new NullLDAPProviderFactory($this);
1065
+            }
1066
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1067
+            return new $factoryClass($this);
1068
+        });
1069
+        $this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
1070
+            $factory = $c->get(ILDAPProviderFactory::class);
1071
+            return $factory->getLDAPProvider();
1072
+        });
1073
+        $this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
1074
+            $ini = $c->get(IniGetWrapper::class);
1075
+            $config = $c->get(\OCP\IConfig::class);
1076
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1077
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1078
+                /** @var \OC\Memcache\Factory $memcacheFactory */
1079
+                $memcacheFactory = $c->get(ICacheFactory::class);
1080
+                $memcache = $memcacheFactory->createLocking('lock');
1081
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
1082
+                    return new MemcacheLockingProvider($memcache, $ttl);
1083
+                }
1084
+                return new DBLockingProvider(
1085
+                    $c->get(IDBConnection::class),
1086
+                    $c->get(ILogger::class),
1087
+                    new TimeFactory(),
1088
+                    $ttl,
1089
+                    !\OC::$CLI
1090
+                );
1091
+            }
1092
+            return new NoopLockingProvider();
1093
+        });
1094
+        /** @deprecated 19.0.0 */
1095
+        $this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1096
+
1097
+        $this->registerAlias(ILockdownManager::class, 'LockdownManager');
1098
+        $this->registerService(SetupManager::class, function ($c) {
1099
+            // create the setupmanager through the mount manager to resolve the cyclic dependency
1100
+            return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
1101
+        });
1102
+        $this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
1103
+        /** @deprecated 19.0.0 */
1104
+        $this->registerDeprecatedAlias('MountManager', IMountManager::class);
1105
+
1106
+        $this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
1107
+            return new \OC\Files\Type\Detection(
1108
+                $c->get(IURLGenerator::class),
1109
+                $c->get(ILogger::class),
1110
+                \OC::$configDir,
1111
+                \OC::$SERVERROOT . '/resources/config/'
1112
+            );
1113
+        });
1114
+        /** @deprecated 19.0.0 */
1115
+        $this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1116
+
1117
+        $this->registerAlias(IMimeTypeLoader::class, Loader::class);
1118
+        /** @deprecated 19.0.0 */
1119
+        $this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1120
+        $this->registerService(BundleFetcher::class, function () {
1121
+            return new BundleFetcher($this->getL10N('lib'));
1122
+        });
1123
+        $this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
1124
+        /** @deprecated 19.0.0 */
1125
+        $this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1126
+
1127
+        $this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
1128
+            $manager = new CapabilitiesManager($c->get(LoggerInterface::class));
1129
+            $manager->registerCapability(function () use ($c) {
1130
+                return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
1131
+            });
1132
+            $manager->registerCapability(function () use ($c) {
1133
+                return $c->get(\OC\Security\Bruteforce\Capabilities::class);
1134
+            });
1135
+            return $manager;
1136
+        });
1137
+        /** @deprecated 19.0.0 */
1138
+        $this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1139
+
1140
+        $this->registerService(ICommentsManager::class, function (Server $c) {
1141
+            $config = $c->get(\OCP\IConfig::class);
1142
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1143
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
1144
+            $factory = new $factoryClass($this);
1145
+            $manager = $factory->getManager();
1146
+
1147
+            $manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1148
+                $manager = $c->get(IUserManager::class);
1149
+                $user = $manager->get($id);
1150
+                if (is_null($user)) {
1151
+                    $l = $c->getL10N('core');
1152
+                    $displayName = $l->t('Unknown user');
1153
+                } else {
1154
+                    $displayName = $user->getDisplayName();
1155
+                }
1156
+                return $displayName;
1157
+            });
1158
+
1159
+            return $manager;
1160
+        });
1161
+        /** @deprecated 19.0.0 */
1162
+        $this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1163
+
1164
+        $this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1165
+        $this->registerService('ThemingDefaults', function (Server $c) {
1166
+            /*
1167 1167
 			 * Dark magic for autoloader.
1168 1168
 			 * If we do a class_exists it will try to load the class which will
1169 1169
 			 * make composer cache the result. Resulting in errors when enabling
1170 1170
 			 * the theming app.
1171 1171
 			 */
1172
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1173
-			if (isset($prefixes['OCA\\Theming\\'])) {
1174
-				$classExists = true;
1175
-			} else {
1176
-				$classExists = false;
1177
-			}
1178
-
1179
-			if ($classExists && $c->get(\OCP\IConfig::class)->getSystemValue('installed', false) && $c->get(IAppManager::class)->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1180
-				return new ThemingDefaults(
1181
-					$c->get(\OCP\IConfig::class),
1182
-					$c->getL10N('theming'),
1183
-					$c->get(IURLGenerator::class),
1184
-					$c->get(ICacheFactory::class),
1185
-					new Util($c->get(\OCP\IConfig::class), $this->get(IAppManager::class), $c->getAppDataDir('theming')),
1186
-					new ImageManager(
1187
-						$c->get(\OCP\IConfig::class),
1188
-						$c->getAppDataDir('theming'),
1189
-						$c->get(IURLGenerator::class),
1190
-						$this->get(ICacheFactory::class),
1191
-						$this->get(ILogger::class),
1192
-						$this->get(ITempManager::class)
1193
-					),
1194
-					$c->get(IAppManager::class),
1195
-					$c->get(INavigationManager::class)
1196
-				);
1197
-			}
1198
-			return new \OC_Defaults();
1199
-		});
1200
-		$this->registerService(JSCombiner::class, function (Server $c) {
1201
-			return new JSCombiner(
1202
-				$c->getAppDataDir('js'),
1203
-				$c->get(IURLGenerator::class),
1204
-				$this->get(ICacheFactory::class),
1205
-				$c->get(SystemConfig::class),
1206
-				$c->get(ILogger::class)
1207
-			);
1208
-		});
1209
-		$this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1210
-		/** @deprecated 19.0.0 */
1211
-		$this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1212
-		$this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1213
-
1214
-		$this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1215
-			// FIXME: Instantiiated here due to cyclic dependency
1216
-			$request = new Request(
1217
-				[
1218
-					'get' => $_GET,
1219
-					'post' => $_POST,
1220
-					'files' => $_FILES,
1221
-					'server' => $_SERVER,
1222
-					'env' => $_ENV,
1223
-					'cookies' => $_COOKIE,
1224
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1225
-						? $_SERVER['REQUEST_METHOD']
1226
-						: null,
1227
-				],
1228
-				$c->get(ISecureRandom::class),
1229
-				$c->get(\OCP\IConfig::class)
1230
-			);
1231
-
1232
-			return new CryptoWrapper(
1233
-				$c->get(\OCP\IConfig::class),
1234
-				$c->get(ICrypto::class),
1235
-				$c->get(ISecureRandom::class),
1236
-				$request
1237
-			);
1238
-		});
1239
-		/** @deprecated 19.0.0 */
1240
-		$this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1241
-		$this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1242
-			return new SessionStorage($c->get(ISession::class));
1243
-		});
1244
-		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1245
-		/** @deprecated 19.0.0 */
1246
-		$this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1247
-
1248
-		$this->registerService(\OCP\Share\IManager::class, function (IServerContainer $c) {
1249
-			$config = $c->get(\OCP\IConfig::class);
1250
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1251
-			/** @var \OCP\Share\IProviderFactory $factory */
1252
-			$factory = new $factoryClass($this);
1253
-
1254
-			$manager = new \OC\Share20\Manager(
1255
-				$c->get(ILogger::class),
1256
-				$c->get(\OCP\IConfig::class),
1257
-				$c->get(ISecureRandom::class),
1258
-				$c->get(IHasher::class),
1259
-				$c->get(IMountManager::class),
1260
-				$c->get(IGroupManager::class),
1261
-				$c->getL10N('lib'),
1262
-				$c->get(IFactory::class),
1263
-				$factory,
1264
-				$c->get(IUserManager::class),
1265
-				$c->get(IRootFolder::class),
1266
-				$c->get(SymfonyAdapter::class),
1267
-				$c->get(IMailer::class),
1268
-				$c->get(IURLGenerator::class),
1269
-				$c->get('ThemingDefaults'),
1270
-				$c->get(IEventDispatcher::class),
1271
-				$c->get(IUserSession::class),
1272
-				$c->get(KnownUserService::class)
1273
-			);
1274
-
1275
-			return $manager;
1276
-		});
1277
-		/** @deprecated 19.0.0 */
1278
-		$this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1279
-
1280
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1281
-			$instance = new Collaboration\Collaborators\Search($c);
1282
-
1283
-			// register default plugins
1284
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1285
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1286
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1287
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1288
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1289
-
1290
-			return $instance;
1291
-		});
1292
-		/** @deprecated 19.0.0 */
1293
-		$this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1294
-		$this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1295
-
1296
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1297
-
1298
-		$this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1299
-		$this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1300
-
1301
-		$this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1302
-		$this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1303
-		$this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1304
-			return new \OC\Files\AppData\Factory(
1305
-				$c->get(IRootFolder::class),
1306
-				$c->get(SystemConfig::class)
1307
-			);
1308
-		});
1309
-
1310
-		$this->registerService('LockdownManager', function (ContainerInterface $c) {
1311
-			return new LockdownManager(function () use ($c) {
1312
-				return $c->get(ISession::class);
1313
-			});
1314
-		});
1315
-
1316
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1317
-			return new DiscoveryService(
1318
-				$c->get(ICacheFactory::class),
1319
-				$c->get(IClientService::class)
1320
-			);
1321
-		});
1322
-
1323
-		$this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1324
-			return new CloudIdManager($c->get(\OCP\Contacts\IManager::class), $c->get(IURLGenerator::class), $c->get(IUserManager::class));
1325
-		});
1326
-
1327
-		$this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1328
-
1329
-		$this->registerService(ICloudFederationProviderManager::class, function (ContainerInterface $c) {
1330
-			return new CloudFederationProviderManager(
1331
-				$c->get(IAppManager::class),
1332
-				$c->get(IClientService::class),
1333
-				$c->get(ICloudIdManager::class),
1334
-				$c->get(ILogger::class)
1335
-			);
1336
-		});
1337
-
1338
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1339
-			return new CloudFederationFactory();
1340
-		});
1341
-
1342
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1343
-		/** @deprecated 19.0.0 */
1344
-		$this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1345
-
1346
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1347
-		/** @deprecated 19.0.0 */
1348
-		$this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1349
-
1350
-		$this->registerService(Defaults::class, function (Server $c) {
1351
-			return new Defaults(
1352
-				$c->getThemingDefaults()
1353
-			);
1354
-		});
1355
-		/** @deprecated 19.0.0 */
1356
-		$this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1357
-
1358
-		$this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1359
-			return $c->get(\OCP\IUserSession::class)->getSession();
1360
-		}, false);
1361
-
1362
-		$this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1363
-			return new ShareHelper(
1364
-				$c->get(\OCP\Share\IManager::class)
1365
-			);
1366
-		});
1367
-
1368
-		$this->registerService(Installer::class, function (ContainerInterface $c) {
1369
-			return new Installer(
1370
-				$c->get(AppFetcher::class),
1371
-				$c->get(IClientService::class),
1372
-				$c->get(ITempManager::class),
1373
-				$c->get(LoggerInterface::class),
1374
-				$c->get(\OCP\IConfig::class),
1375
-				\OC::$CLI
1376
-			);
1377
-		});
1378
-
1379
-		$this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1380
-			return new ApiFactory($c->get(IClientService::class));
1381
-		});
1382
-
1383
-		$this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1384
-			$memcacheFactory = $c->get(ICacheFactory::class);
1385
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1386
-		});
1387
-
1388
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1389
-		$this->registerAlias(IAccountManager::class, AccountManager::class);
1390
-
1391
-		$this->registerAlias(IStorageFactory::class, StorageFactory::class);
1392
-
1393
-		$this->registerAlias(IDashboardManager::class, DashboardManager::class);
1394
-		$this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1395
-		$this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1396
-
1397
-		$this->registerAlias(ISubAdmin::class, SubAdmin::class);
1398
-
1399
-		$this->registerAlias(IInitialStateService::class, InitialStateService::class);
1400
-
1401
-		$this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1402
-
1403
-		$this->connectDispatcher();
1404
-	}
1405
-
1406
-	public function boot() {
1407
-		/** @var HookConnector $hookConnector */
1408
-		$hookConnector = $this->get(HookConnector::class);
1409
-		$hookConnector->viewToNode();
1410
-	}
1411
-
1412
-	/**
1413
-	 * @return \OCP\Calendar\IManager
1414
-	 * @deprecated 20.0.0
1415
-	 */
1416
-	public function getCalendarManager() {
1417
-		return $this->get(\OC\Calendar\Manager::class);
1418
-	}
1419
-
1420
-	/**
1421
-	 * @return \OCP\Calendar\Resource\IManager
1422
-	 * @deprecated 20.0.0
1423
-	 */
1424
-	public function getCalendarResourceBackendManager() {
1425
-		return $this->get(\OC\Calendar\Resource\Manager::class);
1426
-	}
1427
-
1428
-	/**
1429
-	 * @return \OCP\Calendar\Room\IManager
1430
-	 * @deprecated 20.0.0
1431
-	 */
1432
-	public function getCalendarRoomBackendManager() {
1433
-		return $this->get(\OC\Calendar\Room\Manager::class);
1434
-	}
1435
-
1436
-	private function connectDispatcher() {
1437
-		$dispatcher = $this->get(SymfonyAdapter::class);
1438
-
1439
-		// Delete avatar on user deletion
1440
-		$dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1441
-			$logger = $this->get(ILogger::class);
1442
-			$manager = $this->getAvatarManager();
1443
-			/** @var IUser $user */
1444
-			$user = $e->getSubject();
1445
-
1446
-			try {
1447
-				$avatar = $manager->getAvatar($user->getUID());
1448
-				$avatar->remove();
1449
-			} catch (NotFoundException $e) {
1450
-				// no avatar to remove
1451
-			} catch (\Exception $e) {
1452
-				// Ignore exceptions
1453
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1454
-			}
1455
-		});
1456
-
1457
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1458
-			$manager = $this->getAvatarManager();
1459
-			/** @var IUser $user */
1460
-			$user = $e->getSubject();
1461
-			$feature = $e->getArgument('feature');
1462
-			$oldValue = $e->getArgument('oldValue');
1463
-			$value = $e->getArgument('value');
1464
-
1465
-			// We only change the avatar on display name changes
1466
-			if ($feature !== 'displayName') {
1467
-				return;
1468
-			}
1469
-
1470
-			try {
1471
-				$avatar = $manager->getAvatar($user->getUID());
1472
-				$avatar->userChanged($feature, $oldValue, $value);
1473
-			} catch (NotFoundException $e) {
1474
-				// no avatar to remove
1475
-			}
1476
-		});
1477
-
1478
-		/** @var IEventDispatcher $eventDispatched */
1479
-		$eventDispatched = $this->get(IEventDispatcher::class);
1480
-		$eventDispatched->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1481
-		$eventDispatched->addServiceListener(PostLoginEvent::class, UserLoggedInListener::class);
1482
-	}
1483
-
1484
-	/**
1485
-	 * @return \OCP\Contacts\IManager
1486
-	 * @deprecated 20.0.0
1487
-	 */
1488
-	public function getContactsManager() {
1489
-		return $this->get(\OCP\Contacts\IManager::class);
1490
-	}
1491
-
1492
-	/**
1493
-	 * @return \OC\Encryption\Manager
1494
-	 * @deprecated 20.0.0
1495
-	 */
1496
-	public function getEncryptionManager() {
1497
-		return $this->get(\OCP\Encryption\IManager::class);
1498
-	}
1499
-
1500
-	/**
1501
-	 * @return \OC\Encryption\File
1502
-	 * @deprecated 20.0.0
1503
-	 */
1504
-	public function getEncryptionFilesHelper() {
1505
-		return $this->get(IFile::class);
1506
-	}
1507
-
1508
-	/**
1509
-	 * @return \OCP\Encryption\Keys\IStorage
1510
-	 * @deprecated 20.0.0
1511
-	 */
1512
-	public function getEncryptionKeyStorage() {
1513
-		return $this->get(IStorage::class);
1514
-	}
1515
-
1516
-	/**
1517
-	 * The current request object holding all information about the request
1518
-	 * currently being processed is returned from this method.
1519
-	 * In case the current execution was not initiated by a web request null is returned
1520
-	 *
1521
-	 * @return \OCP\IRequest
1522
-	 * @deprecated 20.0.0
1523
-	 */
1524
-	public function getRequest() {
1525
-		return $this->get(IRequest::class);
1526
-	}
1527
-
1528
-	/**
1529
-	 * Returns the preview manager which can create preview images for a given file
1530
-	 *
1531
-	 * @return IPreview
1532
-	 * @deprecated 20.0.0
1533
-	 */
1534
-	public function getPreviewManager() {
1535
-		return $this->get(IPreview::class);
1536
-	}
1537
-
1538
-	/**
1539
-	 * Returns the tag manager which can get and set tags for different object types
1540
-	 *
1541
-	 * @see \OCP\ITagManager::load()
1542
-	 * @return ITagManager
1543
-	 * @deprecated 20.0.0
1544
-	 */
1545
-	public function getTagManager() {
1546
-		return $this->get(ITagManager::class);
1547
-	}
1548
-
1549
-	/**
1550
-	 * Returns the system-tag manager
1551
-	 *
1552
-	 * @return ISystemTagManager
1553
-	 *
1554
-	 * @since 9.0.0
1555
-	 * @deprecated 20.0.0
1556
-	 */
1557
-	public function getSystemTagManager() {
1558
-		return $this->get(ISystemTagManager::class);
1559
-	}
1560
-
1561
-	/**
1562
-	 * Returns the system-tag object mapper
1563
-	 *
1564
-	 * @return ISystemTagObjectMapper
1565
-	 *
1566
-	 * @since 9.0.0
1567
-	 * @deprecated 20.0.0
1568
-	 */
1569
-	public function getSystemTagObjectMapper() {
1570
-		return $this->get(ISystemTagObjectMapper::class);
1571
-	}
1572
-
1573
-	/**
1574
-	 * Returns the avatar manager, used for avatar functionality
1575
-	 *
1576
-	 * @return IAvatarManager
1577
-	 * @deprecated 20.0.0
1578
-	 */
1579
-	public function getAvatarManager() {
1580
-		return $this->get(IAvatarManager::class);
1581
-	}
1582
-
1583
-	/**
1584
-	 * Returns the root folder of ownCloud's data directory
1585
-	 *
1586
-	 * @return IRootFolder
1587
-	 * @deprecated 20.0.0
1588
-	 */
1589
-	public function getRootFolder() {
1590
-		return $this->get(IRootFolder::class);
1591
-	}
1592
-
1593
-	/**
1594
-	 * Returns the root folder of ownCloud's data directory
1595
-	 * This is the lazy variant so this gets only initialized once it
1596
-	 * is actually used.
1597
-	 *
1598
-	 * @return IRootFolder
1599
-	 * @deprecated 20.0.0
1600
-	 */
1601
-	public function getLazyRootFolder() {
1602
-		return $this->get(IRootFolder::class);
1603
-	}
1604
-
1605
-	/**
1606
-	 * Returns a view to ownCloud's files folder
1607
-	 *
1608
-	 * @param string $userId user ID
1609
-	 * @return \OCP\Files\Folder|null
1610
-	 * @deprecated 20.0.0
1611
-	 */
1612
-	public function getUserFolder($userId = null) {
1613
-		if ($userId === null) {
1614
-			$user = $this->get(IUserSession::class)->getUser();
1615
-			if (!$user) {
1616
-				return null;
1617
-			}
1618
-			$userId = $user->getUID();
1619
-		}
1620
-		$root = $this->get(IRootFolder::class);
1621
-		return $root->getUserFolder($userId);
1622
-	}
1623
-
1624
-	/**
1625
-	 * @return \OC\User\Manager
1626
-	 * @deprecated 20.0.0
1627
-	 */
1628
-	public function getUserManager() {
1629
-		return $this->get(IUserManager::class);
1630
-	}
1631
-
1632
-	/**
1633
-	 * @return \OC\Group\Manager
1634
-	 * @deprecated 20.0.0
1635
-	 */
1636
-	public function getGroupManager() {
1637
-		return $this->get(IGroupManager::class);
1638
-	}
1639
-
1640
-	/**
1641
-	 * @return \OC\User\Session
1642
-	 * @deprecated 20.0.0
1643
-	 */
1644
-	public function getUserSession() {
1645
-		return $this->get(IUserSession::class);
1646
-	}
1647
-
1648
-	/**
1649
-	 * @return \OCP\ISession
1650
-	 * @deprecated 20.0.0
1651
-	 */
1652
-	public function getSession() {
1653
-		return $this->get(IUserSession::class)->getSession();
1654
-	}
1655
-
1656
-	/**
1657
-	 * @param \OCP\ISession $session
1658
-	 */
1659
-	public function setSession(\OCP\ISession $session) {
1660
-		$this->get(SessionStorage::class)->setSession($session);
1661
-		$this->get(IUserSession::class)->setSession($session);
1662
-		$this->get(Store::class)->setSession($session);
1663
-	}
1664
-
1665
-	/**
1666
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1667
-	 * @deprecated 20.0.0
1668
-	 */
1669
-	public function getTwoFactorAuthManager() {
1670
-		return $this->get(\OC\Authentication\TwoFactorAuth\Manager::class);
1671
-	}
1672
-
1673
-	/**
1674
-	 * @return \OC\NavigationManager
1675
-	 * @deprecated 20.0.0
1676
-	 */
1677
-	public function getNavigationManager() {
1678
-		return $this->get(INavigationManager::class);
1679
-	}
1680
-
1681
-	/**
1682
-	 * @return \OCP\IConfig
1683
-	 * @deprecated 20.0.0
1684
-	 */
1685
-	public function getConfig() {
1686
-		return $this->get(AllConfig::class);
1687
-	}
1688
-
1689
-	/**
1690
-	 * @return \OC\SystemConfig
1691
-	 * @deprecated 20.0.0
1692
-	 */
1693
-	public function getSystemConfig() {
1694
-		return $this->get(SystemConfig::class);
1695
-	}
1696
-
1697
-	/**
1698
-	 * Returns the app config manager
1699
-	 *
1700
-	 * @return IAppConfig
1701
-	 * @deprecated 20.0.0
1702
-	 */
1703
-	public function getAppConfig() {
1704
-		return $this->get(IAppConfig::class);
1705
-	}
1706
-
1707
-	/**
1708
-	 * @return IFactory
1709
-	 * @deprecated 20.0.0
1710
-	 */
1711
-	public function getL10NFactory() {
1712
-		return $this->get(IFactory::class);
1713
-	}
1714
-
1715
-	/**
1716
-	 * get an L10N instance
1717
-	 *
1718
-	 * @param string $app appid
1719
-	 * @param string $lang
1720
-	 * @return IL10N
1721
-	 * @deprecated 20.0.0
1722
-	 */
1723
-	public function getL10N($app, $lang = null) {
1724
-		return $this->get(IFactory::class)->get($app, $lang);
1725
-	}
1726
-
1727
-	/**
1728
-	 * @return IURLGenerator
1729
-	 * @deprecated 20.0.0
1730
-	 */
1731
-	public function getURLGenerator() {
1732
-		return $this->get(IURLGenerator::class);
1733
-	}
1734
-
1735
-	/**
1736
-	 * @return AppFetcher
1737
-	 * @deprecated 20.0.0
1738
-	 */
1739
-	public function getAppFetcher() {
1740
-		return $this->get(AppFetcher::class);
1741
-	}
1742
-
1743
-	/**
1744
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1745
-	 * getMemCacheFactory() instead.
1746
-	 *
1747
-	 * @return ICache
1748
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1749
-	 */
1750
-	public function getCache() {
1751
-		return $this->get(ICache::class);
1752
-	}
1753
-
1754
-	/**
1755
-	 * Returns an \OCP\CacheFactory instance
1756
-	 *
1757
-	 * @return \OCP\ICacheFactory
1758
-	 * @deprecated 20.0.0
1759
-	 */
1760
-	public function getMemCacheFactory() {
1761
-		return $this->get(ICacheFactory::class);
1762
-	}
1763
-
1764
-	/**
1765
-	 * Returns an \OC\RedisFactory instance
1766
-	 *
1767
-	 * @return \OC\RedisFactory
1768
-	 * @deprecated 20.0.0
1769
-	 */
1770
-	public function getGetRedisFactory() {
1771
-		return $this->get('RedisFactory');
1772
-	}
1773
-
1774
-
1775
-	/**
1776
-	 * Returns the current session
1777
-	 *
1778
-	 * @return \OCP\IDBConnection
1779
-	 * @deprecated 20.0.0
1780
-	 */
1781
-	public function getDatabaseConnection() {
1782
-		return $this->get(IDBConnection::class);
1783
-	}
1784
-
1785
-	/**
1786
-	 * Returns the activity manager
1787
-	 *
1788
-	 * @return \OCP\Activity\IManager
1789
-	 * @deprecated 20.0.0
1790
-	 */
1791
-	public function getActivityManager() {
1792
-		return $this->get(\OCP\Activity\IManager::class);
1793
-	}
1794
-
1795
-	/**
1796
-	 * Returns an job list for controlling background jobs
1797
-	 *
1798
-	 * @return IJobList
1799
-	 * @deprecated 20.0.0
1800
-	 */
1801
-	public function getJobList() {
1802
-		return $this->get(IJobList::class);
1803
-	}
1804
-
1805
-	/**
1806
-	 * Returns a logger instance
1807
-	 *
1808
-	 * @return ILogger
1809
-	 * @deprecated 20.0.0
1810
-	 */
1811
-	public function getLogger() {
1812
-		return $this->get(ILogger::class);
1813
-	}
1814
-
1815
-	/**
1816
-	 * @return ILogFactory
1817
-	 * @throws \OCP\AppFramework\QueryException
1818
-	 * @deprecated 20.0.0
1819
-	 */
1820
-	public function getLogFactory() {
1821
-		return $this->get(ILogFactory::class);
1822
-	}
1823
-
1824
-	/**
1825
-	 * Returns a router for generating and matching urls
1826
-	 *
1827
-	 * @return IRouter
1828
-	 * @deprecated 20.0.0
1829
-	 */
1830
-	public function getRouter() {
1831
-		return $this->get(IRouter::class);
1832
-	}
1833
-
1834
-	/**
1835
-	 * Returns a search instance
1836
-	 *
1837
-	 * @return ISearch
1838
-	 * @deprecated 20.0.0
1839
-	 */
1840
-	public function getSearch() {
1841
-		return $this->get(ISearch::class);
1842
-	}
1843
-
1844
-	/**
1845
-	 * Returns a SecureRandom instance
1846
-	 *
1847
-	 * @return \OCP\Security\ISecureRandom
1848
-	 * @deprecated 20.0.0
1849
-	 */
1850
-	public function getSecureRandom() {
1851
-		return $this->get(ISecureRandom::class);
1852
-	}
1853
-
1854
-	/**
1855
-	 * Returns a Crypto instance
1856
-	 *
1857
-	 * @return ICrypto
1858
-	 * @deprecated 20.0.0
1859
-	 */
1860
-	public function getCrypto() {
1861
-		return $this->get(ICrypto::class);
1862
-	}
1863
-
1864
-	/**
1865
-	 * Returns a Hasher instance
1866
-	 *
1867
-	 * @return IHasher
1868
-	 * @deprecated 20.0.0
1869
-	 */
1870
-	public function getHasher() {
1871
-		return $this->get(IHasher::class);
1872
-	}
1873
-
1874
-	/**
1875
-	 * Returns a CredentialsManager instance
1876
-	 *
1877
-	 * @return ICredentialsManager
1878
-	 * @deprecated 20.0.0
1879
-	 */
1880
-	public function getCredentialsManager() {
1881
-		return $this->get(ICredentialsManager::class);
1882
-	}
1883
-
1884
-	/**
1885
-	 * Get the certificate manager
1886
-	 *
1887
-	 * @return \OCP\ICertificateManager
1888
-	 */
1889
-	public function getCertificateManager() {
1890
-		return $this->get(ICertificateManager::class);
1891
-	}
1892
-
1893
-	/**
1894
-	 * Returns an instance of the HTTP client service
1895
-	 *
1896
-	 * @return IClientService
1897
-	 * @deprecated 20.0.0
1898
-	 */
1899
-	public function getHTTPClientService() {
1900
-		return $this->get(IClientService::class);
1901
-	}
1902
-
1903
-	/**
1904
-	 * Create a new event source
1905
-	 *
1906
-	 * @return \OCP\IEventSource
1907
-	 * @deprecated 20.0.0
1908
-	 */
1909
-	public function createEventSource() {
1910
-		return new \OC_EventSource();
1911
-	}
1912
-
1913
-	/**
1914
-	 * Get the active event logger
1915
-	 *
1916
-	 * The returned logger only logs data when debug mode is enabled
1917
-	 *
1918
-	 * @return IEventLogger
1919
-	 * @deprecated 20.0.0
1920
-	 */
1921
-	public function getEventLogger() {
1922
-		return $this->get(IEventLogger::class);
1923
-	}
1924
-
1925
-	/**
1926
-	 * Get the active query logger
1927
-	 *
1928
-	 * The returned logger only logs data when debug mode is enabled
1929
-	 *
1930
-	 * @return IQueryLogger
1931
-	 * @deprecated 20.0.0
1932
-	 */
1933
-	public function getQueryLogger() {
1934
-		return $this->get(IQueryLogger::class);
1935
-	}
1936
-
1937
-	/**
1938
-	 * Get the manager for temporary files and folders
1939
-	 *
1940
-	 * @return \OCP\ITempManager
1941
-	 * @deprecated 20.0.0
1942
-	 */
1943
-	public function getTempManager() {
1944
-		return $this->get(ITempManager::class);
1945
-	}
1946
-
1947
-	/**
1948
-	 * Get the app manager
1949
-	 *
1950
-	 * @return \OCP\App\IAppManager
1951
-	 * @deprecated 20.0.0
1952
-	 */
1953
-	public function getAppManager() {
1954
-		return $this->get(IAppManager::class);
1955
-	}
1956
-
1957
-	/**
1958
-	 * Creates a new mailer
1959
-	 *
1960
-	 * @return IMailer
1961
-	 * @deprecated 20.0.0
1962
-	 */
1963
-	public function getMailer() {
1964
-		return $this->get(IMailer::class);
1965
-	}
1966
-
1967
-	/**
1968
-	 * Get the webroot
1969
-	 *
1970
-	 * @return string
1971
-	 * @deprecated 20.0.0
1972
-	 */
1973
-	public function getWebRoot() {
1974
-		return $this->webRoot;
1975
-	}
1976
-
1977
-	/**
1978
-	 * @return \OC\OCSClient
1979
-	 * @deprecated 20.0.0
1980
-	 */
1981
-	public function getOcsClient() {
1982
-		return $this->get('OcsClient');
1983
-	}
1984
-
1985
-	/**
1986
-	 * @return IDateTimeZone
1987
-	 * @deprecated 20.0.0
1988
-	 */
1989
-	public function getDateTimeZone() {
1990
-		return $this->get(IDateTimeZone::class);
1991
-	}
1992
-
1993
-	/**
1994
-	 * @return IDateTimeFormatter
1995
-	 * @deprecated 20.0.0
1996
-	 */
1997
-	public function getDateTimeFormatter() {
1998
-		return $this->get(IDateTimeFormatter::class);
1999
-	}
2000
-
2001
-	/**
2002
-	 * @return IMountProviderCollection
2003
-	 * @deprecated 20.0.0
2004
-	 */
2005
-	public function getMountProviderCollection() {
2006
-		return $this->get(IMountProviderCollection::class);
2007
-	}
2008
-
2009
-	/**
2010
-	 * Get the IniWrapper
2011
-	 *
2012
-	 * @return IniGetWrapper
2013
-	 * @deprecated 20.0.0
2014
-	 */
2015
-	public function getIniWrapper() {
2016
-		return $this->get(IniGetWrapper::class);
2017
-	}
2018
-
2019
-	/**
2020
-	 * @return \OCP\Command\IBus
2021
-	 * @deprecated 20.0.0
2022
-	 */
2023
-	public function getCommandBus() {
2024
-		return $this->get(IBus::class);
2025
-	}
2026
-
2027
-	/**
2028
-	 * Get the trusted domain helper
2029
-	 *
2030
-	 * @return TrustedDomainHelper
2031
-	 * @deprecated 20.0.0
2032
-	 */
2033
-	public function getTrustedDomainHelper() {
2034
-		return $this->get(TrustedDomainHelper::class);
2035
-	}
2036
-
2037
-	/**
2038
-	 * Get the locking provider
2039
-	 *
2040
-	 * @return ILockingProvider
2041
-	 * @since 8.1.0
2042
-	 * @deprecated 20.0.0
2043
-	 */
2044
-	public function getLockingProvider() {
2045
-		return $this->get(ILockingProvider::class);
2046
-	}
2047
-
2048
-	/**
2049
-	 * @return IMountManager
2050
-	 * @deprecated 20.0.0
2051
-	 **/
2052
-	public function getMountManager() {
2053
-		return $this->get(IMountManager::class);
2054
-	}
2055
-
2056
-	/**
2057
-	 * @return IUserMountCache
2058
-	 * @deprecated 20.0.0
2059
-	 */
2060
-	public function getUserMountCache() {
2061
-		return $this->get(IUserMountCache::class);
2062
-	}
2063
-
2064
-	/**
2065
-	 * Get the MimeTypeDetector
2066
-	 *
2067
-	 * @return IMimeTypeDetector
2068
-	 * @deprecated 20.0.0
2069
-	 */
2070
-	public function getMimeTypeDetector() {
2071
-		return $this->get(IMimeTypeDetector::class);
2072
-	}
2073
-
2074
-	/**
2075
-	 * Get the MimeTypeLoader
2076
-	 *
2077
-	 * @return IMimeTypeLoader
2078
-	 * @deprecated 20.0.0
2079
-	 */
2080
-	public function getMimeTypeLoader() {
2081
-		return $this->get(IMimeTypeLoader::class);
2082
-	}
2083
-
2084
-	/**
2085
-	 * Get the manager of all the capabilities
2086
-	 *
2087
-	 * @return CapabilitiesManager
2088
-	 * @deprecated 20.0.0
2089
-	 */
2090
-	public function getCapabilitiesManager() {
2091
-		return $this->get(CapabilitiesManager::class);
2092
-	}
2093
-
2094
-	/**
2095
-	 * Get the EventDispatcher
2096
-	 *
2097
-	 * @return EventDispatcherInterface
2098
-	 * @since 8.2.0
2099
-	 * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2100
-	 */
2101
-	public function getEventDispatcher() {
2102
-		return $this->get(\OC\EventDispatcher\SymfonyAdapter::class);
2103
-	}
2104
-
2105
-	/**
2106
-	 * Get the Notification Manager
2107
-	 *
2108
-	 * @return \OCP\Notification\IManager
2109
-	 * @since 8.2.0
2110
-	 * @deprecated 20.0.0
2111
-	 */
2112
-	public function getNotificationManager() {
2113
-		return $this->get(\OCP\Notification\IManager::class);
2114
-	}
2115
-
2116
-	/**
2117
-	 * @return ICommentsManager
2118
-	 * @deprecated 20.0.0
2119
-	 */
2120
-	public function getCommentsManager() {
2121
-		return $this->get(ICommentsManager::class);
2122
-	}
2123
-
2124
-	/**
2125
-	 * @return \OCA\Theming\ThemingDefaults
2126
-	 * @deprecated 20.0.0
2127
-	 */
2128
-	public function getThemingDefaults() {
2129
-		return $this->get('ThemingDefaults');
2130
-	}
2131
-
2132
-	/**
2133
-	 * @return \OC\IntegrityCheck\Checker
2134
-	 * @deprecated 20.0.0
2135
-	 */
2136
-	public function getIntegrityCodeChecker() {
2137
-		return $this->get('IntegrityCodeChecker');
2138
-	}
2139
-
2140
-	/**
2141
-	 * @return \OC\Session\CryptoWrapper
2142
-	 * @deprecated 20.0.0
2143
-	 */
2144
-	public function getSessionCryptoWrapper() {
2145
-		return $this->get('CryptoWrapper');
2146
-	}
2147
-
2148
-	/**
2149
-	 * @return CsrfTokenManager
2150
-	 * @deprecated 20.0.0
2151
-	 */
2152
-	public function getCsrfTokenManager() {
2153
-		return $this->get(CsrfTokenManager::class);
2154
-	}
2155
-
2156
-	/**
2157
-	 * @return Throttler
2158
-	 * @deprecated 20.0.0
2159
-	 */
2160
-	public function getBruteForceThrottler() {
2161
-		return $this->get(Throttler::class);
2162
-	}
2163
-
2164
-	/**
2165
-	 * @return IContentSecurityPolicyManager
2166
-	 * @deprecated 20.0.0
2167
-	 */
2168
-	public function getContentSecurityPolicyManager() {
2169
-		return $this->get(ContentSecurityPolicyManager::class);
2170
-	}
2171
-
2172
-	/**
2173
-	 * @return ContentSecurityPolicyNonceManager
2174
-	 * @deprecated 20.0.0
2175
-	 */
2176
-	public function getContentSecurityPolicyNonceManager() {
2177
-		return $this->get(ContentSecurityPolicyNonceManager::class);
2178
-	}
2179
-
2180
-	/**
2181
-	 * Not a public API as of 8.2, wait for 9.0
2182
-	 *
2183
-	 * @return \OCA\Files_External\Service\BackendService
2184
-	 * @deprecated 20.0.0
2185
-	 */
2186
-	public function getStoragesBackendService() {
2187
-		return $this->get(BackendService::class);
2188
-	}
2189
-
2190
-	/**
2191
-	 * Not a public API as of 8.2, wait for 9.0
2192
-	 *
2193
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
2194
-	 * @deprecated 20.0.0
2195
-	 */
2196
-	public function getGlobalStoragesService() {
2197
-		return $this->get(GlobalStoragesService::class);
2198
-	}
2199
-
2200
-	/**
2201
-	 * Not a public API as of 8.2, wait for 9.0
2202
-	 *
2203
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
2204
-	 * @deprecated 20.0.0
2205
-	 */
2206
-	public function getUserGlobalStoragesService() {
2207
-		return $this->get(UserGlobalStoragesService::class);
2208
-	}
2209
-
2210
-	/**
2211
-	 * Not a public API as of 8.2, wait for 9.0
2212
-	 *
2213
-	 * @return \OCA\Files_External\Service\UserStoragesService
2214
-	 * @deprecated 20.0.0
2215
-	 */
2216
-	public function getUserStoragesService() {
2217
-		return $this->get(UserStoragesService::class);
2218
-	}
2219
-
2220
-	/**
2221
-	 * @return \OCP\Share\IManager
2222
-	 * @deprecated 20.0.0
2223
-	 */
2224
-	public function getShareManager() {
2225
-		return $this->get(\OCP\Share\IManager::class);
2226
-	}
2227
-
2228
-	/**
2229
-	 * @return \OCP\Collaboration\Collaborators\ISearch
2230
-	 * @deprecated 20.0.0
2231
-	 */
2232
-	public function getCollaboratorSearch() {
2233
-		return $this->get(\OCP\Collaboration\Collaborators\ISearch::class);
2234
-	}
2235
-
2236
-	/**
2237
-	 * @return \OCP\Collaboration\AutoComplete\IManager
2238
-	 * @deprecated 20.0.0
2239
-	 */
2240
-	public function getAutoCompleteManager() {
2241
-		return $this->get(IManager::class);
2242
-	}
2243
-
2244
-	/**
2245
-	 * Returns the LDAP Provider
2246
-	 *
2247
-	 * @return \OCP\LDAP\ILDAPProvider
2248
-	 * @deprecated 20.0.0
2249
-	 */
2250
-	public function getLDAPProvider() {
2251
-		return $this->get('LDAPProvider');
2252
-	}
2253
-
2254
-	/**
2255
-	 * @return \OCP\Settings\IManager
2256
-	 * @deprecated 20.0.0
2257
-	 */
2258
-	public function getSettingsManager() {
2259
-		return $this->get(\OC\Settings\Manager::class);
2260
-	}
2261
-
2262
-	/**
2263
-	 * @return \OCP\Files\IAppData
2264
-	 * @deprecated 20.0.0
2265
-	 */
2266
-	public function getAppDataDir($app) {
2267
-		/** @var \OC\Files\AppData\Factory $factory */
2268
-		$factory = $this->get(\OC\Files\AppData\Factory::class);
2269
-		return $factory->get($app);
2270
-	}
2271
-
2272
-	/**
2273
-	 * @return \OCP\Lockdown\ILockdownManager
2274
-	 * @deprecated 20.0.0
2275
-	 */
2276
-	public function getLockdownManager() {
2277
-		return $this->get('LockdownManager');
2278
-	}
2279
-
2280
-	/**
2281
-	 * @return \OCP\Federation\ICloudIdManager
2282
-	 * @deprecated 20.0.0
2283
-	 */
2284
-	public function getCloudIdManager() {
2285
-		return $this->get(ICloudIdManager::class);
2286
-	}
2287
-
2288
-	/**
2289
-	 * @return \OCP\GlobalScale\IConfig
2290
-	 * @deprecated 20.0.0
2291
-	 */
2292
-	public function getGlobalScaleConfig() {
2293
-		return $this->get(IConfig::class);
2294
-	}
2295
-
2296
-	/**
2297
-	 * @return \OCP\Federation\ICloudFederationProviderManager
2298
-	 * @deprecated 20.0.0
2299
-	 */
2300
-	public function getCloudFederationProviderManager() {
2301
-		return $this->get(ICloudFederationProviderManager::class);
2302
-	}
2303
-
2304
-	/**
2305
-	 * @return \OCP\Remote\Api\IApiFactory
2306
-	 * @deprecated 20.0.0
2307
-	 */
2308
-	public function getRemoteApiFactory() {
2309
-		return $this->get(IApiFactory::class);
2310
-	}
2311
-
2312
-	/**
2313
-	 * @return \OCP\Federation\ICloudFederationFactory
2314
-	 * @deprecated 20.0.0
2315
-	 */
2316
-	public function getCloudFederationFactory() {
2317
-		return $this->get(ICloudFederationFactory::class);
2318
-	}
2319
-
2320
-	/**
2321
-	 * @return \OCP\Remote\IInstanceFactory
2322
-	 * @deprecated 20.0.0
2323
-	 */
2324
-	public function getRemoteInstanceFactory() {
2325
-		return $this->get(IInstanceFactory::class);
2326
-	}
2327
-
2328
-	/**
2329
-	 * @return IStorageFactory
2330
-	 * @deprecated 20.0.0
2331
-	 */
2332
-	public function getStorageFactory() {
2333
-		return $this->get(IStorageFactory::class);
2334
-	}
2335
-
2336
-	/**
2337
-	 * Get the Preview GeneratorHelper
2338
-	 *
2339
-	 * @return GeneratorHelper
2340
-	 * @since 17.0.0
2341
-	 * @deprecated 20.0.0
2342
-	 */
2343
-	public function getGeneratorHelper() {
2344
-		return $this->get(\OC\Preview\GeneratorHelper::class);
2345
-	}
2346
-
2347
-	private function registerDeprecatedAlias(string $alias, string $target) {
2348
-		$this->registerService($alias, function (ContainerInterface $container) use ($target, $alias) {
2349
-			try {
2350
-				/** @var ILogger $logger */
2351
-				$logger = $container->get(ILogger::class);
2352
-				$logger->debug('The requested alias "' . $alias . '" is deprecated. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2353
-			} catch (ContainerExceptionInterface $e) {
2354
-				// Could not get logger. Continue
2355
-			}
2356
-
2357
-			return $container->get($target);
2358
-		}, false);
2359
-	}
1172
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1173
+            if (isset($prefixes['OCA\\Theming\\'])) {
1174
+                $classExists = true;
1175
+            } else {
1176
+                $classExists = false;
1177
+            }
1178
+
1179
+            if ($classExists && $c->get(\OCP\IConfig::class)->getSystemValue('installed', false) && $c->get(IAppManager::class)->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1180
+                return new ThemingDefaults(
1181
+                    $c->get(\OCP\IConfig::class),
1182
+                    $c->getL10N('theming'),
1183
+                    $c->get(IURLGenerator::class),
1184
+                    $c->get(ICacheFactory::class),
1185
+                    new Util($c->get(\OCP\IConfig::class), $this->get(IAppManager::class), $c->getAppDataDir('theming')),
1186
+                    new ImageManager(
1187
+                        $c->get(\OCP\IConfig::class),
1188
+                        $c->getAppDataDir('theming'),
1189
+                        $c->get(IURLGenerator::class),
1190
+                        $this->get(ICacheFactory::class),
1191
+                        $this->get(ILogger::class),
1192
+                        $this->get(ITempManager::class)
1193
+                    ),
1194
+                    $c->get(IAppManager::class),
1195
+                    $c->get(INavigationManager::class)
1196
+                );
1197
+            }
1198
+            return new \OC_Defaults();
1199
+        });
1200
+        $this->registerService(JSCombiner::class, function (Server $c) {
1201
+            return new JSCombiner(
1202
+                $c->getAppDataDir('js'),
1203
+                $c->get(IURLGenerator::class),
1204
+                $this->get(ICacheFactory::class),
1205
+                $c->get(SystemConfig::class),
1206
+                $c->get(ILogger::class)
1207
+            );
1208
+        });
1209
+        $this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1210
+        /** @deprecated 19.0.0 */
1211
+        $this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1212
+        $this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1213
+
1214
+        $this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1215
+            // FIXME: Instantiiated here due to cyclic dependency
1216
+            $request = new Request(
1217
+                [
1218
+                    'get' => $_GET,
1219
+                    'post' => $_POST,
1220
+                    'files' => $_FILES,
1221
+                    'server' => $_SERVER,
1222
+                    'env' => $_ENV,
1223
+                    'cookies' => $_COOKIE,
1224
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1225
+                        ? $_SERVER['REQUEST_METHOD']
1226
+                        : null,
1227
+                ],
1228
+                $c->get(ISecureRandom::class),
1229
+                $c->get(\OCP\IConfig::class)
1230
+            );
1231
+
1232
+            return new CryptoWrapper(
1233
+                $c->get(\OCP\IConfig::class),
1234
+                $c->get(ICrypto::class),
1235
+                $c->get(ISecureRandom::class),
1236
+                $request
1237
+            );
1238
+        });
1239
+        /** @deprecated 19.0.0 */
1240
+        $this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1241
+        $this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1242
+            return new SessionStorage($c->get(ISession::class));
1243
+        });
1244
+        $this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1245
+        /** @deprecated 19.0.0 */
1246
+        $this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1247
+
1248
+        $this->registerService(\OCP\Share\IManager::class, function (IServerContainer $c) {
1249
+            $config = $c->get(\OCP\IConfig::class);
1250
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1251
+            /** @var \OCP\Share\IProviderFactory $factory */
1252
+            $factory = new $factoryClass($this);
1253
+
1254
+            $manager = new \OC\Share20\Manager(
1255
+                $c->get(ILogger::class),
1256
+                $c->get(\OCP\IConfig::class),
1257
+                $c->get(ISecureRandom::class),
1258
+                $c->get(IHasher::class),
1259
+                $c->get(IMountManager::class),
1260
+                $c->get(IGroupManager::class),
1261
+                $c->getL10N('lib'),
1262
+                $c->get(IFactory::class),
1263
+                $factory,
1264
+                $c->get(IUserManager::class),
1265
+                $c->get(IRootFolder::class),
1266
+                $c->get(SymfonyAdapter::class),
1267
+                $c->get(IMailer::class),
1268
+                $c->get(IURLGenerator::class),
1269
+                $c->get('ThemingDefaults'),
1270
+                $c->get(IEventDispatcher::class),
1271
+                $c->get(IUserSession::class),
1272
+                $c->get(KnownUserService::class)
1273
+            );
1274
+
1275
+            return $manager;
1276
+        });
1277
+        /** @deprecated 19.0.0 */
1278
+        $this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1279
+
1280
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1281
+            $instance = new Collaboration\Collaborators\Search($c);
1282
+
1283
+            // register default plugins
1284
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1285
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1286
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1287
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1288
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1289
+
1290
+            return $instance;
1291
+        });
1292
+        /** @deprecated 19.0.0 */
1293
+        $this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1294
+        $this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1295
+
1296
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1297
+
1298
+        $this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1299
+        $this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1300
+
1301
+        $this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1302
+        $this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1303
+        $this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1304
+            return new \OC\Files\AppData\Factory(
1305
+                $c->get(IRootFolder::class),
1306
+                $c->get(SystemConfig::class)
1307
+            );
1308
+        });
1309
+
1310
+        $this->registerService('LockdownManager', function (ContainerInterface $c) {
1311
+            return new LockdownManager(function () use ($c) {
1312
+                return $c->get(ISession::class);
1313
+            });
1314
+        });
1315
+
1316
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1317
+            return new DiscoveryService(
1318
+                $c->get(ICacheFactory::class),
1319
+                $c->get(IClientService::class)
1320
+            );
1321
+        });
1322
+
1323
+        $this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1324
+            return new CloudIdManager($c->get(\OCP\Contacts\IManager::class), $c->get(IURLGenerator::class), $c->get(IUserManager::class));
1325
+        });
1326
+
1327
+        $this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1328
+
1329
+        $this->registerService(ICloudFederationProviderManager::class, function (ContainerInterface $c) {
1330
+            return new CloudFederationProviderManager(
1331
+                $c->get(IAppManager::class),
1332
+                $c->get(IClientService::class),
1333
+                $c->get(ICloudIdManager::class),
1334
+                $c->get(ILogger::class)
1335
+            );
1336
+        });
1337
+
1338
+        $this->registerService(ICloudFederationFactory::class, function (Server $c) {
1339
+            return new CloudFederationFactory();
1340
+        });
1341
+
1342
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1343
+        /** @deprecated 19.0.0 */
1344
+        $this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1345
+
1346
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1347
+        /** @deprecated 19.0.0 */
1348
+        $this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1349
+
1350
+        $this->registerService(Defaults::class, function (Server $c) {
1351
+            return new Defaults(
1352
+                $c->getThemingDefaults()
1353
+            );
1354
+        });
1355
+        /** @deprecated 19.0.0 */
1356
+        $this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1357
+
1358
+        $this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1359
+            return $c->get(\OCP\IUserSession::class)->getSession();
1360
+        }, false);
1361
+
1362
+        $this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1363
+            return new ShareHelper(
1364
+                $c->get(\OCP\Share\IManager::class)
1365
+            );
1366
+        });
1367
+
1368
+        $this->registerService(Installer::class, function (ContainerInterface $c) {
1369
+            return new Installer(
1370
+                $c->get(AppFetcher::class),
1371
+                $c->get(IClientService::class),
1372
+                $c->get(ITempManager::class),
1373
+                $c->get(LoggerInterface::class),
1374
+                $c->get(\OCP\IConfig::class),
1375
+                \OC::$CLI
1376
+            );
1377
+        });
1378
+
1379
+        $this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1380
+            return new ApiFactory($c->get(IClientService::class));
1381
+        });
1382
+
1383
+        $this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1384
+            $memcacheFactory = $c->get(ICacheFactory::class);
1385
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1386
+        });
1387
+
1388
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1389
+        $this->registerAlias(IAccountManager::class, AccountManager::class);
1390
+
1391
+        $this->registerAlias(IStorageFactory::class, StorageFactory::class);
1392
+
1393
+        $this->registerAlias(IDashboardManager::class, DashboardManager::class);
1394
+        $this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1395
+        $this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1396
+
1397
+        $this->registerAlias(ISubAdmin::class, SubAdmin::class);
1398
+
1399
+        $this->registerAlias(IInitialStateService::class, InitialStateService::class);
1400
+
1401
+        $this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1402
+
1403
+        $this->connectDispatcher();
1404
+    }
1405
+
1406
+    public function boot() {
1407
+        /** @var HookConnector $hookConnector */
1408
+        $hookConnector = $this->get(HookConnector::class);
1409
+        $hookConnector->viewToNode();
1410
+    }
1411
+
1412
+    /**
1413
+     * @return \OCP\Calendar\IManager
1414
+     * @deprecated 20.0.0
1415
+     */
1416
+    public function getCalendarManager() {
1417
+        return $this->get(\OC\Calendar\Manager::class);
1418
+    }
1419
+
1420
+    /**
1421
+     * @return \OCP\Calendar\Resource\IManager
1422
+     * @deprecated 20.0.0
1423
+     */
1424
+    public function getCalendarResourceBackendManager() {
1425
+        return $this->get(\OC\Calendar\Resource\Manager::class);
1426
+    }
1427
+
1428
+    /**
1429
+     * @return \OCP\Calendar\Room\IManager
1430
+     * @deprecated 20.0.0
1431
+     */
1432
+    public function getCalendarRoomBackendManager() {
1433
+        return $this->get(\OC\Calendar\Room\Manager::class);
1434
+    }
1435
+
1436
+    private function connectDispatcher() {
1437
+        $dispatcher = $this->get(SymfonyAdapter::class);
1438
+
1439
+        // Delete avatar on user deletion
1440
+        $dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1441
+            $logger = $this->get(ILogger::class);
1442
+            $manager = $this->getAvatarManager();
1443
+            /** @var IUser $user */
1444
+            $user = $e->getSubject();
1445
+
1446
+            try {
1447
+                $avatar = $manager->getAvatar($user->getUID());
1448
+                $avatar->remove();
1449
+            } catch (NotFoundException $e) {
1450
+                // no avatar to remove
1451
+            } catch (\Exception $e) {
1452
+                // Ignore exceptions
1453
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1454
+            }
1455
+        });
1456
+
1457
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1458
+            $manager = $this->getAvatarManager();
1459
+            /** @var IUser $user */
1460
+            $user = $e->getSubject();
1461
+            $feature = $e->getArgument('feature');
1462
+            $oldValue = $e->getArgument('oldValue');
1463
+            $value = $e->getArgument('value');
1464
+
1465
+            // We only change the avatar on display name changes
1466
+            if ($feature !== 'displayName') {
1467
+                return;
1468
+            }
1469
+
1470
+            try {
1471
+                $avatar = $manager->getAvatar($user->getUID());
1472
+                $avatar->userChanged($feature, $oldValue, $value);
1473
+            } catch (NotFoundException $e) {
1474
+                // no avatar to remove
1475
+            }
1476
+        });
1477
+
1478
+        /** @var IEventDispatcher $eventDispatched */
1479
+        $eventDispatched = $this->get(IEventDispatcher::class);
1480
+        $eventDispatched->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1481
+        $eventDispatched->addServiceListener(PostLoginEvent::class, UserLoggedInListener::class);
1482
+    }
1483
+
1484
+    /**
1485
+     * @return \OCP\Contacts\IManager
1486
+     * @deprecated 20.0.0
1487
+     */
1488
+    public function getContactsManager() {
1489
+        return $this->get(\OCP\Contacts\IManager::class);
1490
+    }
1491
+
1492
+    /**
1493
+     * @return \OC\Encryption\Manager
1494
+     * @deprecated 20.0.0
1495
+     */
1496
+    public function getEncryptionManager() {
1497
+        return $this->get(\OCP\Encryption\IManager::class);
1498
+    }
1499
+
1500
+    /**
1501
+     * @return \OC\Encryption\File
1502
+     * @deprecated 20.0.0
1503
+     */
1504
+    public function getEncryptionFilesHelper() {
1505
+        return $this->get(IFile::class);
1506
+    }
1507
+
1508
+    /**
1509
+     * @return \OCP\Encryption\Keys\IStorage
1510
+     * @deprecated 20.0.0
1511
+     */
1512
+    public function getEncryptionKeyStorage() {
1513
+        return $this->get(IStorage::class);
1514
+    }
1515
+
1516
+    /**
1517
+     * The current request object holding all information about the request
1518
+     * currently being processed is returned from this method.
1519
+     * In case the current execution was not initiated by a web request null is returned
1520
+     *
1521
+     * @return \OCP\IRequest
1522
+     * @deprecated 20.0.0
1523
+     */
1524
+    public function getRequest() {
1525
+        return $this->get(IRequest::class);
1526
+    }
1527
+
1528
+    /**
1529
+     * Returns the preview manager which can create preview images for a given file
1530
+     *
1531
+     * @return IPreview
1532
+     * @deprecated 20.0.0
1533
+     */
1534
+    public function getPreviewManager() {
1535
+        return $this->get(IPreview::class);
1536
+    }
1537
+
1538
+    /**
1539
+     * Returns the tag manager which can get and set tags for different object types
1540
+     *
1541
+     * @see \OCP\ITagManager::load()
1542
+     * @return ITagManager
1543
+     * @deprecated 20.0.0
1544
+     */
1545
+    public function getTagManager() {
1546
+        return $this->get(ITagManager::class);
1547
+    }
1548
+
1549
+    /**
1550
+     * Returns the system-tag manager
1551
+     *
1552
+     * @return ISystemTagManager
1553
+     *
1554
+     * @since 9.0.0
1555
+     * @deprecated 20.0.0
1556
+     */
1557
+    public function getSystemTagManager() {
1558
+        return $this->get(ISystemTagManager::class);
1559
+    }
1560
+
1561
+    /**
1562
+     * Returns the system-tag object mapper
1563
+     *
1564
+     * @return ISystemTagObjectMapper
1565
+     *
1566
+     * @since 9.0.0
1567
+     * @deprecated 20.0.0
1568
+     */
1569
+    public function getSystemTagObjectMapper() {
1570
+        return $this->get(ISystemTagObjectMapper::class);
1571
+    }
1572
+
1573
+    /**
1574
+     * Returns the avatar manager, used for avatar functionality
1575
+     *
1576
+     * @return IAvatarManager
1577
+     * @deprecated 20.0.0
1578
+     */
1579
+    public function getAvatarManager() {
1580
+        return $this->get(IAvatarManager::class);
1581
+    }
1582
+
1583
+    /**
1584
+     * Returns the root folder of ownCloud's data directory
1585
+     *
1586
+     * @return IRootFolder
1587
+     * @deprecated 20.0.0
1588
+     */
1589
+    public function getRootFolder() {
1590
+        return $this->get(IRootFolder::class);
1591
+    }
1592
+
1593
+    /**
1594
+     * Returns the root folder of ownCloud's data directory
1595
+     * This is the lazy variant so this gets only initialized once it
1596
+     * is actually used.
1597
+     *
1598
+     * @return IRootFolder
1599
+     * @deprecated 20.0.0
1600
+     */
1601
+    public function getLazyRootFolder() {
1602
+        return $this->get(IRootFolder::class);
1603
+    }
1604
+
1605
+    /**
1606
+     * Returns a view to ownCloud's files folder
1607
+     *
1608
+     * @param string $userId user ID
1609
+     * @return \OCP\Files\Folder|null
1610
+     * @deprecated 20.0.0
1611
+     */
1612
+    public function getUserFolder($userId = null) {
1613
+        if ($userId === null) {
1614
+            $user = $this->get(IUserSession::class)->getUser();
1615
+            if (!$user) {
1616
+                return null;
1617
+            }
1618
+            $userId = $user->getUID();
1619
+        }
1620
+        $root = $this->get(IRootFolder::class);
1621
+        return $root->getUserFolder($userId);
1622
+    }
1623
+
1624
+    /**
1625
+     * @return \OC\User\Manager
1626
+     * @deprecated 20.0.0
1627
+     */
1628
+    public function getUserManager() {
1629
+        return $this->get(IUserManager::class);
1630
+    }
1631
+
1632
+    /**
1633
+     * @return \OC\Group\Manager
1634
+     * @deprecated 20.0.0
1635
+     */
1636
+    public function getGroupManager() {
1637
+        return $this->get(IGroupManager::class);
1638
+    }
1639
+
1640
+    /**
1641
+     * @return \OC\User\Session
1642
+     * @deprecated 20.0.0
1643
+     */
1644
+    public function getUserSession() {
1645
+        return $this->get(IUserSession::class);
1646
+    }
1647
+
1648
+    /**
1649
+     * @return \OCP\ISession
1650
+     * @deprecated 20.0.0
1651
+     */
1652
+    public function getSession() {
1653
+        return $this->get(IUserSession::class)->getSession();
1654
+    }
1655
+
1656
+    /**
1657
+     * @param \OCP\ISession $session
1658
+     */
1659
+    public function setSession(\OCP\ISession $session) {
1660
+        $this->get(SessionStorage::class)->setSession($session);
1661
+        $this->get(IUserSession::class)->setSession($session);
1662
+        $this->get(Store::class)->setSession($session);
1663
+    }
1664
+
1665
+    /**
1666
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1667
+     * @deprecated 20.0.0
1668
+     */
1669
+    public function getTwoFactorAuthManager() {
1670
+        return $this->get(\OC\Authentication\TwoFactorAuth\Manager::class);
1671
+    }
1672
+
1673
+    /**
1674
+     * @return \OC\NavigationManager
1675
+     * @deprecated 20.0.0
1676
+     */
1677
+    public function getNavigationManager() {
1678
+        return $this->get(INavigationManager::class);
1679
+    }
1680
+
1681
+    /**
1682
+     * @return \OCP\IConfig
1683
+     * @deprecated 20.0.0
1684
+     */
1685
+    public function getConfig() {
1686
+        return $this->get(AllConfig::class);
1687
+    }
1688
+
1689
+    /**
1690
+     * @return \OC\SystemConfig
1691
+     * @deprecated 20.0.0
1692
+     */
1693
+    public function getSystemConfig() {
1694
+        return $this->get(SystemConfig::class);
1695
+    }
1696
+
1697
+    /**
1698
+     * Returns the app config manager
1699
+     *
1700
+     * @return IAppConfig
1701
+     * @deprecated 20.0.0
1702
+     */
1703
+    public function getAppConfig() {
1704
+        return $this->get(IAppConfig::class);
1705
+    }
1706
+
1707
+    /**
1708
+     * @return IFactory
1709
+     * @deprecated 20.0.0
1710
+     */
1711
+    public function getL10NFactory() {
1712
+        return $this->get(IFactory::class);
1713
+    }
1714
+
1715
+    /**
1716
+     * get an L10N instance
1717
+     *
1718
+     * @param string $app appid
1719
+     * @param string $lang
1720
+     * @return IL10N
1721
+     * @deprecated 20.0.0
1722
+     */
1723
+    public function getL10N($app, $lang = null) {
1724
+        return $this->get(IFactory::class)->get($app, $lang);
1725
+    }
1726
+
1727
+    /**
1728
+     * @return IURLGenerator
1729
+     * @deprecated 20.0.0
1730
+     */
1731
+    public function getURLGenerator() {
1732
+        return $this->get(IURLGenerator::class);
1733
+    }
1734
+
1735
+    /**
1736
+     * @return AppFetcher
1737
+     * @deprecated 20.0.0
1738
+     */
1739
+    public function getAppFetcher() {
1740
+        return $this->get(AppFetcher::class);
1741
+    }
1742
+
1743
+    /**
1744
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1745
+     * getMemCacheFactory() instead.
1746
+     *
1747
+     * @return ICache
1748
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1749
+     */
1750
+    public function getCache() {
1751
+        return $this->get(ICache::class);
1752
+    }
1753
+
1754
+    /**
1755
+     * Returns an \OCP\CacheFactory instance
1756
+     *
1757
+     * @return \OCP\ICacheFactory
1758
+     * @deprecated 20.0.0
1759
+     */
1760
+    public function getMemCacheFactory() {
1761
+        return $this->get(ICacheFactory::class);
1762
+    }
1763
+
1764
+    /**
1765
+     * Returns an \OC\RedisFactory instance
1766
+     *
1767
+     * @return \OC\RedisFactory
1768
+     * @deprecated 20.0.0
1769
+     */
1770
+    public function getGetRedisFactory() {
1771
+        return $this->get('RedisFactory');
1772
+    }
1773
+
1774
+
1775
+    /**
1776
+     * Returns the current session
1777
+     *
1778
+     * @return \OCP\IDBConnection
1779
+     * @deprecated 20.0.0
1780
+     */
1781
+    public function getDatabaseConnection() {
1782
+        return $this->get(IDBConnection::class);
1783
+    }
1784
+
1785
+    /**
1786
+     * Returns the activity manager
1787
+     *
1788
+     * @return \OCP\Activity\IManager
1789
+     * @deprecated 20.0.0
1790
+     */
1791
+    public function getActivityManager() {
1792
+        return $this->get(\OCP\Activity\IManager::class);
1793
+    }
1794
+
1795
+    /**
1796
+     * Returns an job list for controlling background jobs
1797
+     *
1798
+     * @return IJobList
1799
+     * @deprecated 20.0.0
1800
+     */
1801
+    public function getJobList() {
1802
+        return $this->get(IJobList::class);
1803
+    }
1804
+
1805
+    /**
1806
+     * Returns a logger instance
1807
+     *
1808
+     * @return ILogger
1809
+     * @deprecated 20.0.0
1810
+     */
1811
+    public function getLogger() {
1812
+        return $this->get(ILogger::class);
1813
+    }
1814
+
1815
+    /**
1816
+     * @return ILogFactory
1817
+     * @throws \OCP\AppFramework\QueryException
1818
+     * @deprecated 20.0.0
1819
+     */
1820
+    public function getLogFactory() {
1821
+        return $this->get(ILogFactory::class);
1822
+    }
1823
+
1824
+    /**
1825
+     * Returns a router for generating and matching urls
1826
+     *
1827
+     * @return IRouter
1828
+     * @deprecated 20.0.0
1829
+     */
1830
+    public function getRouter() {
1831
+        return $this->get(IRouter::class);
1832
+    }
1833
+
1834
+    /**
1835
+     * Returns a search instance
1836
+     *
1837
+     * @return ISearch
1838
+     * @deprecated 20.0.0
1839
+     */
1840
+    public function getSearch() {
1841
+        return $this->get(ISearch::class);
1842
+    }
1843
+
1844
+    /**
1845
+     * Returns a SecureRandom instance
1846
+     *
1847
+     * @return \OCP\Security\ISecureRandom
1848
+     * @deprecated 20.0.0
1849
+     */
1850
+    public function getSecureRandom() {
1851
+        return $this->get(ISecureRandom::class);
1852
+    }
1853
+
1854
+    /**
1855
+     * Returns a Crypto instance
1856
+     *
1857
+     * @return ICrypto
1858
+     * @deprecated 20.0.0
1859
+     */
1860
+    public function getCrypto() {
1861
+        return $this->get(ICrypto::class);
1862
+    }
1863
+
1864
+    /**
1865
+     * Returns a Hasher instance
1866
+     *
1867
+     * @return IHasher
1868
+     * @deprecated 20.0.0
1869
+     */
1870
+    public function getHasher() {
1871
+        return $this->get(IHasher::class);
1872
+    }
1873
+
1874
+    /**
1875
+     * Returns a CredentialsManager instance
1876
+     *
1877
+     * @return ICredentialsManager
1878
+     * @deprecated 20.0.0
1879
+     */
1880
+    public function getCredentialsManager() {
1881
+        return $this->get(ICredentialsManager::class);
1882
+    }
1883
+
1884
+    /**
1885
+     * Get the certificate manager
1886
+     *
1887
+     * @return \OCP\ICertificateManager
1888
+     */
1889
+    public function getCertificateManager() {
1890
+        return $this->get(ICertificateManager::class);
1891
+    }
1892
+
1893
+    /**
1894
+     * Returns an instance of the HTTP client service
1895
+     *
1896
+     * @return IClientService
1897
+     * @deprecated 20.0.0
1898
+     */
1899
+    public function getHTTPClientService() {
1900
+        return $this->get(IClientService::class);
1901
+    }
1902
+
1903
+    /**
1904
+     * Create a new event source
1905
+     *
1906
+     * @return \OCP\IEventSource
1907
+     * @deprecated 20.0.0
1908
+     */
1909
+    public function createEventSource() {
1910
+        return new \OC_EventSource();
1911
+    }
1912
+
1913
+    /**
1914
+     * Get the active event logger
1915
+     *
1916
+     * The returned logger only logs data when debug mode is enabled
1917
+     *
1918
+     * @return IEventLogger
1919
+     * @deprecated 20.0.0
1920
+     */
1921
+    public function getEventLogger() {
1922
+        return $this->get(IEventLogger::class);
1923
+    }
1924
+
1925
+    /**
1926
+     * Get the active query logger
1927
+     *
1928
+     * The returned logger only logs data when debug mode is enabled
1929
+     *
1930
+     * @return IQueryLogger
1931
+     * @deprecated 20.0.0
1932
+     */
1933
+    public function getQueryLogger() {
1934
+        return $this->get(IQueryLogger::class);
1935
+    }
1936
+
1937
+    /**
1938
+     * Get the manager for temporary files and folders
1939
+     *
1940
+     * @return \OCP\ITempManager
1941
+     * @deprecated 20.0.0
1942
+     */
1943
+    public function getTempManager() {
1944
+        return $this->get(ITempManager::class);
1945
+    }
1946
+
1947
+    /**
1948
+     * Get the app manager
1949
+     *
1950
+     * @return \OCP\App\IAppManager
1951
+     * @deprecated 20.0.0
1952
+     */
1953
+    public function getAppManager() {
1954
+        return $this->get(IAppManager::class);
1955
+    }
1956
+
1957
+    /**
1958
+     * Creates a new mailer
1959
+     *
1960
+     * @return IMailer
1961
+     * @deprecated 20.0.0
1962
+     */
1963
+    public function getMailer() {
1964
+        return $this->get(IMailer::class);
1965
+    }
1966
+
1967
+    /**
1968
+     * Get the webroot
1969
+     *
1970
+     * @return string
1971
+     * @deprecated 20.0.0
1972
+     */
1973
+    public function getWebRoot() {
1974
+        return $this->webRoot;
1975
+    }
1976
+
1977
+    /**
1978
+     * @return \OC\OCSClient
1979
+     * @deprecated 20.0.0
1980
+     */
1981
+    public function getOcsClient() {
1982
+        return $this->get('OcsClient');
1983
+    }
1984
+
1985
+    /**
1986
+     * @return IDateTimeZone
1987
+     * @deprecated 20.0.0
1988
+     */
1989
+    public function getDateTimeZone() {
1990
+        return $this->get(IDateTimeZone::class);
1991
+    }
1992
+
1993
+    /**
1994
+     * @return IDateTimeFormatter
1995
+     * @deprecated 20.0.0
1996
+     */
1997
+    public function getDateTimeFormatter() {
1998
+        return $this->get(IDateTimeFormatter::class);
1999
+    }
2000
+
2001
+    /**
2002
+     * @return IMountProviderCollection
2003
+     * @deprecated 20.0.0
2004
+     */
2005
+    public function getMountProviderCollection() {
2006
+        return $this->get(IMountProviderCollection::class);
2007
+    }
2008
+
2009
+    /**
2010
+     * Get the IniWrapper
2011
+     *
2012
+     * @return IniGetWrapper
2013
+     * @deprecated 20.0.0
2014
+     */
2015
+    public function getIniWrapper() {
2016
+        return $this->get(IniGetWrapper::class);
2017
+    }
2018
+
2019
+    /**
2020
+     * @return \OCP\Command\IBus
2021
+     * @deprecated 20.0.0
2022
+     */
2023
+    public function getCommandBus() {
2024
+        return $this->get(IBus::class);
2025
+    }
2026
+
2027
+    /**
2028
+     * Get the trusted domain helper
2029
+     *
2030
+     * @return TrustedDomainHelper
2031
+     * @deprecated 20.0.0
2032
+     */
2033
+    public function getTrustedDomainHelper() {
2034
+        return $this->get(TrustedDomainHelper::class);
2035
+    }
2036
+
2037
+    /**
2038
+     * Get the locking provider
2039
+     *
2040
+     * @return ILockingProvider
2041
+     * @since 8.1.0
2042
+     * @deprecated 20.0.0
2043
+     */
2044
+    public function getLockingProvider() {
2045
+        return $this->get(ILockingProvider::class);
2046
+    }
2047
+
2048
+    /**
2049
+     * @return IMountManager
2050
+     * @deprecated 20.0.0
2051
+     **/
2052
+    public function getMountManager() {
2053
+        return $this->get(IMountManager::class);
2054
+    }
2055
+
2056
+    /**
2057
+     * @return IUserMountCache
2058
+     * @deprecated 20.0.0
2059
+     */
2060
+    public function getUserMountCache() {
2061
+        return $this->get(IUserMountCache::class);
2062
+    }
2063
+
2064
+    /**
2065
+     * Get the MimeTypeDetector
2066
+     *
2067
+     * @return IMimeTypeDetector
2068
+     * @deprecated 20.0.0
2069
+     */
2070
+    public function getMimeTypeDetector() {
2071
+        return $this->get(IMimeTypeDetector::class);
2072
+    }
2073
+
2074
+    /**
2075
+     * Get the MimeTypeLoader
2076
+     *
2077
+     * @return IMimeTypeLoader
2078
+     * @deprecated 20.0.0
2079
+     */
2080
+    public function getMimeTypeLoader() {
2081
+        return $this->get(IMimeTypeLoader::class);
2082
+    }
2083
+
2084
+    /**
2085
+     * Get the manager of all the capabilities
2086
+     *
2087
+     * @return CapabilitiesManager
2088
+     * @deprecated 20.0.0
2089
+     */
2090
+    public function getCapabilitiesManager() {
2091
+        return $this->get(CapabilitiesManager::class);
2092
+    }
2093
+
2094
+    /**
2095
+     * Get the EventDispatcher
2096
+     *
2097
+     * @return EventDispatcherInterface
2098
+     * @since 8.2.0
2099
+     * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2100
+     */
2101
+    public function getEventDispatcher() {
2102
+        return $this->get(\OC\EventDispatcher\SymfonyAdapter::class);
2103
+    }
2104
+
2105
+    /**
2106
+     * Get the Notification Manager
2107
+     *
2108
+     * @return \OCP\Notification\IManager
2109
+     * @since 8.2.0
2110
+     * @deprecated 20.0.0
2111
+     */
2112
+    public function getNotificationManager() {
2113
+        return $this->get(\OCP\Notification\IManager::class);
2114
+    }
2115
+
2116
+    /**
2117
+     * @return ICommentsManager
2118
+     * @deprecated 20.0.0
2119
+     */
2120
+    public function getCommentsManager() {
2121
+        return $this->get(ICommentsManager::class);
2122
+    }
2123
+
2124
+    /**
2125
+     * @return \OCA\Theming\ThemingDefaults
2126
+     * @deprecated 20.0.0
2127
+     */
2128
+    public function getThemingDefaults() {
2129
+        return $this->get('ThemingDefaults');
2130
+    }
2131
+
2132
+    /**
2133
+     * @return \OC\IntegrityCheck\Checker
2134
+     * @deprecated 20.0.0
2135
+     */
2136
+    public function getIntegrityCodeChecker() {
2137
+        return $this->get('IntegrityCodeChecker');
2138
+    }
2139
+
2140
+    /**
2141
+     * @return \OC\Session\CryptoWrapper
2142
+     * @deprecated 20.0.0
2143
+     */
2144
+    public function getSessionCryptoWrapper() {
2145
+        return $this->get('CryptoWrapper');
2146
+    }
2147
+
2148
+    /**
2149
+     * @return CsrfTokenManager
2150
+     * @deprecated 20.0.0
2151
+     */
2152
+    public function getCsrfTokenManager() {
2153
+        return $this->get(CsrfTokenManager::class);
2154
+    }
2155
+
2156
+    /**
2157
+     * @return Throttler
2158
+     * @deprecated 20.0.0
2159
+     */
2160
+    public function getBruteForceThrottler() {
2161
+        return $this->get(Throttler::class);
2162
+    }
2163
+
2164
+    /**
2165
+     * @return IContentSecurityPolicyManager
2166
+     * @deprecated 20.0.0
2167
+     */
2168
+    public function getContentSecurityPolicyManager() {
2169
+        return $this->get(ContentSecurityPolicyManager::class);
2170
+    }
2171
+
2172
+    /**
2173
+     * @return ContentSecurityPolicyNonceManager
2174
+     * @deprecated 20.0.0
2175
+     */
2176
+    public function getContentSecurityPolicyNonceManager() {
2177
+        return $this->get(ContentSecurityPolicyNonceManager::class);
2178
+    }
2179
+
2180
+    /**
2181
+     * Not a public API as of 8.2, wait for 9.0
2182
+     *
2183
+     * @return \OCA\Files_External\Service\BackendService
2184
+     * @deprecated 20.0.0
2185
+     */
2186
+    public function getStoragesBackendService() {
2187
+        return $this->get(BackendService::class);
2188
+    }
2189
+
2190
+    /**
2191
+     * Not a public API as of 8.2, wait for 9.0
2192
+     *
2193
+     * @return \OCA\Files_External\Service\GlobalStoragesService
2194
+     * @deprecated 20.0.0
2195
+     */
2196
+    public function getGlobalStoragesService() {
2197
+        return $this->get(GlobalStoragesService::class);
2198
+    }
2199
+
2200
+    /**
2201
+     * Not a public API as of 8.2, wait for 9.0
2202
+     *
2203
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
2204
+     * @deprecated 20.0.0
2205
+     */
2206
+    public function getUserGlobalStoragesService() {
2207
+        return $this->get(UserGlobalStoragesService::class);
2208
+    }
2209
+
2210
+    /**
2211
+     * Not a public API as of 8.2, wait for 9.0
2212
+     *
2213
+     * @return \OCA\Files_External\Service\UserStoragesService
2214
+     * @deprecated 20.0.0
2215
+     */
2216
+    public function getUserStoragesService() {
2217
+        return $this->get(UserStoragesService::class);
2218
+    }
2219
+
2220
+    /**
2221
+     * @return \OCP\Share\IManager
2222
+     * @deprecated 20.0.0
2223
+     */
2224
+    public function getShareManager() {
2225
+        return $this->get(\OCP\Share\IManager::class);
2226
+    }
2227
+
2228
+    /**
2229
+     * @return \OCP\Collaboration\Collaborators\ISearch
2230
+     * @deprecated 20.0.0
2231
+     */
2232
+    public function getCollaboratorSearch() {
2233
+        return $this->get(\OCP\Collaboration\Collaborators\ISearch::class);
2234
+    }
2235
+
2236
+    /**
2237
+     * @return \OCP\Collaboration\AutoComplete\IManager
2238
+     * @deprecated 20.0.0
2239
+     */
2240
+    public function getAutoCompleteManager() {
2241
+        return $this->get(IManager::class);
2242
+    }
2243
+
2244
+    /**
2245
+     * Returns the LDAP Provider
2246
+     *
2247
+     * @return \OCP\LDAP\ILDAPProvider
2248
+     * @deprecated 20.0.0
2249
+     */
2250
+    public function getLDAPProvider() {
2251
+        return $this->get('LDAPProvider');
2252
+    }
2253
+
2254
+    /**
2255
+     * @return \OCP\Settings\IManager
2256
+     * @deprecated 20.0.0
2257
+     */
2258
+    public function getSettingsManager() {
2259
+        return $this->get(\OC\Settings\Manager::class);
2260
+    }
2261
+
2262
+    /**
2263
+     * @return \OCP\Files\IAppData
2264
+     * @deprecated 20.0.0
2265
+     */
2266
+    public function getAppDataDir($app) {
2267
+        /** @var \OC\Files\AppData\Factory $factory */
2268
+        $factory = $this->get(\OC\Files\AppData\Factory::class);
2269
+        return $factory->get($app);
2270
+    }
2271
+
2272
+    /**
2273
+     * @return \OCP\Lockdown\ILockdownManager
2274
+     * @deprecated 20.0.0
2275
+     */
2276
+    public function getLockdownManager() {
2277
+        return $this->get('LockdownManager');
2278
+    }
2279
+
2280
+    /**
2281
+     * @return \OCP\Federation\ICloudIdManager
2282
+     * @deprecated 20.0.0
2283
+     */
2284
+    public function getCloudIdManager() {
2285
+        return $this->get(ICloudIdManager::class);
2286
+    }
2287
+
2288
+    /**
2289
+     * @return \OCP\GlobalScale\IConfig
2290
+     * @deprecated 20.0.0
2291
+     */
2292
+    public function getGlobalScaleConfig() {
2293
+        return $this->get(IConfig::class);
2294
+    }
2295
+
2296
+    /**
2297
+     * @return \OCP\Federation\ICloudFederationProviderManager
2298
+     * @deprecated 20.0.0
2299
+     */
2300
+    public function getCloudFederationProviderManager() {
2301
+        return $this->get(ICloudFederationProviderManager::class);
2302
+    }
2303
+
2304
+    /**
2305
+     * @return \OCP\Remote\Api\IApiFactory
2306
+     * @deprecated 20.0.0
2307
+     */
2308
+    public function getRemoteApiFactory() {
2309
+        return $this->get(IApiFactory::class);
2310
+    }
2311
+
2312
+    /**
2313
+     * @return \OCP\Federation\ICloudFederationFactory
2314
+     * @deprecated 20.0.0
2315
+     */
2316
+    public function getCloudFederationFactory() {
2317
+        return $this->get(ICloudFederationFactory::class);
2318
+    }
2319
+
2320
+    /**
2321
+     * @return \OCP\Remote\IInstanceFactory
2322
+     * @deprecated 20.0.0
2323
+     */
2324
+    public function getRemoteInstanceFactory() {
2325
+        return $this->get(IInstanceFactory::class);
2326
+    }
2327
+
2328
+    /**
2329
+     * @return IStorageFactory
2330
+     * @deprecated 20.0.0
2331
+     */
2332
+    public function getStorageFactory() {
2333
+        return $this->get(IStorageFactory::class);
2334
+    }
2335
+
2336
+    /**
2337
+     * Get the Preview GeneratorHelper
2338
+     *
2339
+     * @return GeneratorHelper
2340
+     * @since 17.0.0
2341
+     * @deprecated 20.0.0
2342
+     */
2343
+    public function getGeneratorHelper() {
2344
+        return $this->get(\OC\Preview\GeneratorHelper::class);
2345
+    }
2346
+
2347
+    private function registerDeprecatedAlias(string $alias, string $target) {
2348
+        $this->registerService($alias, function (ContainerInterface $container) use ($target, $alias) {
2349
+            try {
2350
+                /** @var ILogger $logger */
2351
+                $logger = $container->get(ILogger::class);
2352
+                $logger->debug('The requested alias "' . $alias . '" is deprecated. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2353
+            } catch (ContainerExceptionInterface $e) {
2354
+                // Could not get logger. Continue
2355
+            }
2356
+
2357
+            return $container->get($target);
2358
+        }, false);
2359
+    }
2360 2360
 }
Please login to merge, or discard this patch.
Spacing   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -281,10 +281,10 @@  discard block
 block discarded – undo
281 281
 		$this->registerParameter('isCLI', \OC::$CLI);
282 282
 		$this->registerParameter('serverRoot', \OC::$SERVERROOT);
283 283
 
284
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
284
+		$this->registerService(ContainerInterface::class, function(ContainerInterface $c) {
285 285
 			return $c;
286 286
 		});
287
-		$this->registerService(\OCP\IServerContainer::class, function (ContainerInterface $c) {
287
+		$this->registerService(\OCP\IServerContainer::class, function(ContainerInterface $c) {
288 288
 			return $c;
289 289
 		});
290 290
 
@@ -309,11 +309,11 @@  discard block
 block discarded – undo
309 309
 
310 310
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
311 311
 
312
-		$this->registerService(View::class, function (Server $c) {
312
+		$this->registerService(View::class, function(Server $c) {
313 313
 			return new View();
314 314
 		}, false);
315 315
 
316
-		$this->registerService(IPreview::class, function (ContainerInterface $c) {
316
+		$this->registerService(IPreview::class, function(ContainerInterface $c) {
317 317
 			return new PreviewManager(
318 318
 				$c->get(\OCP\IConfig::class),
319 319
 				$c->get(IRootFolder::class),
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 		/** @deprecated 19.0.0 */
332 332
 		$this->registerDeprecatedAlias('PreviewManager', IPreview::class);
333 333
 
334
-		$this->registerService(\OC\Preview\Watcher::class, function (ContainerInterface $c) {
334
+		$this->registerService(\OC\Preview\Watcher::class, function(ContainerInterface $c) {
335 335
 			return new \OC\Preview\Watcher(
336 336
 				new \OC\Preview\Storage\Root(
337 337
 					$c->get(IRootFolder::class),
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 			);
341 341
 		});
342 342
 
343
-		$this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
343
+		$this->registerService(\OCP\Encryption\IManager::class, function(Server $c) {
344 344
 			$view = new View();
345 345
 			$util = new Encryption\Util(
346 346
 				$view,
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
 
363 363
 		/** @deprecated 21.0.0 */
364 364
 		$this->registerDeprecatedAlias('EncryptionFileHelper', IFile::class);
365
-		$this->registerService(IFile::class, function (ContainerInterface $c) {
365
+		$this->registerService(IFile::class, function(ContainerInterface $c) {
366 366
 			$util = new Encryption\Util(
367 367
 				new View(),
368 368
 				$c->get(IUserManager::class),
@@ -378,7 +378,7 @@  discard block
 block discarded – undo
378 378
 
379 379
 		/** @deprecated 21.0.0 */
380 380
 		$this->registerDeprecatedAlias('EncryptionKeyStorage', IStorage::class);
381
-		$this->registerService(IStorage::class, function (ContainerInterface $c) {
381
+		$this->registerService(IStorage::class, function(ContainerInterface $c) {
382 382
 			$view = new View();
383 383
 			$util = new Encryption\Util(
384 384
 				$view,
@@ -401,22 +401,22 @@  discard block
 block discarded – undo
401 401
 		/** @deprecated 19.0.0 */
402 402
 		$this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
403 403
 
404
-		$this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
404
+		$this->registerService('SystemTagManagerFactory', function(ContainerInterface $c) {
405 405
 			/** @var \OCP\IConfig $config */
406 406
 			$config = $c->get(\OCP\IConfig::class);
407 407
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
408 408
 			return new $factoryClass($this);
409 409
 		});
410
-		$this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
410
+		$this->registerService(ISystemTagManager::class, function(ContainerInterface $c) {
411 411
 			return $c->get('SystemTagManagerFactory')->getManager();
412 412
 		});
413 413
 		/** @deprecated 19.0.0 */
414 414
 		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
415 415
 
416
-		$this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
416
+		$this->registerService(ISystemTagObjectMapper::class, function(ContainerInterface $c) {
417 417
 			return $c->get('SystemTagManagerFactory')->getObjectMapper();
418 418
 		});
419
-		$this->registerService('RootFolder', function (ContainerInterface $c) {
419
+		$this->registerService('RootFolder', function(ContainerInterface $c) {
420 420
 			$manager = \OC\Files\Filesystem::getMountManager(null);
421 421
 			$view = new View();
422 422
 			$root = new Root(
@@ -437,7 +437,7 @@  discard block
 block discarded – undo
437 437
 
438 438
 			return $root;
439 439
 		});
440
-		$this->registerService(HookConnector::class, function (ContainerInterface $c) {
440
+		$this->registerService(HookConnector::class, function(ContainerInterface $c) {
441 441
 			return new HookConnector(
442 442
 				$c->get(IRootFolder::class),
443 443
 				new View(),
@@ -449,8 +449,8 @@  discard block
 block discarded – undo
449 449
 		/** @deprecated 19.0.0 */
450 450
 		$this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
451 451
 
452
-		$this->registerService(IRootFolder::class, function (ContainerInterface $c) {
453
-			return new LazyRoot(function () use ($c) {
452
+		$this->registerService(IRootFolder::class, function(ContainerInterface $c) {
453
+			return new LazyRoot(function() use ($c) {
454 454
 				return $c->get('RootFolder');
455 455
 			});
456 456
 		});
@@ -461,44 +461,44 @@  discard block
 block discarded – undo
461 461
 		$this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
462 462
 		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
463 463
 
464
-		$this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
464
+		$this->registerService(\OCP\IGroupManager::class, function(ContainerInterface $c) {
465 465
 			$groupManager = new \OC\Group\Manager($this->get(IUserManager::class), $c->get(SymfonyAdapter::class), $this->get(ILogger::class));
466
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
466
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
467 467
 				/** @var IEventDispatcher $dispatcher */
468 468
 				$dispatcher = $this->get(IEventDispatcher::class);
469 469
 				$dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
470 470
 			});
471
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
471
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $group) {
472 472
 				/** @var IEventDispatcher $dispatcher */
473 473
 				$dispatcher = $this->get(IEventDispatcher::class);
474 474
 				$dispatcher->dispatchTyped(new GroupCreatedEvent($group));
475 475
 			});
476
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
476
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
477 477
 				/** @var IEventDispatcher $dispatcher */
478 478
 				$dispatcher = $this->get(IEventDispatcher::class);
479 479
 				$dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
480 480
 			});
481
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
481
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
482 482
 				/** @var IEventDispatcher $dispatcher */
483 483
 				$dispatcher = $this->get(IEventDispatcher::class);
484 484
 				$dispatcher->dispatchTyped(new GroupDeletedEvent($group));
485 485
 			});
486
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
486
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
487 487
 				/** @var IEventDispatcher $dispatcher */
488 488
 				$dispatcher = $this->get(IEventDispatcher::class);
489 489
 				$dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
490 490
 			});
491
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
491
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
492 492
 				/** @var IEventDispatcher $dispatcher */
493 493
 				$dispatcher = $this->get(IEventDispatcher::class);
494 494
 				$dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
495 495
 			});
496
-			$groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
496
+			$groupManager->listen('\OC\Group', 'preRemoveUser', function(\OC\Group\Group $group, \OC\User\User $user) {
497 497
 				/** @var IEventDispatcher $dispatcher */
498 498
 				$dispatcher = $this->get(IEventDispatcher::class);
499 499
 				$dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
500 500
 			});
501
-			$groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
501
+			$groupManager->listen('\OC\Group', 'postRemoveUser', function(\OC\Group\Group $group, \OC\User\User $user) {
502 502
 				/** @var IEventDispatcher $dispatcher */
503 503
 				$dispatcher = $this->get(IEventDispatcher::class);
504 504
 				$dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
@@ -508,7 +508,7 @@  discard block
 block discarded – undo
508 508
 		/** @deprecated 19.0.0 */
509 509
 		$this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
510 510
 
511
-		$this->registerService(Store::class, function (ContainerInterface $c) {
511
+		$this->registerService(Store::class, function(ContainerInterface $c) {
512 512
 			$session = $c->get(ISession::class);
513 513
 			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
514 514
 				$tokenProvider = $c->get(IProvider::class);
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
 		$this->registerAlias(IStore::class, Store::class);
522 522
 		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
523 523
 
524
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
524
+		$this->registerService(\OC\User\Session::class, function(Server $c) {
525 525
 			$manager = $c->get(IUserManager::class);
526 526
 			$session = new \OC\Session\Memory('');
527 527
 			$timeFactory = new TimeFactory();
@@ -547,26 +547,26 @@  discard block
 block discarded – undo
547 547
 				$c->get(IEventDispatcher::class)
548 548
 			);
549 549
 			/** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
550
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
550
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
551 551
 				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
552 552
 			});
553 553
 			/** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
554
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
554
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
555 555
 				/** @var \OC\User\User $user */
556 556
 				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
557 557
 			});
558 558
 			/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
559
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
559
+			$userSession->listen('\OC\User', 'preDelete', function($user) use ($legacyDispatcher) {
560 560
 				/** @var \OC\User\User $user */
561 561
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
562 562
 				$legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
563 563
 			});
564 564
 			/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
565
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
565
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
566 566
 				/** @var \OC\User\User $user */
567 567
 				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
568 568
 			});
569
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
569
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
570 570
 				/** @var \OC\User\User $user */
571 571
 				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
572 572
 
@@ -574,7 +574,7 @@  discard block
 block discarded – undo
574 574
 				$dispatcher = $this->get(IEventDispatcher::class);
575 575
 				$dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
576 576
 			});
577
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
577
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
578 578
 				/** @var \OC\User\User $user */
579 579
 				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
580 580
 
@@ -582,14 +582,14 @@  discard block
 block discarded – undo
582 582
 				$dispatcher = $this->get(IEventDispatcher::class);
583 583
 				$dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
584 584
 			});
585
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
585
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
586 586
 				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
587 587
 
588 588
 				/** @var IEventDispatcher $dispatcher */
589 589
 				$dispatcher = $this->get(IEventDispatcher::class);
590 590
 				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
591 591
 			});
592
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
592
+			$userSession->listen('\OC\User', 'postLogin', function($user, $loginName, $password, $isTokenLogin) {
593 593
 				/** @var \OC\User\User $user */
594 594
 				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
595 595
 
@@ -597,12 +597,12 @@  discard block
 block discarded – undo
597 597
 				$dispatcher = $this->get(IEventDispatcher::class);
598 598
 				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
599 599
 			});
600
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
600
+			$userSession->listen('\OC\User', 'preRememberedLogin', function($uid) {
601 601
 				/** @var IEventDispatcher $dispatcher */
602 602
 				$dispatcher = $this->get(IEventDispatcher::class);
603 603
 				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
604 604
 			});
605
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
605
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
606 606
 				/** @var \OC\User\User $user */
607 607
 				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
608 608
 
@@ -610,19 +610,19 @@  discard block
 block discarded – undo
610 610
 				$dispatcher = $this->get(IEventDispatcher::class);
611 611
 				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
612 612
 			});
613
-			$userSession->listen('\OC\User', 'logout', function ($user) {
613
+			$userSession->listen('\OC\User', 'logout', function($user) {
614 614
 				\OC_Hook::emit('OC_User', 'logout', []);
615 615
 
616 616
 				/** @var IEventDispatcher $dispatcher */
617 617
 				$dispatcher = $this->get(IEventDispatcher::class);
618 618
 				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
619 619
 			});
620
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
620
+			$userSession->listen('\OC\User', 'postLogout', function($user) {
621 621
 				/** @var IEventDispatcher $dispatcher */
622 622
 				$dispatcher = $this->get(IEventDispatcher::class);
623 623
 				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
624 624
 			});
625
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
625
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) {
626 626
 				/** @var \OC\User\User $user */
627 627
 				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
628 628
 
@@ -646,7 +646,7 @@  discard block
 block discarded – undo
646 646
 		$this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
647 647
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
648 648
 
649
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
649
+		$this->registerService(\OC\SystemConfig::class, function($c) use ($config) {
650 650
 			return new \OC\SystemConfig($config);
651 651
 		});
652 652
 		/** @deprecated 19.0.0 */
@@ -656,7 +656,7 @@  discard block
 block discarded – undo
656 656
 		$this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
657 657
 		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
658 658
 
659
-		$this->registerService(IFactory::class, function (Server $c) {
659
+		$this->registerService(IFactory::class, function(Server $c) {
660 660
 			return new \OC\L10N\Factory(
661 661
 				$c->get(\OCP\IConfig::class),
662 662
 				$c->getRequest(),
@@ -676,13 +676,13 @@  discard block
 block discarded – undo
676 676
 		/** @deprecated 19.0.0 */
677 677
 		$this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
678 678
 
679
-		$this->registerService(ICache::class, function ($c) {
679
+		$this->registerService(ICache::class, function($c) {
680 680
 			return new Cache\File();
681 681
 		});
682 682
 		/** @deprecated 19.0.0 */
683 683
 		$this->registerDeprecatedAlias('UserCache', ICache::class);
684 684
 
685
-		$this->registerService(Factory::class, function (Server $c) {
685
+		$this->registerService(Factory::class, function(Server $c) {
686 686
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->get(ILogger::class),
687 687
 				ArrayCache::class,
688 688
 				ArrayCache::class,
@@ -706,7 +706,7 @@  discard block
 block discarded – undo
706 706
 				$version = implode(',', $v);
707 707
 				$instanceId = \OC_Util::getInstanceId();
708 708
 				$path = \OC::$SERVERROOT;
709
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
709
+				$prefix = md5($instanceId.'-'.$version.'-'.$path);
710 710
 				return new \OC\Memcache\Factory($prefix, $c->get(ILogger::class),
711 711
 					$config->getSystemValue('memcache.local', null),
712 712
 					$config->getSystemValue('memcache.distributed', null),
@@ -720,12 +720,12 @@  discard block
 block discarded – undo
720 720
 		$this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
721 721
 		$this->registerAlias(ICacheFactory::class, Factory::class);
722 722
 
723
-		$this->registerService('RedisFactory', function (Server $c) {
723
+		$this->registerService('RedisFactory', function(Server $c) {
724 724
 			$systemConfig = $c->get(SystemConfig::class);
725 725
 			return new RedisFactory($systemConfig, $c->getEventLogger());
726 726
 		});
727 727
 
728
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
728
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
729 729
 			$l10n = $this->get(IFactory::class)->get('lib');
730 730
 			return new \OC\Activity\Manager(
731 731
 				$c->getRequest(),
@@ -738,14 +738,14 @@  discard block
 block discarded – undo
738 738
 		/** @deprecated 19.0.0 */
739 739
 		$this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
740 740
 
741
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
741
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
742 742
 			return new \OC\Activity\EventMerger(
743 743
 				$c->getL10N('lib')
744 744
 			);
745 745
 		});
746 746
 		$this->registerAlias(IValidator::class, Validator::class);
747 747
 
748
-		$this->registerService(AvatarManager::class, function (Server $c) {
748
+		$this->registerService(AvatarManager::class, function(Server $c) {
749 749
 			return new AvatarManager(
750 750
 				$c->get(IUserSession::class),
751 751
 				$c->get(\OC\User\Manager::class),
@@ -764,7 +764,7 @@  discard block
 block discarded – undo
764 764
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
765 765
 		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
766 766
 
767
-		$this->registerService(\OC\Log::class, function (Server $c) {
767
+		$this->registerService(\OC\Log::class, function(Server $c) {
768 768
 			$logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
769 769
 			$factory = new LogFactory($c, $this->get(SystemConfig::class));
770 770
 			$logger = $factory->get($logType);
@@ -778,7 +778,7 @@  discard block
 block discarded – undo
778 778
 		// PSR-3 logger
779 779
 		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
780 780
 
781
-		$this->registerService(ILogFactory::class, function (Server $c) {
781
+		$this->registerService(ILogFactory::class, function(Server $c) {
782 782
 			return new LogFactory($c, $this->get(SystemConfig::class));
783 783
 		});
784 784
 
@@ -786,7 +786,7 @@  discard block
 block discarded – undo
786 786
 		/** @deprecated 19.0.0 */
787 787
 		$this->registerDeprecatedAlias('JobList', IJobList::class);
788 788
 
789
-		$this->registerService(Router::class, function (Server $c) {
789
+		$this->registerService(Router::class, function(Server $c) {
790 790
 			$cacheFactory = $c->get(ICacheFactory::class);
791 791
 			$logger = $c->get(ILogger::class);
792 792
 			if ($cacheFactory->isLocalCacheAvailable()) {
@@ -804,7 +804,7 @@  discard block
 block discarded – undo
804 804
 		/** @deprecated 19.0.0 */
805 805
 		$this->registerDeprecatedAlias('Search', ISearch::class);
806 806
 
807
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
807
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
808 808
 			$cacheFactory = $c->get(ICacheFactory::class);
809 809
 			if ($cacheFactory->isAvailable()) {
810 810
 				$backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
@@ -840,7 +840,7 @@  discard block
 block discarded – undo
840 840
 		$this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
841 841
 
842 842
 		$this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
843
-		$this->registerService(Connection::class, function (Server $c) {
843
+		$this->registerService(Connection::class, function(Server $c) {
844 844
 			$systemConfig = $c->get(SystemConfig::class);
845 845
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
846 846
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -857,30 +857,30 @@  discard block
 block discarded – undo
857 857
 
858 858
 		$this->registerAlias(ICertificateManager::class, CertificateManager::class);
859 859
 		$this->registerAlias(IClientService::class, ClientService::class);
860
-		$this->registerService(LocalAddressChecker::class, function (ContainerInterface $c) {
860
+		$this->registerService(LocalAddressChecker::class, function(ContainerInterface $c) {
861 861
 			return new LocalAddressChecker(
862 862
 				$c->get(ILogger::class),
863 863
 			);
864 864
 		});
865
-		$this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
865
+		$this->registerService(NegativeDnsCache::class, function(ContainerInterface $c) {
866 866
 			return new NegativeDnsCache(
867 867
 				$c->get(ICacheFactory::class),
868 868
 			);
869 869
 		});
870
-		$this->registerService(DnsPinMiddleware::class, function (ContainerInterface $c) {
870
+		$this->registerService(DnsPinMiddleware::class, function(ContainerInterface $c) {
871 871
 			return new DnsPinMiddleware(
872 872
 				$c->get(NegativeDnsCache::class),
873 873
 				$c->get(LocalAddressChecker::class)
874 874
 			);
875 875
 		});
876 876
 		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
877
-		$this->registerService(IEventLogger::class, function (ContainerInterface $c) {
877
+		$this->registerService(IEventLogger::class, function(ContainerInterface $c) {
878 878
 			return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
879 879
 		});
880 880
 		/** @deprecated 19.0.0 */
881 881
 		$this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
882 882
 
883
-		$this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
883
+		$this->registerService(IQueryLogger::class, function(ContainerInterface $c) {
884 884
 			$queryLogger = new QueryLogger();
885 885
 			if ($c->get(SystemConfig::class)->getValue('debug', false)) {
886 886
 				// In debug mode, module is being activated by default
@@ -895,7 +895,7 @@  discard block
 block discarded – undo
895 895
 		$this->registerDeprecatedAlias('TempManager', TempManager::class);
896 896
 		$this->registerAlias(ITempManager::class, TempManager::class);
897 897
 
898
-		$this->registerService(AppManager::class, function (ContainerInterface $c) {
898
+		$this->registerService(AppManager::class, function(ContainerInterface $c) {
899 899
 			// TODO: use auto-wiring
900 900
 			return new \OC\App\AppManager(
901 901
 				$c->get(IUserSession::class),
@@ -915,7 +915,7 @@  discard block
 block discarded – undo
915 915
 		/** @deprecated 19.0.0 */
916 916
 		$this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
917 917
 
918
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
918
+		$this->registerService(IDateTimeFormatter::class, function(Server $c) {
919 919
 			$language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
920 920
 
921 921
 			return new DateTimeFormatter(
@@ -926,7 +926,7 @@  discard block
 block discarded – undo
926 926
 		/** @deprecated 19.0.0 */
927 927
 		$this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
928 928
 
929
-		$this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
929
+		$this->registerService(IUserMountCache::class, function(ContainerInterface $c) {
930 930
 			$mountCache = new UserMountCache(
931 931
 				$c->get(IDBConnection::class),
932 932
 				$c->get(IUserManager::class),
@@ -939,7 +939,7 @@  discard block
 block discarded – undo
939 939
 		/** @deprecated 19.0.0 */
940 940
 		$this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
941 941
 
942
-		$this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
942
+		$this->registerService(IMountProviderCollection::class, function(ContainerInterface $c) {
943 943
 			$loader = \OC\Files\Filesystem::getLoader();
944 944
 			$mountCache = $c->get(IUserMountCache::class);
945 945
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -961,7 +961,7 @@  discard block
 block discarded – undo
961 961
 
962 962
 		/** @deprecated 20.0.0 */
963 963
 		$this->registerDeprecatedAlias('IniWrapper', IniGetWrapper::class);
964
-		$this->registerService(IBus::class, function (ContainerInterface $c) {
964
+		$this->registerService(IBus::class, function(ContainerInterface $c) {
965 965
 			$busClass = $c->get(\OCP\IConfig::class)->getSystemValue('commandbus');
966 966
 			if ($busClass) {
967 967
 				[$app, $class] = explode('::', $busClass, 2);
@@ -982,7 +982,7 @@  discard block
 block discarded – undo
982 982
 		$this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
983 983
 		/** @deprecated 19.0.0 */
984 984
 		$this->registerDeprecatedAlias('Throttler', Throttler::class);
985
-		$this->registerService('IntegrityCodeChecker', function (ContainerInterface $c) {
985
+		$this->registerService('IntegrityCodeChecker', function(ContainerInterface $c) {
986 986
 			// IConfig and IAppManager requires a working database. This code
987 987
 			// might however be called when ownCloud is not yet setup.
988 988
 			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
@@ -1003,7 +1003,7 @@  discard block
 block discarded – undo
1003 1003
 				$c->get(IMimeTypeDetector::class)
1004 1004
 			);
1005 1005
 		});
1006
-		$this->registerService(\OCP\IRequest::class, function (ContainerInterface $c) {
1006
+		$this->registerService(\OCP\IRequest::class, function(ContainerInterface $c) {
1007 1007
 			if (isset($this['urlParams'])) {
1008 1008
 				$urlParams = $this['urlParams'];
1009 1009
 			} else {
@@ -1040,7 +1040,7 @@  discard block
 block discarded – undo
1040 1040
 		/** @deprecated 19.0.0 */
1041 1041
 		$this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
1042 1042
 
1043
-		$this->registerService(IMailer::class, function (Server $c) {
1043
+		$this->registerService(IMailer::class, function(Server $c) {
1044 1044
 			return new Mailer(
1045 1045
 				$c->get(\OCP\IConfig::class),
1046 1046
 				$c->get(ILogger::class),
@@ -1057,7 +1057,7 @@  discard block
 block discarded – undo
1057 1057
 		/** @deprecated 21.0.0 */
1058 1058
 		$this->registerDeprecatedAlias('LDAPProvider', ILDAPProvider::class);
1059 1059
 
1060
-		$this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
1060
+		$this->registerService(ILDAPProviderFactory::class, function(ContainerInterface $c) {
1061 1061
 			$config = $c->get(\OCP\IConfig::class);
1062 1062
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1063 1063
 			if (is_null($factoryClass) || !class_exists($factoryClass)) {
@@ -1066,11 +1066,11 @@  discard block
 block discarded – undo
1066 1066
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1067 1067
 			return new $factoryClass($this);
1068 1068
 		});
1069
-		$this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
1069
+		$this->registerService(ILDAPProvider::class, function(ContainerInterface $c) {
1070 1070
 			$factory = $c->get(ILDAPProviderFactory::class);
1071 1071
 			return $factory->getLDAPProvider();
1072 1072
 		});
1073
-		$this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
1073
+		$this->registerService(ILockingProvider::class, function(ContainerInterface $c) {
1074 1074
 			$ini = $c->get(IniGetWrapper::class);
1075 1075
 			$config = $c->get(\OCP\IConfig::class);
1076 1076
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -1095,7 +1095,7 @@  discard block
 block discarded – undo
1095 1095
 		$this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1096 1096
 
1097 1097
 		$this->registerAlias(ILockdownManager::class, 'LockdownManager');
1098
-		$this->registerService(SetupManager::class, function ($c) {
1098
+		$this->registerService(SetupManager::class, function($c) {
1099 1099
 			// create the setupmanager through the mount manager to resolve the cyclic dependency
1100 1100
 			return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
1101 1101
 		});
@@ -1103,12 +1103,12 @@  discard block
 block discarded – undo
1103 1103
 		/** @deprecated 19.0.0 */
1104 1104
 		$this->registerDeprecatedAlias('MountManager', IMountManager::class);
1105 1105
 
1106
-		$this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
1106
+		$this->registerService(IMimeTypeDetector::class, function(ContainerInterface $c) {
1107 1107
 			return new \OC\Files\Type\Detection(
1108 1108
 				$c->get(IURLGenerator::class),
1109 1109
 				$c->get(ILogger::class),
1110 1110
 				\OC::$configDir,
1111
-				\OC::$SERVERROOT . '/resources/config/'
1111
+				\OC::$SERVERROOT.'/resources/config/'
1112 1112
 			);
1113 1113
 		});
1114 1114
 		/** @deprecated 19.0.0 */
@@ -1117,19 +1117,19 @@  discard block
 block discarded – undo
1117 1117
 		$this->registerAlias(IMimeTypeLoader::class, Loader::class);
1118 1118
 		/** @deprecated 19.0.0 */
1119 1119
 		$this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1120
-		$this->registerService(BundleFetcher::class, function () {
1120
+		$this->registerService(BundleFetcher::class, function() {
1121 1121
 			return new BundleFetcher($this->getL10N('lib'));
1122 1122
 		});
1123 1123
 		$this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
1124 1124
 		/** @deprecated 19.0.0 */
1125 1125
 		$this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1126 1126
 
1127
-		$this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
1127
+		$this->registerService(CapabilitiesManager::class, function(ContainerInterface $c) {
1128 1128
 			$manager = new CapabilitiesManager($c->get(LoggerInterface::class));
1129
-			$manager->registerCapability(function () use ($c) {
1129
+			$manager->registerCapability(function() use ($c) {
1130 1130
 				return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
1131 1131
 			});
1132
-			$manager->registerCapability(function () use ($c) {
1132
+			$manager->registerCapability(function() use ($c) {
1133 1133
 				return $c->get(\OC\Security\Bruteforce\Capabilities::class);
1134 1134
 			});
1135 1135
 			return $manager;
@@ -1137,14 +1137,14 @@  discard block
 block discarded – undo
1137 1137
 		/** @deprecated 19.0.0 */
1138 1138
 		$this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1139 1139
 
1140
-		$this->registerService(ICommentsManager::class, function (Server $c) {
1140
+		$this->registerService(ICommentsManager::class, function(Server $c) {
1141 1141
 			$config = $c->get(\OCP\IConfig::class);
1142 1142
 			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1143 1143
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
1144 1144
 			$factory = new $factoryClass($this);
1145 1145
 			$manager = $factory->getManager();
1146 1146
 
1147
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1147
+			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
1148 1148
 				$manager = $c->get(IUserManager::class);
1149 1149
 				$user = $manager->get($id);
1150 1150
 				if (is_null($user)) {
@@ -1162,7 +1162,7 @@  discard block
 block discarded – undo
1162 1162
 		$this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1163 1163
 
1164 1164
 		$this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1165
-		$this->registerService('ThemingDefaults', function (Server $c) {
1165
+		$this->registerService('ThemingDefaults', function(Server $c) {
1166 1166
 			/*
1167 1167
 			 * Dark magic for autoloader.
1168 1168
 			 * If we do a class_exists it will try to load the class which will
@@ -1197,7 +1197,7 @@  discard block
 block discarded – undo
1197 1197
 			}
1198 1198
 			return new \OC_Defaults();
1199 1199
 		});
1200
-		$this->registerService(JSCombiner::class, function (Server $c) {
1200
+		$this->registerService(JSCombiner::class, function(Server $c) {
1201 1201
 			return new JSCombiner(
1202 1202
 				$c->getAppDataDir('js'),
1203 1203
 				$c->get(IURLGenerator::class),
@@ -1211,7 +1211,7 @@  discard block
 block discarded – undo
1211 1211
 		$this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1212 1212
 		$this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1213 1213
 
1214
-		$this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1214
+		$this->registerService('CryptoWrapper', function(ContainerInterface $c) {
1215 1215
 			// FIXME: Instantiiated here due to cyclic dependency
1216 1216
 			$request = new Request(
1217 1217
 				[
@@ -1238,14 +1238,14 @@  discard block
 block discarded – undo
1238 1238
 		});
1239 1239
 		/** @deprecated 19.0.0 */
1240 1240
 		$this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1241
-		$this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1241
+		$this->registerService(SessionStorage::class, function(ContainerInterface $c) {
1242 1242
 			return new SessionStorage($c->get(ISession::class));
1243 1243
 		});
1244 1244
 		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1245 1245
 		/** @deprecated 19.0.0 */
1246 1246
 		$this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1247 1247
 
1248
-		$this->registerService(\OCP\Share\IManager::class, function (IServerContainer $c) {
1248
+		$this->registerService(\OCP\Share\IManager::class, function(IServerContainer $c) {
1249 1249
 			$config = $c->get(\OCP\IConfig::class);
1250 1250
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1251 1251
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1277,7 +1277,7 @@  discard block
 block discarded – undo
1277 1277
 		/** @deprecated 19.0.0 */
1278 1278
 		$this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1279 1279
 
1280
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1280
+		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1281 1281
 			$instance = new Collaboration\Collaborators\Search($c);
1282 1282
 
1283 1283
 			// register default plugins
@@ -1300,33 +1300,33 @@  discard block
 block discarded – undo
1300 1300
 
1301 1301
 		$this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1302 1302
 		$this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1303
-		$this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1303
+		$this->registerService(\OC\Files\AppData\Factory::class, function(ContainerInterface $c) {
1304 1304
 			return new \OC\Files\AppData\Factory(
1305 1305
 				$c->get(IRootFolder::class),
1306 1306
 				$c->get(SystemConfig::class)
1307 1307
 			);
1308 1308
 		});
1309 1309
 
1310
-		$this->registerService('LockdownManager', function (ContainerInterface $c) {
1311
-			return new LockdownManager(function () use ($c) {
1310
+		$this->registerService('LockdownManager', function(ContainerInterface $c) {
1311
+			return new LockdownManager(function() use ($c) {
1312 1312
 				return $c->get(ISession::class);
1313 1313
 			});
1314 1314
 		});
1315 1315
 
1316
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1316
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(ContainerInterface $c) {
1317 1317
 			return new DiscoveryService(
1318 1318
 				$c->get(ICacheFactory::class),
1319 1319
 				$c->get(IClientService::class)
1320 1320
 			);
1321 1321
 		});
1322 1322
 
1323
-		$this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1323
+		$this->registerService(ICloudIdManager::class, function(ContainerInterface $c) {
1324 1324
 			return new CloudIdManager($c->get(\OCP\Contacts\IManager::class), $c->get(IURLGenerator::class), $c->get(IUserManager::class));
1325 1325
 		});
1326 1326
 
1327 1327
 		$this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1328 1328
 
1329
-		$this->registerService(ICloudFederationProviderManager::class, function (ContainerInterface $c) {
1329
+		$this->registerService(ICloudFederationProviderManager::class, function(ContainerInterface $c) {
1330 1330
 			return new CloudFederationProviderManager(
1331 1331
 				$c->get(IAppManager::class),
1332 1332
 				$c->get(IClientService::class),
@@ -1335,7 +1335,7 @@  discard block
 block discarded – undo
1335 1335
 			);
1336 1336
 		});
1337 1337
 
1338
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1338
+		$this->registerService(ICloudFederationFactory::class, function(Server $c) {
1339 1339
 			return new CloudFederationFactory();
1340 1340
 		});
1341 1341
 
@@ -1347,7 +1347,7 @@  discard block
 block discarded – undo
1347 1347
 		/** @deprecated 19.0.0 */
1348 1348
 		$this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1349 1349
 
1350
-		$this->registerService(Defaults::class, function (Server $c) {
1350
+		$this->registerService(Defaults::class, function(Server $c) {
1351 1351
 			return new Defaults(
1352 1352
 				$c->getThemingDefaults()
1353 1353
 			);
@@ -1355,17 +1355,17 @@  discard block
 block discarded – undo
1355 1355
 		/** @deprecated 19.0.0 */
1356 1356
 		$this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1357 1357
 
1358
-		$this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1358
+		$this->registerService(\OCP\ISession::class, function(ContainerInterface $c) {
1359 1359
 			return $c->get(\OCP\IUserSession::class)->getSession();
1360 1360
 		}, false);
1361 1361
 
1362
-		$this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1362
+		$this->registerService(IShareHelper::class, function(ContainerInterface $c) {
1363 1363
 			return new ShareHelper(
1364 1364
 				$c->get(\OCP\Share\IManager::class)
1365 1365
 			);
1366 1366
 		});
1367 1367
 
1368
-		$this->registerService(Installer::class, function (ContainerInterface $c) {
1368
+		$this->registerService(Installer::class, function(ContainerInterface $c) {
1369 1369
 			return new Installer(
1370 1370
 				$c->get(AppFetcher::class),
1371 1371
 				$c->get(IClientService::class),
@@ -1376,11 +1376,11 @@  discard block
 block discarded – undo
1376 1376
 			);
1377 1377
 		});
1378 1378
 
1379
-		$this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1379
+		$this->registerService(IApiFactory::class, function(ContainerInterface $c) {
1380 1380
 			return new ApiFactory($c->get(IClientService::class));
1381 1381
 		});
1382 1382
 
1383
-		$this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1383
+		$this->registerService(IInstanceFactory::class, function(ContainerInterface $c) {
1384 1384
 			$memcacheFactory = $c->get(ICacheFactory::class);
1385 1385
 			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1386 1386
 		});
@@ -1437,7 +1437,7 @@  discard block
 block discarded – undo
1437 1437
 		$dispatcher = $this->get(SymfonyAdapter::class);
1438 1438
 
1439 1439
 		// Delete avatar on user deletion
1440
-		$dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1440
+		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1441 1441
 			$logger = $this->get(ILogger::class);
1442 1442
 			$manager = $this->getAvatarManager();
1443 1443
 			/** @var IUser $user */
@@ -1450,11 +1450,11 @@  discard block
 block discarded – undo
1450 1450
 				// no avatar to remove
1451 1451
 			} catch (\Exception $e) {
1452 1452
 				// Ignore exceptions
1453
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1453
+				$logger->info('Could not cleanup avatar of '.$user->getUID());
1454 1454
 			}
1455 1455
 		});
1456 1456
 
1457
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1457
+		$dispatcher->addListener('OCP\IUser::changeUser', function(GenericEvent $e) {
1458 1458
 			$manager = $this->getAvatarManager();
1459 1459
 			/** @var IUser $user */
1460 1460
 			$user = $e->getSubject();
@@ -2345,11 +2345,11 @@  discard block
 block discarded – undo
2345 2345
 	}
2346 2346
 
2347 2347
 	private function registerDeprecatedAlias(string $alias, string $target) {
2348
-		$this->registerService($alias, function (ContainerInterface $container) use ($target, $alias) {
2348
+		$this->registerService($alias, function(ContainerInterface $container) use ($target, $alias) {
2349 2349
 			try {
2350 2350
 				/** @var ILogger $logger */
2351 2351
 				$logger = $container->get(ILogger::class);
2352
-				$logger->debug('The requested alias "' . $alias . '" is deprecated. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2352
+				$logger->debug('The requested alias "'.$alias.'" is deprecated. Please request "'.$target.'" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2353 2353
 			} catch (ContainerExceptionInterface $e) {
2354 2354
 				// Could not get logger. Continue
2355 2355
 			}
Please login to merge, or discard this patch.
lib/private/Files/Node/Root.php 2 patches
Indentation   +332 added lines, -332 removed lines patch added patch discarded remove patch
@@ -68,336 +68,336 @@
 block discarded – undo
68 68
  * @package OC\Files\Node
69 69
  */
70 70
 class Root extends Folder implements IRootFolder {
71
-	private Manager $mountManager;
72
-	private PublicEmitter $emitter;
73
-	private ?IUser $user;
74
-	private CappedMemoryCache $userFolderCache;
75
-	private IUserMountCache $userMountCache;
76
-	private ILogger $logger;
77
-	private IUserManager $userManager;
78
-	private IEventDispatcher $eventDispatcher;
79
-
80
-	/**
81
-	 * @param Manager $manager
82
-	 * @param View $view
83
-	 * @param IUser|null $user
84
-	 * @param IUserMountCache $userMountCache
85
-	 * @param ILogger $logger
86
-	 * @param IUserManager $userManager
87
-	 */
88
-	public function __construct(
89
-		$manager,
90
-		$view,
91
-		$user,
92
-		IUserMountCache $userMountCache,
93
-		ILogger $logger,
94
-		IUserManager $userManager,
95
-		IEventDispatcher $eventDispatcher
96
-	) {
97
-		parent::__construct($this, $view, '');
98
-		$this->mountManager = $manager;
99
-		$this->user = $user;
100
-		$this->emitter = new PublicEmitter();
101
-		$this->userFolderCache = new CappedMemoryCache();
102
-		$this->userMountCache = $userMountCache;
103
-		$this->logger = $logger;
104
-		$this->userManager = $userManager;
105
-		$eventDispatcher->addListener(FilesystemTornDownEvent::class, function () {
106
-			$this->userFolderCache = new CappedMemoryCache();
107
-		});
108
-	}
109
-
110
-	/**
111
-	 * Get the user for which the filesystem is setup
112
-	 *
113
-	 * @return \OC\User\User
114
-	 */
115
-	public function getUser() {
116
-		return $this->user;
117
-	}
118
-
119
-	/**
120
-	 * @param string $scope
121
-	 * @param string $method
122
-	 * @param callable $callback
123
-	 */
124
-	public function listen($scope, $method, callable $callback) {
125
-		$this->emitter->listen($scope, $method, $callback);
126
-	}
127
-
128
-	/**
129
-	 * @param string $scope optional
130
-	 * @param string $method optional
131
-	 * @param callable $callback optional
132
-	 */
133
-	public function removeListener($scope = null, $method = null, callable $callback = null) {
134
-		$this->emitter->removeListener($scope, $method, $callback);
135
-	}
136
-
137
-	/**
138
-	 * @param string $scope
139
-	 * @param string $method
140
-	 * @param Node[] $arguments
141
-	 */
142
-	public function emit($scope, $method, $arguments = []) {
143
-		$this->emitter->emit($scope, $method, $arguments);
144
-	}
145
-
146
-	/**
147
-	 * @param \OC\Files\Storage\Storage $storage
148
-	 * @param string $mountPoint
149
-	 * @param array $arguments
150
-	 */
151
-	public function mount($storage, $mountPoint, $arguments = []) {
152
-		$mount = new MountPoint($storage, $mountPoint, $arguments);
153
-		$this->mountManager->addMount($mount);
154
-	}
155
-
156
-	/**
157
-	 * @param string $mountPoint
158
-	 * @return \OC\Files\Mount\MountPoint
159
-	 */
160
-	public function getMount($mountPoint) {
161
-		return $this->mountManager->find($mountPoint);
162
-	}
163
-
164
-	/**
165
-	 * @param string $mountPoint
166
-	 * @return \OC\Files\Mount\MountPoint[]
167
-	 */
168
-	public function getMountsIn($mountPoint) {
169
-		return $this->mountManager->findIn($mountPoint);
170
-	}
171
-
172
-	/**
173
-	 * @param string $storageId
174
-	 * @return \OC\Files\Mount\MountPoint[]
175
-	 */
176
-	public function getMountByStorageId($storageId) {
177
-		return $this->mountManager->findByStorageId($storageId);
178
-	}
179
-
180
-	/**
181
-	 * @param int $numericId
182
-	 * @return MountPoint[]
183
-	 */
184
-	public function getMountByNumericStorageId($numericId) {
185
-		return $this->mountManager->findByNumericId($numericId);
186
-	}
187
-
188
-	/**
189
-	 * @param \OC\Files\Mount\MountPoint $mount
190
-	 */
191
-	public function unMount($mount) {
192
-		$this->mountManager->remove($mount);
193
-	}
194
-
195
-	/**
196
-	 * @param string $path
197
-	 * @return Node
198
-	 * @throws \OCP\Files\NotPermittedException
199
-	 * @throws \OCP\Files\NotFoundException
200
-	 */
201
-	public function get($path) {
202
-		$path = $this->normalizePath($path);
203
-		if ($this->isValidPath($path)) {
204
-			$fullPath = $this->getFullPath($path);
205
-			$fileInfo = $this->view->getFileInfo($fullPath);
206
-			if ($fileInfo) {
207
-				return $this->createNode($fullPath, $fileInfo);
208
-			} else {
209
-				throw new NotFoundException($path);
210
-			}
211
-		} else {
212
-			throw new NotPermittedException();
213
-		}
214
-	}
215
-
216
-	//most operations can't be done on the root
217
-
218
-	/**
219
-	 * @param string $targetPath
220
-	 * @return \OC\Files\Node\Node
221
-	 * @throws \OCP\Files\NotPermittedException
222
-	 */
223
-	public function rename($targetPath) {
224
-		throw new NotPermittedException();
225
-	}
226
-
227
-	public function delete() {
228
-		throw new NotPermittedException();
229
-	}
230
-
231
-	/**
232
-	 * @param string $targetPath
233
-	 * @return \OC\Files\Node\Node
234
-	 * @throws \OCP\Files\NotPermittedException
235
-	 */
236
-	public function copy($targetPath) {
237
-		throw new NotPermittedException();
238
-	}
239
-
240
-	/**
241
-	 * @param int $mtime
242
-	 * @throws \OCP\Files\NotPermittedException
243
-	 */
244
-	public function touch($mtime = null) {
245
-		throw new NotPermittedException();
246
-	}
247
-
248
-	/**
249
-	 * @return \OC\Files\Storage\Storage
250
-	 * @throws \OCP\Files\NotFoundException
251
-	 */
252
-	public function getStorage() {
253
-		throw new NotFoundException();
254
-	}
255
-
256
-	/**
257
-	 * @return string
258
-	 */
259
-	public function getPath() {
260
-		return '/';
261
-	}
262
-
263
-	/**
264
-	 * @return string
265
-	 */
266
-	public function getInternalPath() {
267
-		return '';
268
-	}
269
-
270
-	/**
271
-	 * @return int
272
-	 */
273
-	public function getId() {
274
-		return 0;
275
-	}
276
-
277
-	/**
278
-	 * @return array
279
-	 */
280
-	public function stat() {
281
-		return [];
282
-	}
283
-
284
-	/**
285
-	 * @return int
286
-	 */
287
-	public function getMTime() {
288
-		return 0;
289
-	}
290
-
291
-	/**
292
-	 * @param bool $includeMounts
293
-	 * @return int
294
-	 */
295
-	public function getSize($includeMounts = true) {
296
-		return 0;
297
-	}
298
-
299
-	/**
300
-	 * @return string
301
-	 */
302
-	public function getEtag() {
303
-		return '';
304
-	}
305
-
306
-	/**
307
-	 * @return int
308
-	 */
309
-	public function getPermissions() {
310
-		return \OCP\Constants::PERMISSION_CREATE;
311
-	}
312
-
313
-	/**
314
-	 * @return bool
315
-	 */
316
-	public function isReadable() {
317
-		return false;
318
-	}
319
-
320
-	/**
321
-	 * @return bool
322
-	 */
323
-	public function isUpdateable() {
324
-		return false;
325
-	}
326
-
327
-	/**
328
-	 * @return bool
329
-	 */
330
-	public function isDeletable() {
331
-		return false;
332
-	}
333
-
334
-	/**
335
-	 * @return bool
336
-	 */
337
-	public function isShareable() {
338
-		return false;
339
-	}
340
-
341
-	/**
342
-	 * @return Node
343
-	 * @throws \OCP\Files\NotFoundException
344
-	 */
345
-	public function getParent() {
346
-		throw new NotFoundException();
347
-	}
348
-
349
-	/**
350
-	 * @return string
351
-	 */
352
-	public function getName() {
353
-		return '';
354
-	}
355
-
356
-	/**
357
-	 * Returns a view to user's files folder
358
-	 *
359
-	 * @param string $userId user ID
360
-	 * @return \OCP\Files\Folder
361
-	 * @throws NoUserException
362
-	 * @throws NotPermittedException
363
-	 */
364
-	public function getUserFolder($userId) {
365
-		$userObject = $this->userManager->get($userId);
366
-
367
-		if (is_null($userObject)) {
368
-			$this->logger->error(
369
-				sprintf(
370
-					'Backends provided no user object for %s',
371
-					$userId
372
-				),
373
-				[
374
-					'app' => 'files',
375
-				]
376
-			);
377
-			throw new NoUserException('Backends provided no user object');
378
-		}
379
-
380
-		$userId = $userObject->getUID();
381
-
382
-		if (!$this->userFolderCache->hasKey($userId)) {
383
-			\OC\Files\Filesystem::initMountPoints($userId);
384
-
385
-			try {
386
-				$folder = $this->get('/' . $userId . '/files');
387
-			} catch (NotFoundException $e) {
388
-				if (!$this->nodeExists('/' . $userId)) {
389
-					$this->newFolder('/' . $userId);
390
-				}
391
-				$folder = $this->newFolder('/' . $userId . '/files');
392
-			}
393
-
394
-			$this->userFolderCache->set($userId, $folder);
395
-		}
396
-
397
-		return $this->userFolderCache->get($userId);
398
-	}
399
-
400
-	public function getUserMountCache() {
401
-		return $this->userMountCache;
402
-	}
71
+    private Manager $mountManager;
72
+    private PublicEmitter $emitter;
73
+    private ?IUser $user;
74
+    private CappedMemoryCache $userFolderCache;
75
+    private IUserMountCache $userMountCache;
76
+    private ILogger $logger;
77
+    private IUserManager $userManager;
78
+    private IEventDispatcher $eventDispatcher;
79
+
80
+    /**
81
+     * @param Manager $manager
82
+     * @param View $view
83
+     * @param IUser|null $user
84
+     * @param IUserMountCache $userMountCache
85
+     * @param ILogger $logger
86
+     * @param IUserManager $userManager
87
+     */
88
+    public function __construct(
89
+        $manager,
90
+        $view,
91
+        $user,
92
+        IUserMountCache $userMountCache,
93
+        ILogger $logger,
94
+        IUserManager $userManager,
95
+        IEventDispatcher $eventDispatcher
96
+    ) {
97
+        parent::__construct($this, $view, '');
98
+        $this->mountManager = $manager;
99
+        $this->user = $user;
100
+        $this->emitter = new PublicEmitter();
101
+        $this->userFolderCache = new CappedMemoryCache();
102
+        $this->userMountCache = $userMountCache;
103
+        $this->logger = $logger;
104
+        $this->userManager = $userManager;
105
+        $eventDispatcher->addListener(FilesystemTornDownEvent::class, function () {
106
+            $this->userFolderCache = new CappedMemoryCache();
107
+        });
108
+    }
109
+
110
+    /**
111
+     * Get the user for which the filesystem is setup
112
+     *
113
+     * @return \OC\User\User
114
+     */
115
+    public function getUser() {
116
+        return $this->user;
117
+    }
118
+
119
+    /**
120
+     * @param string $scope
121
+     * @param string $method
122
+     * @param callable $callback
123
+     */
124
+    public function listen($scope, $method, callable $callback) {
125
+        $this->emitter->listen($scope, $method, $callback);
126
+    }
127
+
128
+    /**
129
+     * @param string $scope optional
130
+     * @param string $method optional
131
+     * @param callable $callback optional
132
+     */
133
+    public function removeListener($scope = null, $method = null, callable $callback = null) {
134
+        $this->emitter->removeListener($scope, $method, $callback);
135
+    }
136
+
137
+    /**
138
+     * @param string $scope
139
+     * @param string $method
140
+     * @param Node[] $arguments
141
+     */
142
+    public function emit($scope, $method, $arguments = []) {
143
+        $this->emitter->emit($scope, $method, $arguments);
144
+    }
145
+
146
+    /**
147
+     * @param \OC\Files\Storage\Storage $storage
148
+     * @param string $mountPoint
149
+     * @param array $arguments
150
+     */
151
+    public function mount($storage, $mountPoint, $arguments = []) {
152
+        $mount = new MountPoint($storage, $mountPoint, $arguments);
153
+        $this->mountManager->addMount($mount);
154
+    }
155
+
156
+    /**
157
+     * @param string $mountPoint
158
+     * @return \OC\Files\Mount\MountPoint
159
+     */
160
+    public function getMount($mountPoint) {
161
+        return $this->mountManager->find($mountPoint);
162
+    }
163
+
164
+    /**
165
+     * @param string $mountPoint
166
+     * @return \OC\Files\Mount\MountPoint[]
167
+     */
168
+    public function getMountsIn($mountPoint) {
169
+        return $this->mountManager->findIn($mountPoint);
170
+    }
171
+
172
+    /**
173
+     * @param string $storageId
174
+     * @return \OC\Files\Mount\MountPoint[]
175
+     */
176
+    public function getMountByStorageId($storageId) {
177
+        return $this->mountManager->findByStorageId($storageId);
178
+    }
179
+
180
+    /**
181
+     * @param int $numericId
182
+     * @return MountPoint[]
183
+     */
184
+    public function getMountByNumericStorageId($numericId) {
185
+        return $this->mountManager->findByNumericId($numericId);
186
+    }
187
+
188
+    /**
189
+     * @param \OC\Files\Mount\MountPoint $mount
190
+     */
191
+    public function unMount($mount) {
192
+        $this->mountManager->remove($mount);
193
+    }
194
+
195
+    /**
196
+     * @param string $path
197
+     * @return Node
198
+     * @throws \OCP\Files\NotPermittedException
199
+     * @throws \OCP\Files\NotFoundException
200
+     */
201
+    public function get($path) {
202
+        $path = $this->normalizePath($path);
203
+        if ($this->isValidPath($path)) {
204
+            $fullPath = $this->getFullPath($path);
205
+            $fileInfo = $this->view->getFileInfo($fullPath);
206
+            if ($fileInfo) {
207
+                return $this->createNode($fullPath, $fileInfo);
208
+            } else {
209
+                throw new NotFoundException($path);
210
+            }
211
+        } else {
212
+            throw new NotPermittedException();
213
+        }
214
+    }
215
+
216
+    //most operations can't be done on the root
217
+
218
+    /**
219
+     * @param string $targetPath
220
+     * @return \OC\Files\Node\Node
221
+     * @throws \OCP\Files\NotPermittedException
222
+     */
223
+    public function rename($targetPath) {
224
+        throw new NotPermittedException();
225
+    }
226
+
227
+    public function delete() {
228
+        throw new NotPermittedException();
229
+    }
230
+
231
+    /**
232
+     * @param string $targetPath
233
+     * @return \OC\Files\Node\Node
234
+     * @throws \OCP\Files\NotPermittedException
235
+     */
236
+    public function copy($targetPath) {
237
+        throw new NotPermittedException();
238
+    }
239
+
240
+    /**
241
+     * @param int $mtime
242
+     * @throws \OCP\Files\NotPermittedException
243
+     */
244
+    public function touch($mtime = null) {
245
+        throw new NotPermittedException();
246
+    }
247
+
248
+    /**
249
+     * @return \OC\Files\Storage\Storage
250
+     * @throws \OCP\Files\NotFoundException
251
+     */
252
+    public function getStorage() {
253
+        throw new NotFoundException();
254
+    }
255
+
256
+    /**
257
+     * @return string
258
+     */
259
+    public function getPath() {
260
+        return '/';
261
+    }
262
+
263
+    /**
264
+     * @return string
265
+     */
266
+    public function getInternalPath() {
267
+        return '';
268
+    }
269
+
270
+    /**
271
+     * @return int
272
+     */
273
+    public function getId() {
274
+        return 0;
275
+    }
276
+
277
+    /**
278
+     * @return array
279
+     */
280
+    public function stat() {
281
+        return [];
282
+    }
283
+
284
+    /**
285
+     * @return int
286
+     */
287
+    public function getMTime() {
288
+        return 0;
289
+    }
290
+
291
+    /**
292
+     * @param bool $includeMounts
293
+     * @return int
294
+     */
295
+    public function getSize($includeMounts = true) {
296
+        return 0;
297
+    }
298
+
299
+    /**
300
+     * @return string
301
+     */
302
+    public function getEtag() {
303
+        return '';
304
+    }
305
+
306
+    /**
307
+     * @return int
308
+     */
309
+    public function getPermissions() {
310
+        return \OCP\Constants::PERMISSION_CREATE;
311
+    }
312
+
313
+    /**
314
+     * @return bool
315
+     */
316
+    public function isReadable() {
317
+        return false;
318
+    }
319
+
320
+    /**
321
+     * @return bool
322
+     */
323
+    public function isUpdateable() {
324
+        return false;
325
+    }
326
+
327
+    /**
328
+     * @return bool
329
+     */
330
+    public function isDeletable() {
331
+        return false;
332
+    }
333
+
334
+    /**
335
+     * @return bool
336
+     */
337
+    public function isShareable() {
338
+        return false;
339
+    }
340
+
341
+    /**
342
+     * @return Node
343
+     * @throws \OCP\Files\NotFoundException
344
+     */
345
+    public function getParent() {
346
+        throw new NotFoundException();
347
+    }
348
+
349
+    /**
350
+     * @return string
351
+     */
352
+    public function getName() {
353
+        return '';
354
+    }
355
+
356
+    /**
357
+     * Returns a view to user's files folder
358
+     *
359
+     * @param string $userId user ID
360
+     * @return \OCP\Files\Folder
361
+     * @throws NoUserException
362
+     * @throws NotPermittedException
363
+     */
364
+    public function getUserFolder($userId) {
365
+        $userObject = $this->userManager->get($userId);
366
+
367
+        if (is_null($userObject)) {
368
+            $this->logger->error(
369
+                sprintf(
370
+                    'Backends provided no user object for %s',
371
+                    $userId
372
+                ),
373
+                [
374
+                    'app' => 'files',
375
+                ]
376
+            );
377
+            throw new NoUserException('Backends provided no user object');
378
+        }
379
+
380
+        $userId = $userObject->getUID();
381
+
382
+        if (!$this->userFolderCache->hasKey($userId)) {
383
+            \OC\Files\Filesystem::initMountPoints($userId);
384
+
385
+            try {
386
+                $folder = $this->get('/' . $userId . '/files');
387
+            } catch (NotFoundException $e) {
388
+                if (!$this->nodeExists('/' . $userId)) {
389
+                    $this->newFolder('/' . $userId);
390
+                }
391
+                $folder = $this->newFolder('/' . $userId . '/files');
392
+            }
393
+
394
+            $this->userFolderCache->set($userId, $folder);
395
+        }
396
+
397
+        return $this->userFolderCache->get($userId);
398
+    }
399
+
400
+    public function getUserMountCache() {
401
+        return $this->userMountCache;
402
+    }
403 403
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 		$this->userMountCache = $userMountCache;
103 103
 		$this->logger = $logger;
104 104
 		$this->userManager = $userManager;
105
-		$eventDispatcher->addListener(FilesystemTornDownEvent::class, function () {
105
+		$eventDispatcher->addListener(FilesystemTornDownEvent::class, function() {
106 106
 			$this->userFolderCache = new CappedMemoryCache();
107 107
 		});
108 108
 	}
@@ -383,12 +383,12 @@  discard block
 block discarded – undo
383 383
 			\OC\Files\Filesystem::initMountPoints($userId);
384 384
 
385 385
 			try {
386
-				$folder = $this->get('/' . $userId . '/files');
386
+				$folder = $this->get('/'.$userId.'/files');
387 387
 			} catch (NotFoundException $e) {
388
-				if (!$this->nodeExists('/' . $userId)) {
389
-					$this->newFolder('/' . $userId);
388
+				if (!$this->nodeExists('/'.$userId)) {
389
+					$this->newFolder('/'.$userId);
390 390
 				}
391
-				$folder = $this->newFolder('/' . $userId . '/files');
391
+				$folder = $this->newFolder('/'.$userId.'/files');
392 392
 			}
393 393
 
394 394
 			$this->userFolderCache->set($userId, $folder);
Please login to merge, or discard this patch.
lib/private/Files/SetupManagerFactory.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -32,35 +32,35 @@
 block discarded – undo
32 32
 use OCP\Lockdown\ILockdownManager;
33 33
 
34 34
 class SetupManagerFactory {
35
-	private IEventLogger $eventLogger;
36
-	private IMountProviderCollection $mountProviderCollection;
37
-	private IUserManager $userManager;
38
-	private IEventDispatcher $eventDispatcher;
39
-	private IUserMountCache $userMountCache;
40
-	private ILockdownManager $lockdownManager;
41
-	private ?SetupManager $setupManager;
35
+    private IEventLogger $eventLogger;
36
+    private IMountProviderCollection $mountProviderCollection;
37
+    private IUserManager $userManager;
38
+    private IEventDispatcher $eventDispatcher;
39
+    private IUserMountCache $userMountCache;
40
+    private ILockdownManager $lockdownManager;
41
+    private ?SetupManager $setupManager;
42 42
 
43
-	public function __construct(
44
-		IEventLogger $eventLogger,
45
-		IMountProviderCollection $mountProviderCollection,
46
-		IUserManager $userManager,
47
-		IEventDispatcher $eventDispatcher,
48
-		IUserMountCache $userMountCache,
49
-		ILockdownManager $lockdownManager
50
-	) {
51
-		$this->eventLogger = $eventLogger;
52
-		$this->mountProviderCollection = $mountProviderCollection;
53
-		$this->userManager = $userManager;
54
-		$this->eventDispatcher = $eventDispatcher;
55
-		$this->userMountCache = $userMountCache;
56
-		$this->lockdownManager = $lockdownManager;
57
-		$this->setupManager = null;
58
-	}
43
+    public function __construct(
44
+        IEventLogger $eventLogger,
45
+        IMountProviderCollection $mountProviderCollection,
46
+        IUserManager $userManager,
47
+        IEventDispatcher $eventDispatcher,
48
+        IUserMountCache $userMountCache,
49
+        ILockdownManager $lockdownManager
50
+    ) {
51
+        $this->eventLogger = $eventLogger;
52
+        $this->mountProviderCollection = $mountProviderCollection;
53
+        $this->userManager = $userManager;
54
+        $this->eventDispatcher = $eventDispatcher;
55
+        $this->userMountCache = $userMountCache;
56
+        $this->lockdownManager = $lockdownManager;
57
+        $this->setupManager = null;
58
+    }
59 59
 
60
-	public function create(IMountManager $mountManager): SetupManager {
61
-		if (!$this->setupManager) {
62
-			$this->setupManager = new SetupManager($this->eventLogger, $this->mountProviderCollection, $mountManager, $this->userManager, $this->eventDispatcher, $this->userMountCache, $this->lockdownManager);
63
-		}
64
-		return $this->setupManager;
65
-	}
60
+    public function create(IMountManager $mountManager): SetupManager {
61
+        if (!$this->setupManager) {
62
+            $this->setupManager = new SetupManager($this->eventLogger, $this->mountProviderCollection, $mountManager, $this->userManager, $this->eventDispatcher, $this->userMountCache, $this->lockdownManager);
63
+        }
64
+        return $this->setupManager;
65
+    }
66 66
 }
Please login to merge, or discard this patch.
lib/private/Files/View.php 2 patches
Indentation   +2117 added lines, -2117 removed lines patch added patch discarded remove patch
@@ -84,2121 +84,2121 @@
 block discarded – undo
84 84
  * \OC\Files\Storage\Storage object
85 85
  */
86 86
 class View {
87
-	/** @var string */
88
-	private $fakeRoot = '';
89
-
90
-	/**
91
-	 * @var \OCP\Lock\ILockingProvider
92
-	 */
93
-	protected $lockingProvider;
94
-
95
-	private $lockingEnabled;
96
-
97
-	private $updaterEnabled = true;
98
-
99
-	/** @var \OC\User\Manager */
100
-	private $userManager;
101
-
102
-	/** @var \OCP\ILogger */
103
-	private $logger;
104
-
105
-	/**
106
-	 * @param string $root
107
-	 * @throws \Exception If $root contains an invalid path
108
-	 */
109
-	public function __construct($root = '') {
110
-		if (is_null($root)) {
111
-			throw new \InvalidArgumentException('Root can\'t be null');
112
-		}
113
-		if (!Filesystem::isValidPath($root)) {
114
-			throw new \Exception();
115
-		}
116
-
117
-		$this->fakeRoot = $root;
118
-		$this->lockingProvider = \OC::$server->getLockingProvider();
119
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
120
-		$this->userManager = \OC::$server->getUserManager();
121
-		$this->logger = \OC::$server->getLogger();
122
-	}
123
-
124
-	public function getAbsolutePath($path = '/') {
125
-		if ($path === null) {
126
-			return null;
127
-		}
128
-		$this->assertPathLength($path);
129
-		if ($path === '') {
130
-			$path = '/';
131
-		}
132
-		if ($path[0] !== '/') {
133
-			$path = '/' . $path;
134
-		}
135
-		return $this->fakeRoot . $path;
136
-	}
137
-
138
-	/**
139
-	 * change the root to a fake root
140
-	 *
141
-	 * @param string $fakeRoot
142
-	 * @return boolean|null
143
-	 */
144
-	public function chroot($fakeRoot) {
145
-		if (!$fakeRoot == '') {
146
-			if ($fakeRoot[0] !== '/') {
147
-				$fakeRoot = '/' . $fakeRoot;
148
-			}
149
-		}
150
-		$this->fakeRoot = $fakeRoot;
151
-	}
152
-
153
-	/**
154
-	 * get the fake root
155
-	 *
156
-	 * @return string
157
-	 */
158
-	public function getRoot() {
159
-		return $this->fakeRoot;
160
-	}
161
-
162
-	/**
163
-	 * get path relative to the root of the view
164
-	 *
165
-	 * @param string $path
166
-	 * @return string
167
-	 */
168
-	public function getRelativePath($path) {
169
-		$this->assertPathLength($path);
170
-		if ($this->fakeRoot == '') {
171
-			return $path;
172
-		}
173
-
174
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
175
-			return '/';
176
-		}
177
-
178
-		// missing slashes can cause wrong matches!
179
-		$root = rtrim($this->fakeRoot, '/') . '/';
180
-
181
-		if (strpos($path, $root) !== 0) {
182
-			return null;
183
-		} else {
184
-			$path = substr($path, strlen($this->fakeRoot));
185
-			if (strlen($path) === 0) {
186
-				return '/';
187
-			} else {
188
-				return $path;
189
-			}
190
-		}
191
-	}
192
-
193
-	/**
194
-	 * get the mountpoint of the storage object for a path
195
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
196
-	 * returned mountpoint is relative to the absolute root of the filesystem
197
-	 * and does not take the chroot into account )
198
-	 *
199
-	 * @param string $path
200
-	 * @return string
201
-	 */
202
-	public function getMountPoint($path) {
203
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
204
-	}
205
-
206
-	/**
207
-	 * get the mountpoint of the storage object for a path
208
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
209
-	 * returned mountpoint is relative to the absolute root of the filesystem
210
-	 * and does not take the chroot into account )
211
-	 *
212
-	 * @param string $path
213
-	 * @return \OCP\Files\Mount\IMountPoint
214
-	 */
215
-	public function getMount($path) {
216
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
217
-	}
218
-
219
-	/**
220
-	 * resolve a path to a storage and internal path
221
-	 *
222
-	 * @param string $path
223
-	 * @return array an array consisting of the storage and the internal path
224
-	 */
225
-	public function resolvePath($path) {
226
-		$a = $this->getAbsolutePath($path);
227
-		$p = Filesystem::normalizePath($a);
228
-		return Filesystem::resolvePath($p);
229
-	}
230
-
231
-	/**
232
-	 * return the path to a local version of the file
233
-	 * we need this because we can't know if a file is stored local or not from
234
-	 * outside the filestorage and for some purposes a local file is needed
235
-	 *
236
-	 * @param string $path
237
-	 * @return string
238
-	 */
239
-	public function getLocalFile($path) {
240
-		$parent = substr($path, 0, strrpos($path, '/'));
241
-		$path = $this->getAbsolutePath($path);
242
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
243
-		if (Filesystem::isValidPath($parent) and $storage) {
244
-			return $storage->getLocalFile($internalPath);
245
-		} else {
246
-			return null;
247
-		}
248
-	}
249
-
250
-	/**
251
-	 * @param string $path
252
-	 * @return string
253
-	 */
254
-	public function getLocalFolder($path) {
255
-		$parent = substr($path, 0, strrpos($path, '/'));
256
-		$path = $this->getAbsolutePath($path);
257
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
258
-		if (Filesystem::isValidPath($parent) and $storage) {
259
-			return $storage->getLocalFolder($internalPath);
260
-		} else {
261
-			return null;
262
-		}
263
-	}
264
-
265
-	/**
266
-	 * the following functions operate with arguments and return values identical
267
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
268
-	 * for \OC\Files\Storage\Storage via basicOperation().
269
-	 */
270
-	public function mkdir($path) {
271
-		return $this->basicOperation('mkdir', $path, ['create', 'write']);
272
-	}
273
-
274
-	/**
275
-	 * remove mount point
276
-	 *
277
-	 * @param IMountPoint $mount
278
-	 * @param string $path relative to data/
279
-	 * @return boolean
280
-	 */
281
-	protected function removeMount($mount, $path) {
282
-		if ($mount instanceof MoveableMount) {
283
-			// cut of /user/files to get the relative path to data/user/files
284
-			$pathParts = explode('/', $path, 4);
285
-			$relPath = '/' . $pathParts[3];
286
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
287
-			\OC_Hook::emit(
288
-				Filesystem::CLASSNAME, "umount",
289
-				[Filesystem::signal_param_path => $relPath]
290
-			);
291
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
292
-			$result = $mount->removeMount();
293
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
294
-			if ($result) {
295
-				\OC_Hook::emit(
296
-					Filesystem::CLASSNAME, "post_umount",
297
-					[Filesystem::signal_param_path => $relPath]
298
-				);
299
-			}
300
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
301
-			return $result;
302
-		} else {
303
-			// do not allow deleting the storage's root / the mount point
304
-			// because for some storages it might delete the whole contents
305
-			// but isn't supposed to work that way
306
-			return false;
307
-		}
308
-	}
309
-
310
-	public function disableCacheUpdate() {
311
-		$this->updaterEnabled = false;
312
-	}
313
-
314
-	public function enableCacheUpdate() {
315
-		$this->updaterEnabled = true;
316
-	}
317
-
318
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
319
-		if ($this->updaterEnabled) {
320
-			if (is_null($time)) {
321
-				$time = time();
322
-			}
323
-			$storage->getUpdater()->update($internalPath, $time);
324
-		}
325
-	}
326
-
327
-	protected function removeUpdate(Storage $storage, $internalPath) {
328
-		if ($this->updaterEnabled) {
329
-			$storage->getUpdater()->remove($internalPath);
330
-		}
331
-	}
332
-
333
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
334
-		if ($this->updaterEnabled) {
335
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
336
-		}
337
-	}
338
-
339
-	/**
340
-	 * @param string $path
341
-	 * @return bool|mixed
342
-	 */
343
-	public function rmdir($path) {
344
-		$absolutePath = $this->getAbsolutePath($path);
345
-		$mount = Filesystem::getMountManager()->find($absolutePath);
346
-		if ($mount->getInternalPath($absolutePath) === '') {
347
-			return $this->removeMount($mount, $absolutePath);
348
-		}
349
-		if ($this->is_dir($path)) {
350
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
351
-		} else {
352
-			$result = false;
353
-		}
354
-
355
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
356
-			$storage = $mount->getStorage();
357
-			$internalPath = $mount->getInternalPath($absolutePath);
358
-			$storage->getUpdater()->remove($internalPath);
359
-		}
360
-		return $result;
361
-	}
362
-
363
-	/**
364
-	 * @param string $path
365
-	 * @return resource
366
-	 */
367
-	public function opendir($path) {
368
-		return $this->basicOperation('opendir', $path, ['read']);
369
-	}
370
-
371
-	/**
372
-	 * @param string $path
373
-	 * @return bool|mixed
374
-	 */
375
-	public function is_dir($path) {
376
-		if ($path == '/') {
377
-			return true;
378
-		}
379
-		return $this->basicOperation('is_dir', $path);
380
-	}
381
-
382
-	/**
383
-	 * @param string $path
384
-	 * @return bool|mixed
385
-	 */
386
-	public function is_file($path) {
387
-		if ($path == '/') {
388
-			return false;
389
-		}
390
-		return $this->basicOperation('is_file', $path);
391
-	}
392
-
393
-	/**
394
-	 * @param string $path
395
-	 * @return mixed
396
-	 */
397
-	public function stat($path) {
398
-		return $this->basicOperation('stat', $path);
399
-	}
400
-
401
-	/**
402
-	 * @param string $path
403
-	 * @return mixed
404
-	 */
405
-	public function filetype($path) {
406
-		return $this->basicOperation('filetype', $path);
407
-	}
408
-
409
-	/**
410
-	 * @param string $path
411
-	 * @return mixed
412
-	 */
413
-	public function filesize($path) {
414
-		return $this->basicOperation('filesize', $path);
415
-	}
416
-
417
-	/**
418
-	 * @param string $path
419
-	 * @return bool|mixed
420
-	 * @throws \OCP\Files\InvalidPathException
421
-	 */
422
-	public function readfile($path) {
423
-		$this->assertPathLength($path);
424
-		if (ob_get_level()) {
425
-			ob_end_clean();
426
-		}
427
-		$handle = $this->fopen($path, 'rb');
428
-		if ($handle) {
429
-			$chunkSize = 524288; // 512 kB chunks
430
-			while (!feof($handle)) {
431
-				echo fread($handle, $chunkSize);
432
-				flush();
433
-			}
434
-			fclose($handle);
435
-			return $this->filesize($path);
436
-		}
437
-		return false;
438
-	}
439
-
440
-	/**
441
-	 * @param string $path
442
-	 * @param int $from
443
-	 * @param int $to
444
-	 * @return bool|mixed
445
-	 * @throws \OCP\Files\InvalidPathException
446
-	 * @throws \OCP\Files\UnseekableException
447
-	 */
448
-	public function readfilePart($path, $from, $to) {
449
-		$this->assertPathLength($path);
450
-		if (ob_get_level()) {
451
-			ob_end_clean();
452
-		}
453
-		$handle = $this->fopen($path, 'rb');
454
-		if ($handle) {
455
-			$chunkSize = 524288; // 512 kB chunks
456
-			$startReading = true;
457
-
458
-			if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
459
-				// forward file handle via chunked fread because fseek seem to have failed
460
-
461
-				$end = $from + 1;
462
-				while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
463
-					$len = $from - ftell($handle);
464
-					if ($len > $chunkSize) {
465
-						$len = $chunkSize;
466
-					}
467
-					$result = fread($handle, $len);
468
-
469
-					if ($result === false) {
470
-						$startReading = false;
471
-						break;
472
-					}
473
-				}
474
-			}
475
-
476
-			if ($startReading) {
477
-				$end = $to + 1;
478
-				while (!feof($handle) && ftell($handle) < $end) {
479
-					$len = $end - ftell($handle);
480
-					if ($len > $chunkSize) {
481
-						$len = $chunkSize;
482
-					}
483
-					echo fread($handle, $len);
484
-					flush();
485
-				}
486
-				return ftell($handle) - $from;
487
-			}
488
-
489
-			throw new \OCP\Files\UnseekableException('fseek error');
490
-		}
491
-		return false;
492
-	}
493
-
494
-	/**
495
-	 * @param string $path
496
-	 * @return mixed
497
-	 */
498
-	public function isCreatable($path) {
499
-		return $this->basicOperation('isCreatable', $path);
500
-	}
501
-
502
-	/**
503
-	 * @param string $path
504
-	 * @return mixed
505
-	 */
506
-	public function isReadable($path) {
507
-		return $this->basicOperation('isReadable', $path);
508
-	}
509
-
510
-	/**
511
-	 * @param string $path
512
-	 * @return mixed
513
-	 */
514
-	public function isUpdatable($path) {
515
-		return $this->basicOperation('isUpdatable', $path);
516
-	}
517
-
518
-	/**
519
-	 * @param string $path
520
-	 * @return bool|mixed
521
-	 */
522
-	public function isDeletable($path) {
523
-		$absolutePath = $this->getAbsolutePath($path);
524
-		$mount = Filesystem::getMountManager()->find($absolutePath);
525
-		if ($mount->getInternalPath($absolutePath) === '') {
526
-			return $mount instanceof MoveableMount;
527
-		}
528
-		return $this->basicOperation('isDeletable', $path);
529
-	}
530
-
531
-	/**
532
-	 * @param string $path
533
-	 * @return mixed
534
-	 */
535
-	public function isSharable($path) {
536
-		return $this->basicOperation('isSharable', $path);
537
-	}
538
-
539
-	/**
540
-	 * @param string $path
541
-	 * @return bool|mixed
542
-	 */
543
-	public function file_exists($path) {
544
-		if ($path == '/') {
545
-			return true;
546
-		}
547
-		return $this->basicOperation('file_exists', $path);
548
-	}
549
-
550
-	/**
551
-	 * @param string $path
552
-	 * @return mixed
553
-	 */
554
-	public function filemtime($path) {
555
-		return $this->basicOperation('filemtime', $path);
556
-	}
557
-
558
-	/**
559
-	 * @param string $path
560
-	 * @param int|string $mtime
561
-	 * @return bool
562
-	 */
563
-	public function touch($path, $mtime = null) {
564
-		if (!is_null($mtime) and !is_numeric($mtime)) {
565
-			$mtime = strtotime($mtime);
566
-		}
567
-
568
-		$hooks = ['touch'];
569
-
570
-		if (!$this->file_exists($path)) {
571
-			$hooks[] = 'create';
572
-			$hooks[] = 'write';
573
-		}
574
-		try {
575
-			$result = $this->basicOperation('touch', $path, $hooks, $mtime);
576
-		} catch (\Exception $e) {
577
-			$this->logger->logException($e, ['level' => ILogger::INFO, 'message' => 'Error while setting modified time']);
578
-			$result = false;
579
-		}
580
-		if (!$result) {
581
-			// If create file fails because of permissions on external storage like SMB folders,
582
-			// check file exists and return false if not.
583
-			if (!$this->file_exists($path)) {
584
-				return false;
585
-			}
586
-			if (is_null($mtime)) {
587
-				$mtime = time();
588
-			}
589
-			//if native touch fails, we emulate it by changing the mtime in the cache
590
-			$this->putFileInfo($path, ['mtime' => floor($mtime)]);
591
-		}
592
-		return true;
593
-	}
594
-
595
-	/**
596
-	 * @param string $path
597
-	 * @return mixed
598
-	 * @throws LockedException
599
-	 */
600
-	public function file_get_contents($path) {
601
-		return $this->basicOperation('file_get_contents', $path, ['read']);
602
-	}
603
-
604
-	/**
605
-	 * @param bool $exists
606
-	 * @param string $path
607
-	 * @param bool $run
608
-	 */
609
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
610
-		if (!$exists) {
611
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
612
-				Filesystem::signal_param_path => $this->getHookPath($path),
613
-				Filesystem::signal_param_run => &$run,
614
-			]);
615
-		} else {
616
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
617
-				Filesystem::signal_param_path => $this->getHookPath($path),
618
-				Filesystem::signal_param_run => &$run,
619
-			]);
620
-		}
621
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
622
-			Filesystem::signal_param_path => $this->getHookPath($path),
623
-			Filesystem::signal_param_run => &$run,
624
-		]);
625
-	}
626
-
627
-	/**
628
-	 * @param bool $exists
629
-	 * @param string $path
630
-	 */
631
-	protected function emit_file_hooks_post($exists, $path) {
632
-		if (!$exists) {
633
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
634
-				Filesystem::signal_param_path => $this->getHookPath($path),
635
-			]);
636
-		} else {
637
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
638
-				Filesystem::signal_param_path => $this->getHookPath($path),
639
-			]);
640
-		}
641
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
642
-			Filesystem::signal_param_path => $this->getHookPath($path),
643
-		]);
644
-	}
645
-
646
-	/**
647
-	 * @param string $path
648
-	 * @param string|resource $data
649
-	 * @return bool|mixed
650
-	 * @throws LockedException
651
-	 */
652
-	public function file_put_contents($path, $data) {
653
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
654
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
655
-			if (Filesystem::isValidPath($path)
656
-				and !Filesystem::isFileBlacklisted($path)
657
-			) {
658
-				$path = $this->getRelativePath($absolutePath);
659
-
660
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
661
-
662
-				$exists = $this->file_exists($path);
663
-				$run = true;
664
-				if ($this->shouldEmitHooks($path)) {
665
-					$this->emit_file_hooks_pre($exists, $path, $run);
666
-				}
667
-				if (!$run) {
668
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
669
-					return false;
670
-				}
671
-
672
-				try {
673
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
674
-				} catch (\Exception $e) {
675
-					// Release the shared lock before throwing.
676
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
677
-					throw $e;
678
-				}
679
-
680
-				/** @var \OC\Files\Storage\Storage $storage */
681
-				[$storage, $internalPath] = $this->resolvePath($path);
682
-				$target = $storage->fopen($internalPath, 'w');
683
-				if ($target) {
684
-					[, $result] = \OC_Helper::streamCopy($data, $target);
685
-					fclose($target);
686
-					fclose($data);
687
-
688
-					$this->writeUpdate($storage, $internalPath);
689
-
690
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
691
-
692
-					if ($this->shouldEmitHooks($path) && $result !== false) {
693
-						$this->emit_file_hooks_post($exists, $path);
694
-					}
695
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
696
-					return $result;
697
-				} else {
698
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
699
-					return false;
700
-				}
701
-			} else {
702
-				return false;
703
-			}
704
-		} else {
705
-			$hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
706
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
707
-		}
708
-	}
709
-
710
-	/**
711
-	 * @param string $path
712
-	 * @return bool|mixed
713
-	 */
714
-	public function unlink($path) {
715
-		if ($path === '' || $path === '/') {
716
-			// do not allow deleting the root
717
-			return false;
718
-		}
719
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
720
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
721
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
722
-		if ($mount->getInternalPath($absolutePath) === '') {
723
-			return $this->removeMount($mount, $absolutePath);
724
-		}
725
-		if ($this->is_dir($path)) {
726
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
727
-		} else {
728
-			$result = $this->basicOperation('unlink', $path, ['delete']);
729
-		}
730
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
731
-			$storage = $mount->getStorage();
732
-			$internalPath = $mount->getInternalPath($absolutePath);
733
-			$storage->getUpdater()->remove($internalPath);
734
-			return true;
735
-		} else {
736
-			return $result;
737
-		}
738
-	}
739
-
740
-	/**
741
-	 * @param string $directory
742
-	 * @return bool|mixed
743
-	 */
744
-	public function deleteAll($directory) {
745
-		return $this->rmdir($directory);
746
-	}
747
-
748
-	/**
749
-	 * Rename/move a file or folder from the source path to target path.
750
-	 *
751
-	 * @param string $path1 source path
752
-	 * @param string $path2 target path
753
-	 *
754
-	 * @return bool|mixed
755
-	 * @throws LockedException
756
-	 */
757
-	public function rename($path1, $path2) {
758
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
759
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
760
-		$result = false;
761
-		if (
762
-			Filesystem::isValidPath($path2)
763
-			and Filesystem::isValidPath($path1)
764
-			and !Filesystem::isFileBlacklisted($path2)
765
-		) {
766
-			$path1 = $this->getRelativePath($absolutePath1);
767
-			$path2 = $this->getRelativePath($absolutePath2);
768
-			$exists = $this->file_exists($path2);
769
-
770
-			if ($path1 == null or $path2 == null) {
771
-				return false;
772
-			}
773
-
774
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
775
-			try {
776
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
777
-
778
-				$run = true;
779
-				if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
780
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
781
-					$this->emit_file_hooks_pre($exists, $path2, $run);
782
-				} elseif ($this->shouldEmitHooks($path1)) {
783
-					\OC_Hook::emit(
784
-						Filesystem::CLASSNAME, Filesystem::signal_rename,
785
-						[
786
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
787
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
788
-							Filesystem::signal_param_run => &$run
789
-						]
790
-					);
791
-				}
792
-				if ($run) {
793
-					$this->verifyPath(dirname($path2), basename($path2));
794
-
795
-					$manager = Filesystem::getMountManager();
796
-					$mount1 = $this->getMount($path1);
797
-					$mount2 = $this->getMount($path2);
798
-					$storage1 = $mount1->getStorage();
799
-					$storage2 = $mount2->getStorage();
800
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
801
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
802
-
803
-					$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
804
-					try {
805
-						$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
806
-
807
-						if ($internalPath1 === '') {
808
-							if ($mount1 instanceof MoveableMount) {
809
-								$sourceParentMount = $this->getMount(dirname($path1));
810
-								if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
811
-									/**
812
-									 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
813
-									 */
814
-									$sourceMountPoint = $mount1->getMountPoint();
815
-									$result = $mount1->moveMount($absolutePath2);
816
-									$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
817
-								} else {
818
-									$result = false;
819
-								}
820
-							} else {
821
-								$result = false;
822
-							}
823
-							// moving a file/folder within the same mount point
824
-						} elseif ($storage1 === $storage2) {
825
-							if ($storage1) {
826
-								$result = $storage1->rename($internalPath1, $internalPath2);
827
-							} else {
828
-								$result = false;
829
-							}
830
-							// moving a file/folder between storages (from $storage1 to $storage2)
831
-						} else {
832
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
833
-						}
834
-
835
-						if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
836
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
837
-							$this->writeUpdate($storage2, $internalPath2);
838
-						} elseif ($result) {
839
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
840
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
841
-							}
842
-						}
843
-					} catch (\Exception $e) {
844
-						throw $e;
845
-					} finally {
846
-						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
847
-						$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
848
-					}
849
-
850
-					if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
851
-						if ($this->shouldEmitHooks()) {
852
-							$this->emit_file_hooks_post($exists, $path2);
853
-						}
854
-					} elseif ($result) {
855
-						if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
856
-							\OC_Hook::emit(
857
-								Filesystem::CLASSNAME,
858
-								Filesystem::signal_post_rename,
859
-								[
860
-									Filesystem::signal_param_oldpath => $this->getHookPath($path1),
861
-									Filesystem::signal_param_newpath => $this->getHookPath($path2)
862
-								]
863
-							);
864
-						}
865
-					}
866
-				}
867
-			} catch (\Exception $e) {
868
-				throw $e;
869
-			} finally {
870
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
871
-				$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
872
-			}
873
-		}
874
-		return $result;
875
-	}
876
-
877
-	/**
878
-	 * Copy a file/folder from the source path to target path
879
-	 *
880
-	 * @param string $path1 source path
881
-	 * @param string $path2 target path
882
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
883
-	 *
884
-	 * @return bool|mixed
885
-	 */
886
-	public function copy($path1, $path2, $preserveMtime = false) {
887
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
888
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
889
-		$result = false;
890
-		if (
891
-			Filesystem::isValidPath($path2)
892
-			and Filesystem::isValidPath($path1)
893
-			and !Filesystem::isFileBlacklisted($path2)
894
-		) {
895
-			$path1 = $this->getRelativePath($absolutePath1);
896
-			$path2 = $this->getRelativePath($absolutePath2);
897
-
898
-			if ($path1 == null or $path2 == null) {
899
-				return false;
900
-			}
901
-			$run = true;
902
-
903
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
904
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
905
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
906
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
907
-
908
-			try {
909
-				$exists = $this->file_exists($path2);
910
-				if ($this->shouldEmitHooks()) {
911
-					\OC_Hook::emit(
912
-						Filesystem::CLASSNAME,
913
-						Filesystem::signal_copy,
914
-						[
915
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
916
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
917
-							Filesystem::signal_param_run => &$run
918
-						]
919
-					);
920
-					$this->emit_file_hooks_pre($exists, $path2, $run);
921
-				}
922
-				if ($run) {
923
-					$mount1 = $this->getMount($path1);
924
-					$mount2 = $this->getMount($path2);
925
-					$storage1 = $mount1->getStorage();
926
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
927
-					$storage2 = $mount2->getStorage();
928
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
929
-
930
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
931
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
932
-
933
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
934
-						if ($storage1) {
935
-							$result = $storage1->copy($internalPath1, $internalPath2);
936
-						} else {
937
-							$result = false;
938
-						}
939
-					} else {
940
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
941
-					}
942
-
943
-					$this->writeUpdate($storage2, $internalPath2);
944
-
945
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
946
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
947
-
948
-					if ($this->shouldEmitHooks() && $result !== false) {
949
-						\OC_Hook::emit(
950
-							Filesystem::CLASSNAME,
951
-							Filesystem::signal_post_copy,
952
-							[
953
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
954
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
955
-							]
956
-						);
957
-						$this->emit_file_hooks_post($exists, $path2);
958
-					}
959
-				}
960
-			} catch (\Exception $e) {
961
-				$this->unlockFile($path2, $lockTypePath2);
962
-				$this->unlockFile($path1, $lockTypePath1);
963
-				throw $e;
964
-			}
965
-
966
-			$this->unlockFile($path2, $lockTypePath2);
967
-			$this->unlockFile($path1, $lockTypePath1);
968
-		}
969
-		return $result;
970
-	}
971
-
972
-	/**
973
-	 * @param string $path
974
-	 * @param string $mode 'r' or 'w'
975
-	 * @return resource
976
-	 * @throws LockedException
977
-	 */
978
-	public function fopen($path, $mode) {
979
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
980
-		$hooks = [];
981
-		switch ($mode) {
982
-			case 'r':
983
-				$hooks[] = 'read';
984
-				break;
985
-			case 'r+':
986
-			case 'w+':
987
-			case 'x+':
988
-			case 'a+':
989
-				$hooks[] = 'read';
990
-				$hooks[] = 'write';
991
-				break;
992
-			case 'w':
993
-			case 'x':
994
-			case 'a':
995
-				$hooks[] = 'write';
996
-				break;
997
-			default:
998
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, ILogger::ERROR);
999
-		}
1000
-
1001
-		if ($mode !== 'r' && $mode !== 'w') {
1002
-			\OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
1003
-		}
1004
-
1005
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
1006
-	}
1007
-
1008
-	/**
1009
-	 * @param string $path
1010
-	 * @return bool|string
1011
-	 * @throws \OCP\Files\InvalidPathException
1012
-	 */
1013
-	public function toTmpFile($path) {
1014
-		$this->assertPathLength($path);
1015
-		if (Filesystem::isValidPath($path)) {
1016
-			$source = $this->fopen($path, 'r');
1017
-			if ($source) {
1018
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
1019
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1020
-				file_put_contents($tmpFile, $source);
1021
-				return $tmpFile;
1022
-			} else {
1023
-				return false;
1024
-			}
1025
-		} else {
1026
-			return false;
1027
-		}
1028
-	}
1029
-
1030
-	/**
1031
-	 * @param string $tmpFile
1032
-	 * @param string $path
1033
-	 * @return bool|mixed
1034
-	 * @throws \OCP\Files\InvalidPathException
1035
-	 */
1036
-	public function fromTmpFile($tmpFile, $path) {
1037
-		$this->assertPathLength($path);
1038
-		if (Filesystem::isValidPath($path)) {
1039
-
1040
-			// Get directory that the file is going into
1041
-			$filePath = dirname($path);
1042
-
1043
-			// Create the directories if any
1044
-			if (!$this->file_exists($filePath)) {
1045
-				$result = $this->createParentDirectories($filePath);
1046
-				if ($result === false) {
1047
-					return false;
1048
-				}
1049
-			}
1050
-
1051
-			$source = fopen($tmpFile, 'r');
1052
-			if ($source) {
1053
-				$result = $this->file_put_contents($path, $source);
1054
-				// $this->file_put_contents() might have already closed
1055
-				// the resource, so we check it, before trying to close it
1056
-				// to avoid messages in the error log.
1057
-				if (is_resource($source)) {
1058
-					fclose($source);
1059
-				}
1060
-				unlink($tmpFile);
1061
-				return $result;
1062
-			} else {
1063
-				return false;
1064
-			}
1065
-		} else {
1066
-			return false;
1067
-		}
1068
-	}
1069
-
1070
-
1071
-	/**
1072
-	 * @param string $path
1073
-	 * @return mixed
1074
-	 * @throws \OCP\Files\InvalidPathException
1075
-	 */
1076
-	public function getMimeType($path) {
1077
-		$this->assertPathLength($path);
1078
-		return $this->basicOperation('getMimeType', $path);
1079
-	}
1080
-
1081
-	/**
1082
-	 * @param string $type
1083
-	 * @param string $path
1084
-	 * @param bool $raw
1085
-	 * @return bool|string
1086
-	 */
1087
-	public function hash($type, $path, $raw = false) {
1088
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1089
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1090
-		if (Filesystem::isValidPath($path)) {
1091
-			$path = $this->getRelativePath($absolutePath);
1092
-			if ($path == null) {
1093
-				return false;
1094
-			}
1095
-			if ($this->shouldEmitHooks($path)) {
1096
-				\OC_Hook::emit(
1097
-					Filesystem::CLASSNAME,
1098
-					Filesystem::signal_read,
1099
-					[Filesystem::signal_param_path => $this->getHookPath($path)]
1100
-				);
1101
-			}
1102
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1103
-			if ($storage) {
1104
-				return $storage->hash($type, $internalPath, $raw);
1105
-			}
1106
-		}
1107
-		return false;
1108
-	}
1109
-
1110
-	/**
1111
-	 * @param string $path
1112
-	 * @return mixed
1113
-	 * @throws \OCP\Files\InvalidPathException
1114
-	 */
1115
-	public function free_space($path = '/') {
1116
-		$this->assertPathLength($path);
1117
-		$result = $this->basicOperation('free_space', $path);
1118
-		if ($result === null) {
1119
-			throw new InvalidPathException();
1120
-		}
1121
-		return $result;
1122
-	}
1123
-
1124
-	/**
1125
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1126
-	 *
1127
-	 * @param string $operation
1128
-	 * @param string $path
1129
-	 * @param array $hooks (optional)
1130
-	 * @param mixed $extraParam (optional)
1131
-	 * @return mixed
1132
-	 * @throws LockedException
1133
-	 *
1134
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1135
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1136
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1137
-	 */
1138
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1139
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1140
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1141
-		if (Filesystem::isValidPath($path)
1142
-			and !Filesystem::isFileBlacklisted($path)
1143
-		) {
1144
-			$path = $this->getRelativePath($absolutePath);
1145
-			if ($path == null) {
1146
-				return false;
1147
-			}
1148
-
1149
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1150
-				// always a shared lock during pre-hooks so the hook can read the file
1151
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1152
-			}
1153
-
1154
-			$run = $this->runHooks($hooks, $path);
1155
-			/** @var \OC\Files\Storage\Storage $storage */
1156
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1157
-			if ($run and $storage) {
1158
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1159
-					try {
1160
-						$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1161
-					} catch (LockedException $e) {
1162
-						// release the shared lock we acquired before quiting
1163
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1164
-						throw $e;
1165
-					}
1166
-				}
1167
-				try {
1168
-					if (!is_null($extraParam)) {
1169
-						$result = $storage->$operation($internalPath, $extraParam);
1170
-					} else {
1171
-						$result = $storage->$operation($internalPath);
1172
-					}
1173
-				} catch (\Exception $e) {
1174
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1175
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1176
-					} elseif (in_array('read', $hooks)) {
1177
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1178
-					}
1179
-					throw $e;
1180
-				}
1181
-
1182
-				if ($result && in_array('delete', $hooks) and $result) {
1183
-					$this->removeUpdate($storage, $internalPath);
1184
-				}
1185
-				if ($result && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
1186
-					$this->writeUpdate($storage, $internalPath);
1187
-				}
1188
-				if ($result && in_array('touch', $hooks)) {
1189
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1190
-				}
1191
-
1192
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1193
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1194
-				}
1195
-
1196
-				$unlockLater = false;
1197
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1198
-					$unlockLater = true;
1199
-					// make sure our unlocking callback will still be called if connection is aborted
1200
-					ignore_user_abort(true);
1201
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1202
-						if (in_array('write', $hooks)) {
1203
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1204
-						} elseif (in_array('read', $hooks)) {
1205
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1206
-						}
1207
-					});
1208
-				}
1209
-
1210
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1211
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1212
-						$this->runHooks($hooks, $path, true);
1213
-					}
1214
-				}
1215
-
1216
-				if (!$unlockLater
1217
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1218
-				) {
1219
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1220
-				}
1221
-				return $result;
1222
-			} else {
1223
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1224
-			}
1225
-		}
1226
-		return null;
1227
-	}
1228
-
1229
-	/**
1230
-	 * get the path relative to the default root for hook usage
1231
-	 *
1232
-	 * @param string $path
1233
-	 * @return string
1234
-	 */
1235
-	private function getHookPath($path) {
1236
-		if (!Filesystem::getView()) {
1237
-			return $path;
1238
-		}
1239
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1240
-	}
1241
-
1242
-	private function shouldEmitHooks($path = '') {
1243
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1244
-			return false;
1245
-		}
1246
-		if (!Filesystem::$loaded) {
1247
-			return false;
1248
-		}
1249
-		$defaultRoot = Filesystem::getRoot();
1250
-		if ($defaultRoot === null) {
1251
-			return false;
1252
-		}
1253
-		if ($this->fakeRoot === $defaultRoot) {
1254
-			return true;
1255
-		}
1256
-		$fullPath = $this->getAbsolutePath($path);
1257
-
1258
-		if ($fullPath === $defaultRoot) {
1259
-			return true;
1260
-		}
1261
-
1262
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1263
-	}
1264
-
1265
-	/**
1266
-	 * @param string[] $hooks
1267
-	 * @param string $path
1268
-	 * @param bool $post
1269
-	 * @return bool
1270
-	 */
1271
-	private function runHooks($hooks, $path, $post = false) {
1272
-		$relativePath = $path;
1273
-		$path = $this->getHookPath($path);
1274
-		$prefix = $post ? 'post_' : '';
1275
-		$run = true;
1276
-		if ($this->shouldEmitHooks($relativePath)) {
1277
-			foreach ($hooks as $hook) {
1278
-				if ($hook != 'read') {
1279
-					\OC_Hook::emit(
1280
-						Filesystem::CLASSNAME,
1281
-						$prefix . $hook,
1282
-						[
1283
-							Filesystem::signal_param_run => &$run,
1284
-							Filesystem::signal_param_path => $path
1285
-						]
1286
-					);
1287
-				} elseif (!$post) {
1288
-					\OC_Hook::emit(
1289
-						Filesystem::CLASSNAME,
1290
-						$prefix . $hook,
1291
-						[
1292
-							Filesystem::signal_param_path => $path
1293
-						]
1294
-					);
1295
-				}
1296
-			}
1297
-		}
1298
-		return $run;
1299
-	}
1300
-
1301
-	/**
1302
-	 * check if a file or folder has been updated since $time
1303
-	 *
1304
-	 * @param string $path
1305
-	 * @param int $time
1306
-	 * @return bool
1307
-	 */
1308
-	public function hasUpdated($path, $time) {
1309
-		return $this->basicOperation('hasUpdated', $path, [], $time);
1310
-	}
1311
-
1312
-	/**
1313
-	 * @param string $ownerId
1314
-	 * @return \OC\User\User
1315
-	 */
1316
-	private function getUserObjectForOwner($ownerId) {
1317
-		$owner = $this->userManager->get($ownerId);
1318
-		if ($owner instanceof IUser) {
1319
-			return $owner;
1320
-		} else {
1321
-			return new User($ownerId, null, \OC::$server->getEventDispatcher());
1322
-		}
1323
-	}
1324
-
1325
-	/**
1326
-	 * Get file info from cache
1327
-	 *
1328
-	 * If the file is not in cached it will be scanned
1329
-	 * If the file has changed on storage the cache will be updated
1330
-	 *
1331
-	 * @param \OC\Files\Storage\Storage $storage
1332
-	 * @param string $internalPath
1333
-	 * @param string $relativePath
1334
-	 * @return ICacheEntry|bool
1335
-	 */
1336
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1337
-		$cache = $storage->getCache($internalPath);
1338
-		$data = $cache->get($internalPath);
1339
-		$watcher = $storage->getWatcher($internalPath);
1340
-
1341
-		try {
1342
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1343
-			if (!$data || (isset($data['size']) && $data['size'] === -1)) {
1344
-				if (!$storage->file_exists($internalPath)) {
1345
-					return false;
1346
-				}
1347
-				// don't need to get a lock here since the scanner does it's own locking
1348
-				$scanner = $storage->getScanner($internalPath);
1349
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1350
-				$data = $cache->get($internalPath);
1351
-			} elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1352
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1353
-				$watcher->update($internalPath, $data);
1354
-				$storage->getPropagator()->propagateChange($internalPath, time());
1355
-				$data = $cache->get($internalPath);
1356
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1357
-			}
1358
-		} catch (LockedException $e) {
1359
-			// if the file is locked we just use the old cache info
1360
-		}
1361
-
1362
-		return $data;
1363
-	}
1364
-
1365
-	/**
1366
-	 * get the filesystem info
1367
-	 *
1368
-	 * @param string $path
1369
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1370
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1371
-	 * defaults to true
1372
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1373
-	 */
1374
-	public function getFileInfo($path, $includeMountPoints = true) {
1375
-		$this->assertPathLength($path);
1376
-		if (!Filesystem::isValidPath($path)) {
1377
-			return false;
1378
-		}
1379
-		if (Cache\Scanner::isPartialFile($path)) {
1380
-			return $this->getPartFileInfo($path);
1381
-		}
1382
-		$relativePath = $path;
1383
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1384
-
1385
-		$mount = Filesystem::getMountManager()->find($path);
1386
-		$storage = $mount->getStorage();
1387
-		$internalPath = $mount->getInternalPath($path);
1388
-		if ($storage) {
1389
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1390
-
1391
-			if (!$data instanceof ICacheEntry) {
1392
-				return false;
1393
-			}
1394
-
1395
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1396
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1397
-			}
1398
-			$ownerId = $storage->getOwner($internalPath);
1399
-			$owner = null;
1400
-			if ($ownerId !== null && $ownerId !== false) {
1401
-				// ownerId might be null if files are accessed with an access token without file system access
1402
-				$owner = $this->getUserObjectForOwner($ownerId);
1403
-			}
1404
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1405
-
1406
-			if (isset($data['fileid'])) {
1407
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1408
-					//add the sizes of other mount points to the folder
1409
-					$extOnly = ($includeMountPoints === 'ext');
1410
-					$mounts = Filesystem::getMountManager()->findIn($path);
1411
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1412
-						$subStorage = $mount->getStorage();
1413
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1414
-					}));
1415
-				}
1416
-			}
1417
-
1418
-			return $info;
1419
-		} else {
1420
-			\OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
1421
-		}
1422
-
1423
-		return false;
1424
-	}
1425
-
1426
-	/**
1427
-	 * get the content of a directory
1428
-	 *
1429
-	 * @param string $directory path under datadirectory
1430
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1431
-	 * @return FileInfo[]
1432
-	 */
1433
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1434
-		$this->assertPathLength($directory);
1435
-		if (!Filesystem::isValidPath($directory)) {
1436
-			return [];
1437
-		}
1438
-		$path = $this->getAbsolutePath($directory);
1439
-		$path = Filesystem::normalizePath($path);
1440
-		$mount = $this->getMount($directory);
1441
-		if (!$mount) {
1442
-			return [];
1443
-		}
1444
-		$storage = $mount->getStorage();
1445
-		$internalPath = $mount->getInternalPath($path);
1446
-		if ($storage) {
1447
-			$cache = $storage->getCache($internalPath);
1448
-			$user = \OC_User::getUser();
1449
-
1450
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1451
-
1452
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1453
-				return [];
1454
-			}
1455
-
1456
-			$folderId = $data['fileid'];
1457
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1458
-
1459
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1460
-
1461
-			$fileNames = array_map(function (ICacheEntry $content) {
1462
-				return $content->getName();
1463
-			}, $contents);
1464
-			/**
1465
-			 * @var \OC\Files\FileInfo[] $fileInfos
1466
-			 */
1467
-			$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1468
-				if ($sharingDisabled) {
1469
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1470
-				}
1471
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1472
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1473
-			}, $contents);
1474
-			$files = array_combine($fileNames, $fileInfos);
1475
-
1476
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1477
-			$mounts = Filesystem::getMountManager()->findIn($path);
1478
-			$dirLength = strlen($path);
1479
-			foreach ($mounts as $mount) {
1480
-				$mountPoint = $mount->getMountPoint();
1481
-				$subStorage = $mount->getStorage();
1482
-				if ($subStorage) {
1483
-					$subCache = $subStorage->getCache('');
1484
-
1485
-					$rootEntry = $subCache->get('');
1486
-					if (!$rootEntry) {
1487
-						$subScanner = $subStorage->getScanner();
1488
-						try {
1489
-							$subScanner->scanFile('');
1490
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1491
-							continue;
1492
-						} catch (\OCP\Files\StorageInvalidException $e) {
1493
-							continue;
1494
-						} catch (\Exception $e) {
1495
-							// sometimes when the storage is not available it can be any exception
1496
-							\OC::$server->getLogger()->logException($e, [
1497
-								'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
1498
-								'level' => ILogger::ERROR,
1499
-								'app' => 'lib',
1500
-							]);
1501
-							continue;
1502
-						}
1503
-						$rootEntry = $subCache->get('');
1504
-					}
1505
-
1506
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1507
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1508
-						if ($pos = strpos($relativePath, '/')) {
1509
-							//mountpoint inside subfolder add size to the correct folder
1510
-							$entryName = substr($relativePath, 0, $pos);
1511
-							foreach ($files as &$entry) {
1512
-								if ($entry->getName() === $entryName) {
1513
-									$entry->addSubEntry($rootEntry, $mountPoint);
1514
-								}
1515
-							}
1516
-						} else { //mountpoint in this folder, add an entry for it
1517
-							$rootEntry['name'] = $relativePath;
1518
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1519
-							$permissions = $rootEntry['permissions'];
1520
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1521
-							// for shared files/folders we use the permissions given by the owner
1522
-							if ($mount instanceof MoveableMount) {
1523
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1524
-							} else {
1525
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1526
-							}
1527
-
1528
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1529
-
1530
-							// if sharing was disabled for the user we remove the share permissions
1531
-							if (\OCP\Util::isSharingDisabledForUser()) {
1532
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1533
-							}
1534
-
1535
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1536
-							$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1537
-						}
1538
-					}
1539
-				}
1540
-			}
1541
-
1542
-			if ($mimetype_filter) {
1543
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1544
-					if (strpos($mimetype_filter, '/')) {
1545
-						return $file->getMimetype() === $mimetype_filter;
1546
-					} else {
1547
-						return $file->getMimePart() === $mimetype_filter;
1548
-					}
1549
-				});
1550
-			}
1551
-
1552
-			return array_values($files);
1553
-		} else {
1554
-			return [];
1555
-		}
1556
-	}
1557
-
1558
-	/**
1559
-	 * change file metadata
1560
-	 *
1561
-	 * @param string $path
1562
-	 * @param array|\OCP\Files\FileInfo $data
1563
-	 * @return int
1564
-	 *
1565
-	 * returns the fileid of the updated file
1566
-	 */
1567
-	public function putFileInfo($path, $data) {
1568
-		$this->assertPathLength($path);
1569
-		if ($data instanceof FileInfo) {
1570
-			$data = $data->getData();
1571
-		}
1572
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1573
-		/**
1574
-		 * @var \OC\Files\Storage\Storage $storage
1575
-		 * @var string $internalPath
1576
-		 */
1577
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
1578
-		if ($storage) {
1579
-			$cache = $storage->getCache($path);
1580
-
1581
-			if (!$cache->inCache($internalPath)) {
1582
-				$scanner = $storage->getScanner($internalPath);
1583
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1584
-			}
1585
-
1586
-			return $cache->put($internalPath, $data);
1587
-		} else {
1588
-			return -1;
1589
-		}
1590
-	}
1591
-
1592
-	/**
1593
-	 * search for files with the name matching $query
1594
-	 *
1595
-	 * @param string $query
1596
-	 * @return FileInfo[]
1597
-	 */
1598
-	public function search($query) {
1599
-		return $this->searchCommon('search', ['%' . $query . '%']);
1600
-	}
1601
-
1602
-	/**
1603
-	 * search for files with the name matching $query
1604
-	 *
1605
-	 * @param string $query
1606
-	 * @return FileInfo[]
1607
-	 */
1608
-	public function searchRaw($query) {
1609
-		return $this->searchCommon('search', [$query]);
1610
-	}
1611
-
1612
-	/**
1613
-	 * search for files by mimetype
1614
-	 *
1615
-	 * @param string $mimetype
1616
-	 * @return FileInfo[]
1617
-	 */
1618
-	public function searchByMime($mimetype) {
1619
-		return $this->searchCommon('searchByMime', [$mimetype]);
1620
-	}
1621
-
1622
-	/**
1623
-	 * search for files by tag
1624
-	 *
1625
-	 * @param string|int $tag name or tag id
1626
-	 * @param string $userId owner of the tags
1627
-	 * @return FileInfo[]
1628
-	 */
1629
-	public function searchByTag($tag, $userId) {
1630
-		return $this->searchCommon('searchByTag', [$tag, $userId]);
1631
-	}
1632
-
1633
-	/**
1634
-	 * @param string $method cache method
1635
-	 * @param array $args
1636
-	 * @return FileInfo[]
1637
-	 */
1638
-	private function searchCommon($method, $args) {
1639
-		$files = [];
1640
-		$rootLength = strlen($this->fakeRoot);
1641
-
1642
-		$mount = $this->getMount('');
1643
-		$mountPoint = $mount->getMountPoint();
1644
-		$storage = $mount->getStorage();
1645
-		$userManager = \OC::$server->getUserManager();
1646
-		if ($storage) {
1647
-			$cache = $storage->getCache('');
1648
-
1649
-			$results = call_user_func_array([$cache, $method], $args);
1650
-			foreach ($results as $result) {
1651
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1652
-					$internalPath = $result['path'];
1653
-					$path = $mountPoint . $result['path'];
1654
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1655
-					$owner = $userManager->get($storage->getOwner($internalPath));
1656
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1657
-				}
1658
-			}
1659
-
1660
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1661
-			foreach ($mounts as $mount) {
1662
-				$mountPoint = $mount->getMountPoint();
1663
-				$storage = $mount->getStorage();
1664
-				if ($storage) {
1665
-					$cache = $storage->getCache('');
1666
-
1667
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1668
-					$results = call_user_func_array([$cache, $method], $args);
1669
-					if ($results) {
1670
-						foreach ($results as $result) {
1671
-							$internalPath = $result['path'];
1672
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1673
-							$path = rtrim($mountPoint . $internalPath, '/');
1674
-							$owner = $userManager->get($storage->getOwner($internalPath));
1675
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1676
-						}
1677
-					}
1678
-				}
1679
-			}
1680
-		}
1681
-		return $files;
1682
-	}
1683
-
1684
-	/**
1685
-	 * Get the owner for a file or folder
1686
-	 *
1687
-	 * @param string $path
1688
-	 * @return string the user id of the owner
1689
-	 * @throws NotFoundException
1690
-	 */
1691
-	public function getOwner($path) {
1692
-		$info = $this->getFileInfo($path);
1693
-		if (!$info) {
1694
-			throw new NotFoundException($path . ' not found while trying to get owner');
1695
-		}
1696
-
1697
-		if ($info->getOwner() === null) {
1698
-			throw new NotFoundException($path . ' has no owner');
1699
-		}
1700
-
1701
-		return $info->getOwner()->getUID();
1702
-	}
1703
-
1704
-	/**
1705
-	 * get the ETag for a file or folder
1706
-	 *
1707
-	 * @param string $path
1708
-	 * @return string
1709
-	 */
1710
-	public function getETag($path) {
1711
-		/**
1712
-		 * @var Storage\Storage $storage
1713
-		 * @var string $internalPath
1714
-		 */
1715
-		[$storage, $internalPath] = $this->resolvePath($path);
1716
-		if ($storage) {
1717
-			return $storage->getETag($internalPath);
1718
-		} else {
1719
-			return null;
1720
-		}
1721
-	}
1722
-
1723
-	/**
1724
-	 * Get the path of a file by id, relative to the view
1725
-	 *
1726
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1727
-	 *
1728
-	 * @param int $id
1729
-	 * @param int|null $storageId
1730
-	 * @return string
1731
-	 * @throws NotFoundException
1732
-	 */
1733
-	public function getPath($id, int $storageId = null) {
1734
-		$id = (int)$id;
1735
-		$manager = Filesystem::getMountManager();
1736
-		$mounts = $manager->findIn($this->fakeRoot);
1737
-		$mounts[] = $manager->find($this->fakeRoot);
1738
-		$mounts = array_filter($mounts);
1739
-		// reverse the array, so we start with the storage this view is in
1740
-		// which is the most likely to contain the file we're looking for
1741
-		$mounts = array_reverse($mounts);
1742
-
1743
-		// put non-shared mounts in front of the shared mount
1744
-		// this prevents unneeded recursion into shares
1745
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1746
-			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1747
-		});
1748
-
1749
-		if (!is_null($storageId)) {
1750
-			$mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1751
-				return $mount->getNumericStorageId() === $storageId;
1752
-			});
1753
-		}
1754
-
1755
-		foreach ($mounts as $mount) {
1756
-			/**
1757
-			 * @var \OC\Files\Mount\MountPoint $mount
1758
-			 */
1759
-			if ($mount->getStorage()) {
1760
-				$cache = $mount->getStorage()->getCache();
1761
-				$internalPath = $cache->getPathById($id);
1762
-				if (is_string($internalPath)) {
1763
-					$fullPath = $mount->getMountPoint() . $internalPath;
1764
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1765
-						return $path;
1766
-					}
1767
-				}
1768
-			}
1769
-		}
1770
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1771
-	}
1772
-
1773
-	/**
1774
-	 * @param string $path
1775
-	 * @throws InvalidPathException
1776
-	 */
1777
-	private function assertPathLength($path) {
1778
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1779
-		// Check for the string length - performed using isset() instead of strlen()
1780
-		// because isset() is about 5x-40x faster.
1781
-		if (isset($path[$maxLen])) {
1782
-			$pathLen = strlen($path);
1783
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1784
-		}
1785
-	}
1786
-
1787
-	/**
1788
-	 * check if it is allowed to move a mount point to a given target.
1789
-	 * It is not allowed to move a mount point into a different mount point or
1790
-	 * into an already shared folder
1791
-	 *
1792
-	 * @param IStorage $targetStorage
1793
-	 * @param string $targetInternalPath
1794
-	 * @return boolean
1795
-	 */
1796
-	private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1797
-
1798
-		// note: cannot use the view because the target is already locked
1799
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1800
-		if ($fileId === -1) {
1801
-			// target might not exist, need to check parent instead
1802
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1803
-		}
1804
-
1805
-		// check if any of the parents were shared by the current owner (include collections)
1806
-		$shares = \OCP\Share::getItemShared(
1807
-			'folder',
1808
-			$fileId,
1809
-			\OCP\Share::FORMAT_NONE,
1810
-			null,
1811
-			true
1812
-		);
1813
-
1814
-		if (count($shares) > 0) {
1815
-			\OCP\Util::writeLog('files',
1816
-				'It is not allowed to move one mount point into a shared folder',
1817
-				ILogger::DEBUG);
1818
-			return false;
1819
-		}
1820
-
1821
-		return true;
1822
-	}
1823
-
1824
-	/**
1825
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1826
-	 *
1827
-	 * @param string $path
1828
-	 * @return \OCP\Files\FileInfo
1829
-	 */
1830
-	private function getPartFileInfo($path) {
1831
-		$mount = $this->getMount($path);
1832
-		$storage = $mount->getStorage();
1833
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1834
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1835
-		return new FileInfo(
1836
-			$this->getAbsolutePath($path),
1837
-			$storage,
1838
-			$internalPath,
1839
-			[
1840
-				'fileid' => null,
1841
-				'mimetype' => $storage->getMimeType($internalPath),
1842
-				'name' => basename($path),
1843
-				'etag' => null,
1844
-				'size' => $storage->filesize($internalPath),
1845
-				'mtime' => $storage->filemtime($internalPath),
1846
-				'encrypted' => false,
1847
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1848
-			],
1849
-			$mount,
1850
-			$owner
1851
-		);
1852
-	}
1853
-
1854
-	/**
1855
-	 * @param string $path
1856
-	 * @param string $fileName
1857
-	 * @throws InvalidPathException
1858
-	 */
1859
-	public function verifyPath($path, $fileName) {
1860
-		try {
1861
-			/** @type \OCP\Files\Storage $storage */
1862
-			[$storage, $internalPath] = $this->resolvePath($path);
1863
-			$storage->verifyPath($internalPath, $fileName);
1864
-		} catch (ReservedWordException $ex) {
1865
-			$l = \OC::$server->getL10N('lib');
1866
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1867
-		} catch (InvalidCharacterInPathException $ex) {
1868
-			$l = \OC::$server->getL10N('lib');
1869
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1870
-		} catch (FileNameTooLongException $ex) {
1871
-			$l = \OC::$server->getL10N('lib');
1872
-			throw new InvalidPathException($l->t('File name is too long'));
1873
-		} catch (InvalidDirectoryException $ex) {
1874
-			$l = \OC::$server->getL10N('lib');
1875
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1876
-		} catch (EmptyFileNameException $ex) {
1877
-			$l = \OC::$server->getL10N('lib');
1878
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1879
-		}
1880
-	}
1881
-
1882
-	/**
1883
-	 * get all parent folders of $path
1884
-	 *
1885
-	 * @param string $path
1886
-	 * @return string[]
1887
-	 */
1888
-	private function getParents($path) {
1889
-		$path = trim($path, '/');
1890
-		if (!$path) {
1891
-			return [];
1892
-		}
1893
-
1894
-		$parts = explode('/', $path);
1895
-
1896
-		// remove the single file
1897
-		array_pop($parts);
1898
-		$result = ['/'];
1899
-		$resultPath = '';
1900
-		foreach ($parts as $part) {
1901
-			if ($part) {
1902
-				$resultPath .= '/' . $part;
1903
-				$result[] = $resultPath;
1904
-			}
1905
-		}
1906
-		return $result;
1907
-	}
1908
-
1909
-	/**
1910
-	 * Returns the mount point for which to lock
1911
-	 *
1912
-	 * @param string $absolutePath absolute path
1913
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1914
-	 * is mounted directly on the given path, false otherwise
1915
-	 * @return IMountPoint mount point for which to apply locks
1916
-	 */
1917
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1918
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1919
-
1920
-		if ($useParentMount) {
1921
-			// find out if something is mounted directly on the path
1922
-			$internalPath = $mount->getInternalPath($absolutePath);
1923
-			if ($internalPath === '') {
1924
-				// resolve the parent mount instead
1925
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1926
-			}
1927
-		}
1928
-
1929
-		return $mount;
1930
-	}
1931
-
1932
-	/**
1933
-	 * Lock the given path
1934
-	 *
1935
-	 * @param string $path the path of the file to lock, relative to the view
1936
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1937
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1938
-	 *
1939
-	 * @return bool False if the path is excluded from locking, true otherwise
1940
-	 * @throws LockedException if the path is already locked
1941
-	 */
1942
-	private function lockPath($path, $type, $lockMountPoint = false) {
1943
-		$absolutePath = $this->getAbsolutePath($path);
1944
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1945
-		if (!$this->shouldLockFile($absolutePath)) {
1946
-			return false;
1947
-		}
1948
-
1949
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1950
-		if ($mount) {
1951
-			try {
1952
-				$storage = $mount->getStorage();
1953
-				if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1954
-					$storage->acquireLock(
1955
-						$mount->getInternalPath($absolutePath),
1956
-						$type,
1957
-						$this->lockingProvider
1958
-					);
1959
-				}
1960
-			} catch (LockedException $e) {
1961
-				// rethrow with the a human-readable path
1962
-				throw new LockedException(
1963
-					$this->getPathRelativeToFiles($absolutePath),
1964
-					$e,
1965
-					$e->getExistingLock()
1966
-				);
1967
-			}
1968
-		}
1969
-
1970
-		return true;
1971
-	}
1972
-
1973
-	/**
1974
-	 * Change the lock type
1975
-	 *
1976
-	 * @param string $path the path of the file to lock, relative to the view
1977
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1978
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1979
-	 *
1980
-	 * @return bool False if the path is excluded from locking, true otherwise
1981
-	 * @throws LockedException if the path is already locked
1982
-	 */
1983
-	public function changeLock($path, $type, $lockMountPoint = false) {
1984
-		$path = Filesystem::normalizePath($path);
1985
-		$absolutePath = $this->getAbsolutePath($path);
1986
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1987
-		if (!$this->shouldLockFile($absolutePath)) {
1988
-			return false;
1989
-		}
1990
-
1991
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1992
-		if ($mount) {
1993
-			try {
1994
-				$storage = $mount->getStorage();
1995
-				if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1996
-					$storage->changeLock(
1997
-						$mount->getInternalPath($absolutePath),
1998
-						$type,
1999
-						$this->lockingProvider
2000
-					);
2001
-				}
2002
-			} catch (LockedException $e) {
2003
-				try {
2004
-					// rethrow with the a human-readable path
2005
-					throw new LockedException(
2006
-						$this->getPathRelativeToFiles($absolutePath),
2007
-						$e,
2008
-						$e->getExistingLock()
2009
-					);
2010
-				} catch (\InvalidArgumentException $ex) {
2011
-					throw new LockedException(
2012
-						$absolutePath,
2013
-						$ex,
2014
-						$e->getExistingLock()
2015
-					);
2016
-				}
2017
-			}
2018
-		}
2019
-
2020
-		return true;
2021
-	}
2022
-
2023
-	/**
2024
-	 * Unlock the given path
2025
-	 *
2026
-	 * @param string $path the path of the file to unlock, relative to the view
2027
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2028
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2029
-	 *
2030
-	 * @return bool False if the path is excluded from locking, true otherwise
2031
-	 * @throws LockedException
2032
-	 */
2033
-	private function unlockPath($path, $type, $lockMountPoint = false) {
2034
-		$absolutePath = $this->getAbsolutePath($path);
2035
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2036
-		if (!$this->shouldLockFile($absolutePath)) {
2037
-			return false;
2038
-		}
2039
-
2040
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2041
-		if ($mount) {
2042
-			$storage = $mount->getStorage();
2043
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2044
-				$storage->releaseLock(
2045
-					$mount->getInternalPath($absolutePath),
2046
-					$type,
2047
-					$this->lockingProvider
2048
-				);
2049
-			}
2050
-		}
2051
-
2052
-		return true;
2053
-	}
2054
-
2055
-	/**
2056
-	 * Lock a path and all its parents up to the root of the view
2057
-	 *
2058
-	 * @param string $path the path of the file to lock relative to the view
2059
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2060
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2061
-	 *
2062
-	 * @return bool False if the path is excluded from locking, true otherwise
2063
-	 * @throws LockedException
2064
-	 */
2065
-	public function lockFile($path, $type, $lockMountPoint = false) {
2066
-		$absolutePath = $this->getAbsolutePath($path);
2067
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2068
-		if (!$this->shouldLockFile($absolutePath)) {
2069
-			return false;
2070
-		}
2071
-
2072
-		$this->lockPath($path, $type, $lockMountPoint);
2073
-
2074
-		$parents = $this->getParents($path);
2075
-		foreach ($parents as $parent) {
2076
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2077
-		}
2078
-
2079
-		return true;
2080
-	}
2081
-
2082
-	/**
2083
-	 * Unlock a path and all its parents up to the root of the view
2084
-	 *
2085
-	 * @param string $path the path of the file to lock relative to the view
2086
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2087
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2088
-	 *
2089
-	 * @return bool False if the path is excluded from locking, true otherwise
2090
-	 * @throws LockedException
2091
-	 */
2092
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2093
-		$absolutePath = $this->getAbsolutePath($path);
2094
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2095
-		if (!$this->shouldLockFile($absolutePath)) {
2096
-			return false;
2097
-		}
2098
-
2099
-		$this->unlockPath($path, $type, $lockMountPoint);
2100
-
2101
-		$parents = $this->getParents($path);
2102
-		foreach ($parents as $parent) {
2103
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2104
-		}
2105
-
2106
-		return true;
2107
-	}
2108
-
2109
-	/**
2110
-	 * Only lock files in data/user/files/
2111
-	 *
2112
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2113
-	 * @return bool
2114
-	 */
2115
-	protected function shouldLockFile($path) {
2116
-		$path = Filesystem::normalizePath($path);
2117
-
2118
-		$pathSegments = explode('/', $path);
2119
-		if (isset($pathSegments[2])) {
2120
-			// E.g.: /username/files/path-to-file
2121
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2122
-		}
2123
-
2124
-		return strpos($path, '/appdata_') !== 0;
2125
-	}
2126
-
2127
-	/**
2128
-	 * Shortens the given absolute path to be relative to
2129
-	 * "$user/files".
2130
-	 *
2131
-	 * @param string $absolutePath absolute path which is under "files"
2132
-	 *
2133
-	 * @return string path relative to "files" with trimmed slashes or null
2134
-	 * if the path was NOT relative to files
2135
-	 *
2136
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2137
-	 * @since 8.1.0
2138
-	 */
2139
-	public function getPathRelativeToFiles($absolutePath) {
2140
-		$path = Filesystem::normalizePath($absolutePath);
2141
-		$parts = explode('/', trim($path, '/'), 3);
2142
-		// "$user", "files", "path/to/dir"
2143
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2144
-			$this->logger->error(
2145
-				'$absolutePath must be relative to "files", value is "%s"',
2146
-				[
2147
-					$absolutePath
2148
-				]
2149
-			);
2150
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2151
-		}
2152
-		if (isset($parts[2])) {
2153
-			return $parts[2];
2154
-		}
2155
-		return '';
2156
-	}
2157
-
2158
-	/**
2159
-	 * @param string $filename
2160
-	 * @return array
2161
-	 * @throws \OC\User\NoUserException
2162
-	 * @throws NotFoundException
2163
-	 */
2164
-	public function getUidAndFilename($filename) {
2165
-		$info = $this->getFileInfo($filename);
2166
-		if (!$info instanceof \OCP\Files\FileInfo) {
2167
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2168
-		}
2169
-		$uid = $info->getOwner()->getUID();
2170
-		if ($uid != \OC_User::getUser()) {
2171
-			Filesystem::initMountPoints($uid);
2172
-			$ownerView = new View('/' . $uid . '/files');
2173
-			try {
2174
-				$filename = $ownerView->getPath($info['fileid']);
2175
-			} catch (NotFoundException $e) {
2176
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2177
-			}
2178
-		}
2179
-		return [$uid, $filename];
2180
-	}
2181
-
2182
-	/**
2183
-	 * Creates parent non-existing folders
2184
-	 *
2185
-	 * @param string $filePath
2186
-	 * @return bool
2187
-	 */
2188
-	private function createParentDirectories($filePath) {
2189
-		$directoryParts = explode('/', $filePath);
2190
-		$directoryParts = array_filter($directoryParts);
2191
-		foreach ($directoryParts as $key => $part) {
2192
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2193
-			$currentPath = '/' . implode('/', $currentPathElements);
2194
-			if ($this->is_file($currentPath)) {
2195
-				return false;
2196
-			}
2197
-			if (!$this->file_exists($currentPath)) {
2198
-				$this->mkdir($currentPath);
2199
-			}
2200
-		}
2201
-
2202
-		return true;
2203
-	}
87
+    /** @var string */
88
+    private $fakeRoot = '';
89
+
90
+    /**
91
+     * @var \OCP\Lock\ILockingProvider
92
+     */
93
+    protected $lockingProvider;
94
+
95
+    private $lockingEnabled;
96
+
97
+    private $updaterEnabled = true;
98
+
99
+    /** @var \OC\User\Manager */
100
+    private $userManager;
101
+
102
+    /** @var \OCP\ILogger */
103
+    private $logger;
104
+
105
+    /**
106
+     * @param string $root
107
+     * @throws \Exception If $root contains an invalid path
108
+     */
109
+    public function __construct($root = '') {
110
+        if (is_null($root)) {
111
+            throw new \InvalidArgumentException('Root can\'t be null');
112
+        }
113
+        if (!Filesystem::isValidPath($root)) {
114
+            throw new \Exception();
115
+        }
116
+
117
+        $this->fakeRoot = $root;
118
+        $this->lockingProvider = \OC::$server->getLockingProvider();
119
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
120
+        $this->userManager = \OC::$server->getUserManager();
121
+        $this->logger = \OC::$server->getLogger();
122
+    }
123
+
124
+    public function getAbsolutePath($path = '/') {
125
+        if ($path === null) {
126
+            return null;
127
+        }
128
+        $this->assertPathLength($path);
129
+        if ($path === '') {
130
+            $path = '/';
131
+        }
132
+        if ($path[0] !== '/') {
133
+            $path = '/' . $path;
134
+        }
135
+        return $this->fakeRoot . $path;
136
+    }
137
+
138
+    /**
139
+     * change the root to a fake root
140
+     *
141
+     * @param string $fakeRoot
142
+     * @return boolean|null
143
+     */
144
+    public function chroot($fakeRoot) {
145
+        if (!$fakeRoot == '') {
146
+            if ($fakeRoot[0] !== '/') {
147
+                $fakeRoot = '/' . $fakeRoot;
148
+            }
149
+        }
150
+        $this->fakeRoot = $fakeRoot;
151
+    }
152
+
153
+    /**
154
+     * get the fake root
155
+     *
156
+     * @return string
157
+     */
158
+    public function getRoot() {
159
+        return $this->fakeRoot;
160
+    }
161
+
162
+    /**
163
+     * get path relative to the root of the view
164
+     *
165
+     * @param string $path
166
+     * @return string
167
+     */
168
+    public function getRelativePath($path) {
169
+        $this->assertPathLength($path);
170
+        if ($this->fakeRoot == '') {
171
+            return $path;
172
+        }
173
+
174
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
175
+            return '/';
176
+        }
177
+
178
+        // missing slashes can cause wrong matches!
179
+        $root = rtrim($this->fakeRoot, '/') . '/';
180
+
181
+        if (strpos($path, $root) !== 0) {
182
+            return null;
183
+        } else {
184
+            $path = substr($path, strlen($this->fakeRoot));
185
+            if (strlen($path) === 0) {
186
+                return '/';
187
+            } else {
188
+                return $path;
189
+            }
190
+        }
191
+    }
192
+
193
+    /**
194
+     * get the mountpoint of the storage object for a path
195
+     * ( note: because a storage is not always mounted inside the fakeroot, the
196
+     * returned mountpoint is relative to the absolute root of the filesystem
197
+     * and does not take the chroot into account )
198
+     *
199
+     * @param string $path
200
+     * @return string
201
+     */
202
+    public function getMountPoint($path) {
203
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
204
+    }
205
+
206
+    /**
207
+     * get the mountpoint of the storage object for a path
208
+     * ( note: because a storage is not always mounted inside the fakeroot, the
209
+     * returned mountpoint is relative to the absolute root of the filesystem
210
+     * and does not take the chroot into account )
211
+     *
212
+     * @param string $path
213
+     * @return \OCP\Files\Mount\IMountPoint
214
+     */
215
+    public function getMount($path) {
216
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
217
+    }
218
+
219
+    /**
220
+     * resolve a path to a storage and internal path
221
+     *
222
+     * @param string $path
223
+     * @return array an array consisting of the storage and the internal path
224
+     */
225
+    public function resolvePath($path) {
226
+        $a = $this->getAbsolutePath($path);
227
+        $p = Filesystem::normalizePath($a);
228
+        return Filesystem::resolvePath($p);
229
+    }
230
+
231
+    /**
232
+     * return the path to a local version of the file
233
+     * we need this because we can't know if a file is stored local or not from
234
+     * outside the filestorage and for some purposes a local file is needed
235
+     *
236
+     * @param string $path
237
+     * @return string
238
+     */
239
+    public function getLocalFile($path) {
240
+        $parent = substr($path, 0, strrpos($path, '/'));
241
+        $path = $this->getAbsolutePath($path);
242
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
243
+        if (Filesystem::isValidPath($parent) and $storage) {
244
+            return $storage->getLocalFile($internalPath);
245
+        } else {
246
+            return null;
247
+        }
248
+    }
249
+
250
+    /**
251
+     * @param string $path
252
+     * @return string
253
+     */
254
+    public function getLocalFolder($path) {
255
+        $parent = substr($path, 0, strrpos($path, '/'));
256
+        $path = $this->getAbsolutePath($path);
257
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
258
+        if (Filesystem::isValidPath($parent) and $storage) {
259
+            return $storage->getLocalFolder($internalPath);
260
+        } else {
261
+            return null;
262
+        }
263
+    }
264
+
265
+    /**
266
+     * the following functions operate with arguments and return values identical
267
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
268
+     * for \OC\Files\Storage\Storage via basicOperation().
269
+     */
270
+    public function mkdir($path) {
271
+        return $this->basicOperation('mkdir', $path, ['create', 'write']);
272
+    }
273
+
274
+    /**
275
+     * remove mount point
276
+     *
277
+     * @param IMountPoint $mount
278
+     * @param string $path relative to data/
279
+     * @return boolean
280
+     */
281
+    protected function removeMount($mount, $path) {
282
+        if ($mount instanceof MoveableMount) {
283
+            // cut of /user/files to get the relative path to data/user/files
284
+            $pathParts = explode('/', $path, 4);
285
+            $relPath = '/' . $pathParts[3];
286
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
287
+            \OC_Hook::emit(
288
+                Filesystem::CLASSNAME, "umount",
289
+                [Filesystem::signal_param_path => $relPath]
290
+            );
291
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
292
+            $result = $mount->removeMount();
293
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
294
+            if ($result) {
295
+                \OC_Hook::emit(
296
+                    Filesystem::CLASSNAME, "post_umount",
297
+                    [Filesystem::signal_param_path => $relPath]
298
+                );
299
+            }
300
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
301
+            return $result;
302
+        } else {
303
+            // do not allow deleting the storage's root / the mount point
304
+            // because for some storages it might delete the whole contents
305
+            // but isn't supposed to work that way
306
+            return false;
307
+        }
308
+    }
309
+
310
+    public function disableCacheUpdate() {
311
+        $this->updaterEnabled = false;
312
+    }
313
+
314
+    public function enableCacheUpdate() {
315
+        $this->updaterEnabled = true;
316
+    }
317
+
318
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
319
+        if ($this->updaterEnabled) {
320
+            if (is_null($time)) {
321
+                $time = time();
322
+            }
323
+            $storage->getUpdater()->update($internalPath, $time);
324
+        }
325
+    }
326
+
327
+    protected function removeUpdate(Storage $storage, $internalPath) {
328
+        if ($this->updaterEnabled) {
329
+            $storage->getUpdater()->remove($internalPath);
330
+        }
331
+    }
332
+
333
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
334
+        if ($this->updaterEnabled) {
335
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
336
+        }
337
+    }
338
+
339
+    /**
340
+     * @param string $path
341
+     * @return bool|mixed
342
+     */
343
+    public function rmdir($path) {
344
+        $absolutePath = $this->getAbsolutePath($path);
345
+        $mount = Filesystem::getMountManager()->find($absolutePath);
346
+        if ($mount->getInternalPath($absolutePath) === '') {
347
+            return $this->removeMount($mount, $absolutePath);
348
+        }
349
+        if ($this->is_dir($path)) {
350
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
351
+        } else {
352
+            $result = false;
353
+        }
354
+
355
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
356
+            $storage = $mount->getStorage();
357
+            $internalPath = $mount->getInternalPath($absolutePath);
358
+            $storage->getUpdater()->remove($internalPath);
359
+        }
360
+        return $result;
361
+    }
362
+
363
+    /**
364
+     * @param string $path
365
+     * @return resource
366
+     */
367
+    public function opendir($path) {
368
+        return $this->basicOperation('opendir', $path, ['read']);
369
+    }
370
+
371
+    /**
372
+     * @param string $path
373
+     * @return bool|mixed
374
+     */
375
+    public function is_dir($path) {
376
+        if ($path == '/') {
377
+            return true;
378
+        }
379
+        return $this->basicOperation('is_dir', $path);
380
+    }
381
+
382
+    /**
383
+     * @param string $path
384
+     * @return bool|mixed
385
+     */
386
+    public function is_file($path) {
387
+        if ($path == '/') {
388
+            return false;
389
+        }
390
+        return $this->basicOperation('is_file', $path);
391
+    }
392
+
393
+    /**
394
+     * @param string $path
395
+     * @return mixed
396
+     */
397
+    public function stat($path) {
398
+        return $this->basicOperation('stat', $path);
399
+    }
400
+
401
+    /**
402
+     * @param string $path
403
+     * @return mixed
404
+     */
405
+    public function filetype($path) {
406
+        return $this->basicOperation('filetype', $path);
407
+    }
408
+
409
+    /**
410
+     * @param string $path
411
+     * @return mixed
412
+     */
413
+    public function filesize($path) {
414
+        return $this->basicOperation('filesize', $path);
415
+    }
416
+
417
+    /**
418
+     * @param string $path
419
+     * @return bool|mixed
420
+     * @throws \OCP\Files\InvalidPathException
421
+     */
422
+    public function readfile($path) {
423
+        $this->assertPathLength($path);
424
+        if (ob_get_level()) {
425
+            ob_end_clean();
426
+        }
427
+        $handle = $this->fopen($path, 'rb');
428
+        if ($handle) {
429
+            $chunkSize = 524288; // 512 kB chunks
430
+            while (!feof($handle)) {
431
+                echo fread($handle, $chunkSize);
432
+                flush();
433
+            }
434
+            fclose($handle);
435
+            return $this->filesize($path);
436
+        }
437
+        return false;
438
+    }
439
+
440
+    /**
441
+     * @param string $path
442
+     * @param int $from
443
+     * @param int $to
444
+     * @return bool|mixed
445
+     * @throws \OCP\Files\InvalidPathException
446
+     * @throws \OCP\Files\UnseekableException
447
+     */
448
+    public function readfilePart($path, $from, $to) {
449
+        $this->assertPathLength($path);
450
+        if (ob_get_level()) {
451
+            ob_end_clean();
452
+        }
453
+        $handle = $this->fopen($path, 'rb');
454
+        if ($handle) {
455
+            $chunkSize = 524288; // 512 kB chunks
456
+            $startReading = true;
457
+
458
+            if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
459
+                // forward file handle via chunked fread because fseek seem to have failed
460
+
461
+                $end = $from + 1;
462
+                while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
463
+                    $len = $from - ftell($handle);
464
+                    if ($len > $chunkSize) {
465
+                        $len = $chunkSize;
466
+                    }
467
+                    $result = fread($handle, $len);
468
+
469
+                    if ($result === false) {
470
+                        $startReading = false;
471
+                        break;
472
+                    }
473
+                }
474
+            }
475
+
476
+            if ($startReading) {
477
+                $end = $to + 1;
478
+                while (!feof($handle) && ftell($handle) < $end) {
479
+                    $len = $end - ftell($handle);
480
+                    if ($len > $chunkSize) {
481
+                        $len = $chunkSize;
482
+                    }
483
+                    echo fread($handle, $len);
484
+                    flush();
485
+                }
486
+                return ftell($handle) - $from;
487
+            }
488
+
489
+            throw new \OCP\Files\UnseekableException('fseek error');
490
+        }
491
+        return false;
492
+    }
493
+
494
+    /**
495
+     * @param string $path
496
+     * @return mixed
497
+     */
498
+    public function isCreatable($path) {
499
+        return $this->basicOperation('isCreatable', $path);
500
+    }
501
+
502
+    /**
503
+     * @param string $path
504
+     * @return mixed
505
+     */
506
+    public function isReadable($path) {
507
+        return $this->basicOperation('isReadable', $path);
508
+    }
509
+
510
+    /**
511
+     * @param string $path
512
+     * @return mixed
513
+     */
514
+    public function isUpdatable($path) {
515
+        return $this->basicOperation('isUpdatable', $path);
516
+    }
517
+
518
+    /**
519
+     * @param string $path
520
+     * @return bool|mixed
521
+     */
522
+    public function isDeletable($path) {
523
+        $absolutePath = $this->getAbsolutePath($path);
524
+        $mount = Filesystem::getMountManager()->find($absolutePath);
525
+        if ($mount->getInternalPath($absolutePath) === '') {
526
+            return $mount instanceof MoveableMount;
527
+        }
528
+        return $this->basicOperation('isDeletable', $path);
529
+    }
530
+
531
+    /**
532
+     * @param string $path
533
+     * @return mixed
534
+     */
535
+    public function isSharable($path) {
536
+        return $this->basicOperation('isSharable', $path);
537
+    }
538
+
539
+    /**
540
+     * @param string $path
541
+     * @return bool|mixed
542
+     */
543
+    public function file_exists($path) {
544
+        if ($path == '/') {
545
+            return true;
546
+        }
547
+        return $this->basicOperation('file_exists', $path);
548
+    }
549
+
550
+    /**
551
+     * @param string $path
552
+     * @return mixed
553
+     */
554
+    public function filemtime($path) {
555
+        return $this->basicOperation('filemtime', $path);
556
+    }
557
+
558
+    /**
559
+     * @param string $path
560
+     * @param int|string $mtime
561
+     * @return bool
562
+     */
563
+    public function touch($path, $mtime = null) {
564
+        if (!is_null($mtime) and !is_numeric($mtime)) {
565
+            $mtime = strtotime($mtime);
566
+        }
567
+
568
+        $hooks = ['touch'];
569
+
570
+        if (!$this->file_exists($path)) {
571
+            $hooks[] = 'create';
572
+            $hooks[] = 'write';
573
+        }
574
+        try {
575
+            $result = $this->basicOperation('touch', $path, $hooks, $mtime);
576
+        } catch (\Exception $e) {
577
+            $this->logger->logException($e, ['level' => ILogger::INFO, 'message' => 'Error while setting modified time']);
578
+            $result = false;
579
+        }
580
+        if (!$result) {
581
+            // If create file fails because of permissions on external storage like SMB folders,
582
+            // check file exists and return false if not.
583
+            if (!$this->file_exists($path)) {
584
+                return false;
585
+            }
586
+            if (is_null($mtime)) {
587
+                $mtime = time();
588
+            }
589
+            //if native touch fails, we emulate it by changing the mtime in the cache
590
+            $this->putFileInfo($path, ['mtime' => floor($mtime)]);
591
+        }
592
+        return true;
593
+    }
594
+
595
+    /**
596
+     * @param string $path
597
+     * @return mixed
598
+     * @throws LockedException
599
+     */
600
+    public function file_get_contents($path) {
601
+        return $this->basicOperation('file_get_contents', $path, ['read']);
602
+    }
603
+
604
+    /**
605
+     * @param bool $exists
606
+     * @param string $path
607
+     * @param bool $run
608
+     */
609
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
610
+        if (!$exists) {
611
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
612
+                Filesystem::signal_param_path => $this->getHookPath($path),
613
+                Filesystem::signal_param_run => &$run,
614
+            ]);
615
+        } else {
616
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
617
+                Filesystem::signal_param_path => $this->getHookPath($path),
618
+                Filesystem::signal_param_run => &$run,
619
+            ]);
620
+        }
621
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
622
+            Filesystem::signal_param_path => $this->getHookPath($path),
623
+            Filesystem::signal_param_run => &$run,
624
+        ]);
625
+    }
626
+
627
+    /**
628
+     * @param bool $exists
629
+     * @param string $path
630
+     */
631
+    protected function emit_file_hooks_post($exists, $path) {
632
+        if (!$exists) {
633
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
634
+                Filesystem::signal_param_path => $this->getHookPath($path),
635
+            ]);
636
+        } else {
637
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
638
+                Filesystem::signal_param_path => $this->getHookPath($path),
639
+            ]);
640
+        }
641
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
642
+            Filesystem::signal_param_path => $this->getHookPath($path),
643
+        ]);
644
+    }
645
+
646
+    /**
647
+     * @param string $path
648
+     * @param string|resource $data
649
+     * @return bool|mixed
650
+     * @throws LockedException
651
+     */
652
+    public function file_put_contents($path, $data) {
653
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
654
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
655
+            if (Filesystem::isValidPath($path)
656
+                and !Filesystem::isFileBlacklisted($path)
657
+            ) {
658
+                $path = $this->getRelativePath($absolutePath);
659
+
660
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
661
+
662
+                $exists = $this->file_exists($path);
663
+                $run = true;
664
+                if ($this->shouldEmitHooks($path)) {
665
+                    $this->emit_file_hooks_pre($exists, $path, $run);
666
+                }
667
+                if (!$run) {
668
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
669
+                    return false;
670
+                }
671
+
672
+                try {
673
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
674
+                } catch (\Exception $e) {
675
+                    // Release the shared lock before throwing.
676
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
677
+                    throw $e;
678
+                }
679
+
680
+                /** @var \OC\Files\Storage\Storage $storage */
681
+                [$storage, $internalPath] = $this->resolvePath($path);
682
+                $target = $storage->fopen($internalPath, 'w');
683
+                if ($target) {
684
+                    [, $result] = \OC_Helper::streamCopy($data, $target);
685
+                    fclose($target);
686
+                    fclose($data);
687
+
688
+                    $this->writeUpdate($storage, $internalPath);
689
+
690
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
691
+
692
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
693
+                        $this->emit_file_hooks_post($exists, $path);
694
+                    }
695
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
696
+                    return $result;
697
+                } else {
698
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
699
+                    return false;
700
+                }
701
+            } else {
702
+                return false;
703
+            }
704
+        } else {
705
+            $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
706
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
707
+        }
708
+    }
709
+
710
+    /**
711
+     * @param string $path
712
+     * @return bool|mixed
713
+     */
714
+    public function unlink($path) {
715
+        if ($path === '' || $path === '/') {
716
+            // do not allow deleting the root
717
+            return false;
718
+        }
719
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
720
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
721
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
722
+        if ($mount->getInternalPath($absolutePath) === '') {
723
+            return $this->removeMount($mount, $absolutePath);
724
+        }
725
+        if ($this->is_dir($path)) {
726
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
727
+        } else {
728
+            $result = $this->basicOperation('unlink', $path, ['delete']);
729
+        }
730
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
731
+            $storage = $mount->getStorage();
732
+            $internalPath = $mount->getInternalPath($absolutePath);
733
+            $storage->getUpdater()->remove($internalPath);
734
+            return true;
735
+        } else {
736
+            return $result;
737
+        }
738
+    }
739
+
740
+    /**
741
+     * @param string $directory
742
+     * @return bool|mixed
743
+     */
744
+    public function deleteAll($directory) {
745
+        return $this->rmdir($directory);
746
+    }
747
+
748
+    /**
749
+     * Rename/move a file or folder from the source path to target path.
750
+     *
751
+     * @param string $path1 source path
752
+     * @param string $path2 target path
753
+     *
754
+     * @return bool|mixed
755
+     * @throws LockedException
756
+     */
757
+    public function rename($path1, $path2) {
758
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
759
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
760
+        $result = false;
761
+        if (
762
+            Filesystem::isValidPath($path2)
763
+            and Filesystem::isValidPath($path1)
764
+            and !Filesystem::isFileBlacklisted($path2)
765
+        ) {
766
+            $path1 = $this->getRelativePath($absolutePath1);
767
+            $path2 = $this->getRelativePath($absolutePath2);
768
+            $exists = $this->file_exists($path2);
769
+
770
+            if ($path1 == null or $path2 == null) {
771
+                return false;
772
+            }
773
+
774
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
775
+            try {
776
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
777
+
778
+                $run = true;
779
+                if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
780
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
781
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
782
+                } elseif ($this->shouldEmitHooks($path1)) {
783
+                    \OC_Hook::emit(
784
+                        Filesystem::CLASSNAME, Filesystem::signal_rename,
785
+                        [
786
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
787
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
788
+                            Filesystem::signal_param_run => &$run
789
+                        ]
790
+                    );
791
+                }
792
+                if ($run) {
793
+                    $this->verifyPath(dirname($path2), basename($path2));
794
+
795
+                    $manager = Filesystem::getMountManager();
796
+                    $mount1 = $this->getMount($path1);
797
+                    $mount2 = $this->getMount($path2);
798
+                    $storage1 = $mount1->getStorage();
799
+                    $storage2 = $mount2->getStorage();
800
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
801
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
802
+
803
+                    $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
804
+                    try {
805
+                        $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
806
+
807
+                        if ($internalPath1 === '') {
808
+                            if ($mount1 instanceof MoveableMount) {
809
+                                $sourceParentMount = $this->getMount(dirname($path1));
810
+                                if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
811
+                                    /**
812
+                                     * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
813
+                                     */
814
+                                    $sourceMountPoint = $mount1->getMountPoint();
815
+                                    $result = $mount1->moveMount($absolutePath2);
816
+                                    $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
817
+                                } else {
818
+                                    $result = false;
819
+                                }
820
+                            } else {
821
+                                $result = false;
822
+                            }
823
+                            // moving a file/folder within the same mount point
824
+                        } elseif ($storage1 === $storage2) {
825
+                            if ($storage1) {
826
+                                $result = $storage1->rename($internalPath1, $internalPath2);
827
+                            } else {
828
+                                $result = false;
829
+                            }
830
+                            // moving a file/folder between storages (from $storage1 to $storage2)
831
+                        } else {
832
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
833
+                        }
834
+
835
+                        if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
836
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
837
+                            $this->writeUpdate($storage2, $internalPath2);
838
+                        } elseif ($result) {
839
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
840
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
841
+                            }
842
+                        }
843
+                    } catch (\Exception $e) {
844
+                        throw $e;
845
+                    } finally {
846
+                        $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
847
+                        $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
848
+                    }
849
+
850
+                    if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
851
+                        if ($this->shouldEmitHooks()) {
852
+                            $this->emit_file_hooks_post($exists, $path2);
853
+                        }
854
+                    } elseif ($result) {
855
+                        if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
856
+                            \OC_Hook::emit(
857
+                                Filesystem::CLASSNAME,
858
+                                Filesystem::signal_post_rename,
859
+                                [
860
+                                    Filesystem::signal_param_oldpath => $this->getHookPath($path1),
861
+                                    Filesystem::signal_param_newpath => $this->getHookPath($path2)
862
+                                ]
863
+                            );
864
+                        }
865
+                    }
866
+                }
867
+            } catch (\Exception $e) {
868
+                throw $e;
869
+            } finally {
870
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
871
+                $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
872
+            }
873
+        }
874
+        return $result;
875
+    }
876
+
877
+    /**
878
+     * Copy a file/folder from the source path to target path
879
+     *
880
+     * @param string $path1 source path
881
+     * @param string $path2 target path
882
+     * @param bool $preserveMtime whether to preserve mtime on the copy
883
+     *
884
+     * @return bool|mixed
885
+     */
886
+    public function copy($path1, $path2, $preserveMtime = false) {
887
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
888
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
889
+        $result = false;
890
+        if (
891
+            Filesystem::isValidPath($path2)
892
+            and Filesystem::isValidPath($path1)
893
+            and !Filesystem::isFileBlacklisted($path2)
894
+        ) {
895
+            $path1 = $this->getRelativePath($absolutePath1);
896
+            $path2 = $this->getRelativePath($absolutePath2);
897
+
898
+            if ($path1 == null or $path2 == null) {
899
+                return false;
900
+            }
901
+            $run = true;
902
+
903
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
904
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
905
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
906
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
907
+
908
+            try {
909
+                $exists = $this->file_exists($path2);
910
+                if ($this->shouldEmitHooks()) {
911
+                    \OC_Hook::emit(
912
+                        Filesystem::CLASSNAME,
913
+                        Filesystem::signal_copy,
914
+                        [
915
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
916
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
917
+                            Filesystem::signal_param_run => &$run
918
+                        ]
919
+                    );
920
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
921
+                }
922
+                if ($run) {
923
+                    $mount1 = $this->getMount($path1);
924
+                    $mount2 = $this->getMount($path2);
925
+                    $storage1 = $mount1->getStorage();
926
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
927
+                    $storage2 = $mount2->getStorage();
928
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
929
+
930
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
931
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
932
+
933
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
934
+                        if ($storage1) {
935
+                            $result = $storage1->copy($internalPath1, $internalPath2);
936
+                        } else {
937
+                            $result = false;
938
+                        }
939
+                    } else {
940
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
941
+                    }
942
+
943
+                    $this->writeUpdate($storage2, $internalPath2);
944
+
945
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
946
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
947
+
948
+                    if ($this->shouldEmitHooks() && $result !== false) {
949
+                        \OC_Hook::emit(
950
+                            Filesystem::CLASSNAME,
951
+                            Filesystem::signal_post_copy,
952
+                            [
953
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
954
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
955
+                            ]
956
+                        );
957
+                        $this->emit_file_hooks_post($exists, $path2);
958
+                    }
959
+                }
960
+            } catch (\Exception $e) {
961
+                $this->unlockFile($path2, $lockTypePath2);
962
+                $this->unlockFile($path1, $lockTypePath1);
963
+                throw $e;
964
+            }
965
+
966
+            $this->unlockFile($path2, $lockTypePath2);
967
+            $this->unlockFile($path1, $lockTypePath1);
968
+        }
969
+        return $result;
970
+    }
971
+
972
+    /**
973
+     * @param string $path
974
+     * @param string $mode 'r' or 'w'
975
+     * @return resource
976
+     * @throws LockedException
977
+     */
978
+    public function fopen($path, $mode) {
979
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
980
+        $hooks = [];
981
+        switch ($mode) {
982
+            case 'r':
983
+                $hooks[] = 'read';
984
+                break;
985
+            case 'r+':
986
+            case 'w+':
987
+            case 'x+':
988
+            case 'a+':
989
+                $hooks[] = 'read';
990
+                $hooks[] = 'write';
991
+                break;
992
+            case 'w':
993
+            case 'x':
994
+            case 'a':
995
+                $hooks[] = 'write';
996
+                break;
997
+            default:
998
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, ILogger::ERROR);
999
+        }
1000
+
1001
+        if ($mode !== 'r' && $mode !== 'w') {
1002
+            \OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
1003
+        }
1004
+
1005
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
1006
+    }
1007
+
1008
+    /**
1009
+     * @param string $path
1010
+     * @return bool|string
1011
+     * @throws \OCP\Files\InvalidPathException
1012
+     */
1013
+    public function toTmpFile($path) {
1014
+        $this->assertPathLength($path);
1015
+        if (Filesystem::isValidPath($path)) {
1016
+            $source = $this->fopen($path, 'r');
1017
+            if ($source) {
1018
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
1019
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1020
+                file_put_contents($tmpFile, $source);
1021
+                return $tmpFile;
1022
+            } else {
1023
+                return false;
1024
+            }
1025
+        } else {
1026
+            return false;
1027
+        }
1028
+    }
1029
+
1030
+    /**
1031
+     * @param string $tmpFile
1032
+     * @param string $path
1033
+     * @return bool|mixed
1034
+     * @throws \OCP\Files\InvalidPathException
1035
+     */
1036
+    public function fromTmpFile($tmpFile, $path) {
1037
+        $this->assertPathLength($path);
1038
+        if (Filesystem::isValidPath($path)) {
1039
+
1040
+            // Get directory that the file is going into
1041
+            $filePath = dirname($path);
1042
+
1043
+            // Create the directories if any
1044
+            if (!$this->file_exists($filePath)) {
1045
+                $result = $this->createParentDirectories($filePath);
1046
+                if ($result === false) {
1047
+                    return false;
1048
+                }
1049
+            }
1050
+
1051
+            $source = fopen($tmpFile, 'r');
1052
+            if ($source) {
1053
+                $result = $this->file_put_contents($path, $source);
1054
+                // $this->file_put_contents() might have already closed
1055
+                // the resource, so we check it, before trying to close it
1056
+                // to avoid messages in the error log.
1057
+                if (is_resource($source)) {
1058
+                    fclose($source);
1059
+                }
1060
+                unlink($tmpFile);
1061
+                return $result;
1062
+            } else {
1063
+                return false;
1064
+            }
1065
+        } else {
1066
+            return false;
1067
+        }
1068
+    }
1069
+
1070
+
1071
+    /**
1072
+     * @param string $path
1073
+     * @return mixed
1074
+     * @throws \OCP\Files\InvalidPathException
1075
+     */
1076
+    public function getMimeType($path) {
1077
+        $this->assertPathLength($path);
1078
+        return $this->basicOperation('getMimeType', $path);
1079
+    }
1080
+
1081
+    /**
1082
+     * @param string $type
1083
+     * @param string $path
1084
+     * @param bool $raw
1085
+     * @return bool|string
1086
+     */
1087
+    public function hash($type, $path, $raw = false) {
1088
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1089
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1090
+        if (Filesystem::isValidPath($path)) {
1091
+            $path = $this->getRelativePath($absolutePath);
1092
+            if ($path == null) {
1093
+                return false;
1094
+            }
1095
+            if ($this->shouldEmitHooks($path)) {
1096
+                \OC_Hook::emit(
1097
+                    Filesystem::CLASSNAME,
1098
+                    Filesystem::signal_read,
1099
+                    [Filesystem::signal_param_path => $this->getHookPath($path)]
1100
+                );
1101
+            }
1102
+            [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1103
+            if ($storage) {
1104
+                return $storage->hash($type, $internalPath, $raw);
1105
+            }
1106
+        }
1107
+        return false;
1108
+    }
1109
+
1110
+    /**
1111
+     * @param string $path
1112
+     * @return mixed
1113
+     * @throws \OCP\Files\InvalidPathException
1114
+     */
1115
+    public function free_space($path = '/') {
1116
+        $this->assertPathLength($path);
1117
+        $result = $this->basicOperation('free_space', $path);
1118
+        if ($result === null) {
1119
+            throw new InvalidPathException();
1120
+        }
1121
+        return $result;
1122
+    }
1123
+
1124
+    /**
1125
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1126
+     *
1127
+     * @param string $operation
1128
+     * @param string $path
1129
+     * @param array $hooks (optional)
1130
+     * @param mixed $extraParam (optional)
1131
+     * @return mixed
1132
+     * @throws LockedException
1133
+     *
1134
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1135
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1136
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1137
+     */
1138
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1139
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1140
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1141
+        if (Filesystem::isValidPath($path)
1142
+            and !Filesystem::isFileBlacklisted($path)
1143
+        ) {
1144
+            $path = $this->getRelativePath($absolutePath);
1145
+            if ($path == null) {
1146
+                return false;
1147
+            }
1148
+
1149
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1150
+                // always a shared lock during pre-hooks so the hook can read the file
1151
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1152
+            }
1153
+
1154
+            $run = $this->runHooks($hooks, $path);
1155
+            /** @var \OC\Files\Storage\Storage $storage */
1156
+            [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1157
+            if ($run and $storage) {
1158
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1159
+                    try {
1160
+                        $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1161
+                    } catch (LockedException $e) {
1162
+                        // release the shared lock we acquired before quiting
1163
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1164
+                        throw $e;
1165
+                    }
1166
+                }
1167
+                try {
1168
+                    if (!is_null($extraParam)) {
1169
+                        $result = $storage->$operation($internalPath, $extraParam);
1170
+                    } else {
1171
+                        $result = $storage->$operation($internalPath);
1172
+                    }
1173
+                } catch (\Exception $e) {
1174
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1175
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1176
+                    } elseif (in_array('read', $hooks)) {
1177
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1178
+                    }
1179
+                    throw $e;
1180
+                }
1181
+
1182
+                if ($result && in_array('delete', $hooks) and $result) {
1183
+                    $this->removeUpdate($storage, $internalPath);
1184
+                }
1185
+                if ($result && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
1186
+                    $this->writeUpdate($storage, $internalPath);
1187
+                }
1188
+                if ($result && in_array('touch', $hooks)) {
1189
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1190
+                }
1191
+
1192
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1193
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1194
+                }
1195
+
1196
+                $unlockLater = false;
1197
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1198
+                    $unlockLater = true;
1199
+                    // make sure our unlocking callback will still be called if connection is aborted
1200
+                    ignore_user_abort(true);
1201
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1202
+                        if (in_array('write', $hooks)) {
1203
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1204
+                        } elseif (in_array('read', $hooks)) {
1205
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1206
+                        }
1207
+                    });
1208
+                }
1209
+
1210
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1211
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1212
+                        $this->runHooks($hooks, $path, true);
1213
+                    }
1214
+                }
1215
+
1216
+                if (!$unlockLater
1217
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1218
+                ) {
1219
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1220
+                }
1221
+                return $result;
1222
+            } else {
1223
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1224
+            }
1225
+        }
1226
+        return null;
1227
+    }
1228
+
1229
+    /**
1230
+     * get the path relative to the default root for hook usage
1231
+     *
1232
+     * @param string $path
1233
+     * @return string
1234
+     */
1235
+    private function getHookPath($path) {
1236
+        if (!Filesystem::getView()) {
1237
+            return $path;
1238
+        }
1239
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1240
+    }
1241
+
1242
+    private function shouldEmitHooks($path = '') {
1243
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1244
+            return false;
1245
+        }
1246
+        if (!Filesystem::$loaded) {
1247
+            return false;
1248
+        }
1249
+        $defaultRoot = Filesystem::getRoot();
1250
+        if ($defaultRoot === null) {
1251
+            return false;
1252
+        }
1253
+        if ($this->fakeRoot === $defaultRoot) {
1254
+            return true;
1255
+        }
1256
+        $fullPath = $this->getAbsolutePath($path);
1257
+
1258
+        if ($fullPath === $defaultRoot) {
1259
+            return true;
1260
+        }
1261
+
1262
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1263
+    }
1264
+
1265
+    /**
1266
+     * @param string[] $hooks
1267
+     * @param string $path
1268
+     * @param bool $post
1269
+     * @return bool
1270
+     */
1271
+    private function runHooks($hooks, $path, $post = false) {
1272
+        $relativePath = $path;
1273
+        $path = $this->getHookPath($path);
1274
+        $prefix = $post ? 'post_' : '';
1275
+        $run = true;
1276
+        if ($this->shouldEmitHooks($relativePath)) {
1277
+            foreach ($hooks as $hook) {
1278
+                if ($hook != 'read') {
1279
+                    \OC_Hook::emit(
1280
+                        Filesystem::CLASSNAME,
1281
+                        $prefix . $hook,
1282
+                        [
1283
+                            Filesystem::signal_param_run => &$run,
1284
+                            Filesystem::signal_param_path => $path
1285
+                        ]
1286
+                    );
1287
+                } elseif (!$post) {
1288
+                    \OC_Hook::emit(
1289
+                        Filesystem::CLASSNAME,
1290
+                        $prefix . $hook,
1291
+                        [
1292
+                            Filesystem::signal_param_path => $path
1293
+                        ]
1294
+                    );
1295
+                }
1296
+            }
1297
+        }
1298
+        return $run;
1299
+    }
1300
+
1301
+    /**
1302
+     * check if a file or folder has been updated since $time
1303
+     *
1304
+     * @param string $path
1305
+     * @param int $time
1306
+     * @return bool
1307
+     */
1308
+    public function hasUpdated($path, $time) {
1309
+        return $this->basicOperation('hasUpdated', $path, [], $time);
1310
+    }
1311
+
1312
+    /**
1313
+     * @param string $ownerId
1314
+     * @return \OC\User\User
1315
+     */
1316
+    private function getUserObjectForOwner($ownerId) {
1317
+        $owner = $this->userManager->get($ownerId);
1318
+        if ($owner instanceof IUser) {
1319
+            return $owner;
1320
+        } else {
1321
+            return new User($ownerId, null, \OC::$server->getEventDispatcher());
1322
+        }
1323
+    }
1324
+
1325
+    /**
1326
+     * Get file info from cache
1327
+     *
1328
+     * If the file is not in cached it will be scanned
1329
+     * If the file has changed on storage the cache will be updated
1330
+     *
1331
+     * @param \OC\Files\Storage\Storage $storage
1332
+     * @param string $internalPath
1333
+     * @param string $relativePath
1334
+     * @return ICacheEntry|bool
1335
+     */
1336
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1337
+        $cache = $storage->getCache($internalPath);
1338
+        $data = $cache->get($internalPath);
1339
+        $watcher = $storage->getWatcher($internalPath);
1340
+
1341
+        try {
1342
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1343
+            if (!$data || (isset($data['size']) && $data['size'] === -1)) {
1344
+                if (!$storage->file_exists($internalPath)) {
1345
+                    return false;
1346
+                }
1347
+                // don't need to get a lock here since the scanner does it's own locking
1348
+                $scanner = $storage->getScanner($internalPath);
1349
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1350
+                $data = $cache->get($internalPath);
1351
+            } elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1352
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1353
+                $watcher->update($internalPath, $data);
1354
+                $storage->getPropagator()->propagateChange($internalPath, time());
1355
+                $data = $cache->get($internalPath);
1356
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1357
+            }
1358
+        } catch (LockedException $e) {
1359
+            // if the file is locked we just use the old cache info
1360
+        }
1361
+
1362
+        return $data;
1363
+    }
1364
+
1365
+    /**
1366
+     * get the filesystem info
1367
+     *
1368
+     * @param string $path
1369
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1370
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1371
+     * defaults to true
1372
+     * @return \OC\Files\FileInfo|false False if file does not exist
1373
+     */
1374
+    public function getFileInfo($path, $includeMountPoints = true) {
1375
+        $this->assertPathLength($path);
1376
+        if (!Filesystem::isValidPath($path)) {
1377
+            return false;
1378
+        }
1379
+        if (Cache\Scanner::isPartialFile($path)) {
1380
+            return $this->getPartFileInfo($path);
1381
+        }
1382
+        $relativePath = $path;
1383
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1384
+
1385
+        $mount = Filesystem::getMountManager()->find($path);
1386
+        $storage = $mount->getStorage();
1387
+        $internalPath = $mount->getInternalPath($path);
1388
+        if ($storage) {
1389
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1390
+
1391
+            if (!$data instanceof ICacheEntry) {
1392
+                return false;
1393
+            }
1394
+
1395
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1396
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1397
+            }
1398
+            $ownerId = $storage->getOwner($internalPath);
1399
+            $owner = null;
1400
+            if ($ownerId !== null && $ownerId !== false) {
1401
+                // ownerId might be null if files are accessed with an access token without file system access
1402
+                $owner = $this->getUserObjectForOwner($ownerId);
1403
+            }
1404
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1405
+
1406
+            if (isset($data['fileid'])) {
1407
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1408
+                    //add the sizes of other mount points to the folder
1409
+                    $extOnly = ($includeMountPoints === 'ext');
1410
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1411
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1412
+                        $subStorage = $mount->getStorage();
1413
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1414
+                    }));
1415
+                }
1416
+            }
1417
+
1418
+            return $info;
1419
+        } else {
1420
+            \OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
1421
+        }
1422
+
1423
+        return false;
1424
+    }
1425
+
1426
+    /**
1427
+     * get the content of a directory
1428
+     *
1429
+     * @param string $directory path under datadirectory
1430
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1431
+     * @return FileInfo[]
1432
+     */
1433
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1434
+        $this->assertPathLength($directory);
1435
+        if (!Filesystem::isValidPath($directory)) {
1436
+            return [];
1437
+        }
1438
+        $path = $this->getAbsolutePath($directory);
1439
+        $path = Filesystem::normalizePath($path);
1440
+        $mount = $this->getMount($directory);
1441
+        if (!$mount) {
1442
+            return [];
1443
+        }
1444
+        $storage = $mount->getStorage();
1445
+        $internalPath = $mount->getInternalPath($path);
1446
+        if ($storage) {
1447
+            $cache = $storage->getCache($internalPath);
1448
+            $user = \OC_User::getUser();
1449
+
1450
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1451
+
1452
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1453
+                return [];
1454
+            }
1455
+
1456
+            $folderId = $data['fileid'];
1457
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1458
+
1459
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1460
+
1461
+            $fileNames = array_map(function (ICacheEntry $content) {
1462
+                return $content->getName();
1463
+            }, $contents);
1464
+            /**
1465
+             * @var \OC\Files\FileInfo[] $fileInfos
1466
+             */
1467
+            $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1468
+                if ($sharingDisabled) {
1469
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1470
+                }
1471
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1472
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1473
+            }, $contents);
1474
+            $files = array_combine($fileNames, $fileInfos);
1475
+
1476
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1477
+            $mounts = Filesystem::getMountManager()->findIn($path);
1478
+            $dirLength = strlen($path);
1479
+            foreach ($mounts as $mount) {
1480
+                $mountPoint = $mount->getMountPoint();
1481
+                $subStorage = $mount->getStorage();
1482
+                if ($subStorage) {
1483
+                    $subCache = $subStorage->getCache('');
1484
+
1485
+                    $rootEntry = $subCache->get('');
1486
+                    if (!$rootEntry) {
1487
+                        $subScanner = $subStorage->getScanner();
1488
+                        try {
1489
+                            $subScanner->scanFile('');
1490
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1491
+                            continue;
1492
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1493
+                            continue;
1494
+                        } catch (\Exception $e) {
1495
+                            // sometimes when the storage is not available it can be any exception
1496
+                            \OC::$server->getLogger()->logException($e, [
1497
+                                'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
1498
+                                'level' => ILogger::ERROR,
1499
+                                'app' => 'lib',
1500
+                            ]);
1501
+                            continue;
1502
+                        }
1503
+                        $rootEntry = $subCache->get('');
1504
+                    }
1505
+
1506
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1507
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1508
+                        if ($pos = strpos($relativePath, '/')) {
1509
+                            //mountpoint inside subfolder add size to the correct folder
1510
+                            $entryName = substr($relativePath, 0, $pos);
1511
+                            foreach ($files as &$entry) {
1512
+                                if ($entry->getName() === $entryName) {
1513
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1514
+                                }
1515
+                            }
1516
+                        } else { //mountpoint in this folder, add an entry for it
1517
+                            $rootEntry['name'] = $relativePath;
1518
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1519
+                            $permissions = $rootEntry['permissions'];
1520
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1521
+                            // for shared files/folders we use the permissions given by the owner
1522
+                            if ($mount instanceof MoveableMount) {
1523
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1524
+                            } else {
1525
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1526
+                            }
1527
+
1528
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1529
+
1530
+                            // if sharing was disabled for the user we remove the share permissions
1531
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1532
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1533
+                            }
1534
+
1535
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1536
+                            $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1537
+                        }
1538
+                    }
1539
+                }
1540
+            }
1541
+
1542
+            if ($mimetype_filter) {
1543
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1544
+                    if (strpos($mimetype_filter, '/')) {
1545
+                        return $file->getMimetype() === $mimetype_filter;
1546
+                    } else {
1547
+                        return $file->getMimePart() === $mimetype_filter;
1548
+                    }
1549
+                });
1550
+            }
1551
+
1552
+            return array_values($files);
1553
+        } else {
1554
+            return [];
1555
+        }
1556
+    }
1557
+
1558
+    /**
1559
+     * change file metadata
1560
+     *
1561
+     * @param string $path
1562
+     * @param array|\OCP\Files\FileInfo $data
1563
+     * @return int
1564
+     *
1565
+     * returns the fileid of the updated file
1566
+     */
1567
+    public function putFileInfo($path, $data) {
1568
+        $this->assertPathLength($path);
1569
+        if ($data instanceof FileInfo) {
1570
+            $data = $data->getData();
1571
+        }
1572
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1573
+        /**
1574
+         * @var \OC\Files\Storage\Storage $storage
1575
+         * @var string $internalPath
1576
+         */
1577
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
1578
+        if ($storage) {
1579
+            $cache = $storage->getCache($path);
1580
+
1581
+            if (!$cache->inCache($internalPath)) {
1582
+                $scanner = $storage->getScanner($internalPath);
1583
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1584
+            }
1585
+
1586
+            return $cache->put($internalPath, $data);
1587
+        } else {
1588
+            return -1;
1589
+        }
1590
+    }
1591
+
1592
+    /**
1593
+     * search for files with the name matching $query
1594
+     *
1595
+     * @param string $query
1596
+     * @return FileInfo[]
1597
+     */
1598
+    public function search($query) {
1599
+        return $this->searchCommon('search', ['%' . $query . '%']);
1600
+    }
1601
+
1602
+    /**
1603
+     * search for files with the name matching $query
1604
+     *
1605
+     * @param string $query
1606
+     * @return FileInfo[]
1607
+     */
1608
+    public function searchRaw($query) {
1609
+        return $this->searchCommon('search', [$query]);
1610
+    }
1611
+
1612
+    /**
1613
+     * search for files by mimetype
1614
+     *
1615
+     * @param string $mimetype
1616
+     * @return FileInfo[]
1617
+     */
1618
+    public function searchByMime($mimetype) {
1619
+        return $this->searchCommon('searchByMime', [$mimetype]);
1620
+    }
1621
+
1622
+    /**
1623
+     * search for files by tag
1624
+     *
1625
+     * @param string|int $tag name or tag id
1626
+     * @param string $userId owner of the tags
1627
+     * @return FileInfo[]
1628
+     */
1629
+    public function searchByTag($tag, $userId) {
1630
+        return $this->searchCommon('searchByTag', [$tag, $userId]);
1631
+    }
1632
+
1633
+    /**
1634
+     * @param string $method cache method
1635
+     * @param array $args
1636
+     * @return FileInfo[]
1637
+     */
1638
+    private function searchCommon($method, $args) {
1639
+        $files = [];
1640
+        $rootLength = strlen($this->fakeRoot);
1641
+
1642
+        $mount = $this->getMount('');
1643
+        $mountPoint = $mount->getMountPoint();
1644
+        $storage = $mount->getStorage();
1645
+        $userManager = \OC::$server->getUserManager();
1646
+        if ($storage) {
1647
+            $cache = $storage->getCache('');
1648
+
1649
+            $results = call_user_func_array([$cache, $method], $args);
1650
+            foreach ($results as $result) {
1651
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1652
+                    $internalPath = $result['path'];
1653
+                    $path = $mountPoint . $result['path'];
1654
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1655
+                    $owner = $userManager->get($storage->getOwner($internalPath));
1656
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1657
+                }
1658
+            }
1659
+
1660
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1661
+            foreach ($mounts as $mount) {
1662
+                $mountPoint = $mount->getMountPoint();
1663
+                $storage = $mount->getStorage();
1664
+                if ($storage) {
1665
+                    $cache = $storage->getCache('');
1666
+
1667
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1668
+                    $results = call_user_func_array([$cache, $method], $args);
1669
+                    if ($results) {
1670
+                        foreach ($results as $result) {
1671
+                            $internalPath = $result['path'];
1672
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1673
+                            $path = rtrim($mountPoint . $internalPath, '/');
1674
+                            $owner = $userManager->get($storage->getOwner($internalPath));
1675
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1676
+                        }
1677
+                    }
1678
+                }
1679
+            }
1680
+        }
1681
+        return $files;
1682
+    }
1683
+
1684
+    /**
1685
+     * Get the owner for a file or folder
1686
+     *
1687
+     * @param string $path
1688
+     * @return string the user id of the owner
1689
+     * @throws NotFoundException
1690
+     */
1691
+    public function getOwner($path) {
1692
+        $info = $this->getFileInfo($path);
1693
+        if (!$info) {
1694
+            throw new NotFoundException($path . ' not found while trying to get owner');
1695
+        }
1696
+
1697
+        if ($info->getOwner() === null) {
1698
+            throw new NotFoundException($path . ' has no owner');
1699
+        }
1700
+
1701
+        return $info->getOwner()->getUID();
1702
+    }
1703
+
1704
+    /**
1705
+     * get the ETag for a file or folder
1706
+     *
1707
+     * @param string $path
1708
+     * @return string
1709
+     */
1710
+    public function getETag($path) {
1711
+        /**
1712
+         * @var Storage\Storage $storage
1713
+         * @var string $internalPath
1714
+         */
1715
+        [$storage, $internalPath] = $this->resolvePath($path);
1716
+        if ($storage) {
1717
+            return $storage->getETag($internalPath);
1718
+        } else {
1719
+            return null;
1720
+        }
1721
+    }
1722
+
1723
+    /**
1724
+     * Get the path of a file by id, relative to the view
1725
+     *
1726
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1727
+     *
1728
+     * @param int $id
1729
+     * @param int|null $storageId
1730
+     * @return string
1731
+     * @throws NotFoundException
1732
+     */
1733
+    public function getPath($id, int $storageId = null) {
1734
+        $id = (int)$id;
1735
+        $manager = Filesystem::getMountManager();
1736
+        $mounts = $manager->findIn($this->fakeRoot);
1737
+        $mounts[] = $manager->find($this->fakeRoot);
1738
+        $mounts = array_filter($mounts);
1739
+        // reverse the array, so we start with the storage this view is in
1740
+        // which is the most likely to contain the file we're looking for
1741
+        $mounts = array_reverse($mounts);
1742
+
1743
+        // put non-shared mounts in front of the shared mount
1744
+        // this prevents unneeded recursion into shares
1745
+        usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1746
+            return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1747
+        });
1748
+
1749
+        if (!is_null($storageId)) {
1750
+            $mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1751
+                return $mount->getNumericStorageId() === $storageId;
1752
+            });
1753
+        }
1754
+
1755
+        foreach ($mounts as $mount) {
1756
+            /**
1757
+             * @var \OC\Files\Mount\MountPoint $mount
1758
+             */
1759
+            if ($mount->getStorage()) {
1760
+                $cache = $mount->getStorage()->getCache();
1761
+                $internalPath = $cache->getPathById($id);
1762
+                if (is_string($internalPath)) {
1763
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1764
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1765
+                        return $path;
1766
+                    }
1767
+                }
1768
+            }
1769
+        }
1770
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1771
+    }
1772
+
1773
+    /**
1774
+     * @param string $path
1775
+     * @throws InvalidPathException
1776
+     */
1777
+    private function assertPathLength($path) {
1778
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1779
+        // Check for the string length - performed using isset() instead of strlen()
1780
+        // because isset() is about 5x-40x faster.
1781
+        if (isset($path[$maxLen])) {
1782
+            $pathLen = strlen($path);
1783
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1784
+        }
1785
+    }
1786
+
1787
+    /**
1788
+     * check if it is allowed to move a mount point to a given target.
1789
+     * It is not allowed to move a mount point into a different mount point or
1790
+     * into an already shared folder
1791
+     *
1792
+     * @param IStorage $targetStorage
1793
+     * @param string $targetInternalPath
1794
+     * @return boolean
1795
+     */
1796
+    private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1797
+
1798
+        // note: cannot use the view because the target is already locked
1799
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1800
+        if ($fileId === -1) {
1801
+            // target might not exist, need to check parent instead
1802
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1803
+        }
1804
+
1805
+        // check if any of the parents were shared by the current owner (include collections)
1806
+        $shares = \OCP\Share::getItemShared(
1807
+            'folder',
1808
+            $fileId,
1809
+            \OCP\Share::FORMAT_NONE,
1810
+            null,
1811
+            true
1812
+        );
1813
+
1814
+        if (count($shares) > 0) {
1815
+            \OCP\Util::writeLog('files',
1816
+                'It is not allowed to move one mount point into a shared folder',
1817
+                ILogger::DEBUG);
1818
+            return false;
1819
+        }
1820
+
1821
+        return true;
1822
+    }
1823
+
1824
+    /**
1825
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1826
+     *
1827
+     * @param string $path
1828
+     * @return \OCP\Files\FileInfo
1829
+     */
1830
+    private function getPartFileInfo($path) {
1831
+        $mount = $this->getMount($path);
1832
+        $storage = $mount->getStorage();
1833
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1834
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1835
+        return new FileInfo(
1836
+            $this->getAbsolutePath($path),
1837
+            $storage,
1838
+            $internalPath,
1839
+            [
1840
+                'fileid' => null,
1841
+                'mimetype' => $storage->getMimeType($internalPath),
1842
+                'name' => basename($path),
1843
+                'etag' => null,
1844
+                'size' => $storage->filesize($internalPath),
1845
+                'mtime' => $storage->filemtime($internalPath),
1846
+                'encrypted' => false,
1847
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1848
+            ],
1849
+            $mount,
1850
+            $owner
1851
+        );
1852
+    }
1853
+
1854
+    /**
1855
+     * @param string $path
1856
+     * @param string $fileName
1857
+     * @throws InvalidPathException
1858
+     */
1859
+    public function verifyPath($path, $fileName) {
1860
+        try {
1861
+            /** @type \OCP\Files\Storage $storage */
1862
+            [$storage, $internalPath] = $this->resolvePath($path);
1863
+            $storage->verifyPath($internalPath, $fileName);
1864
+        } catch (ReservedWordException $ex) {
1865
+            $l = \OC::$server->getL10N('lib');
1866
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1867
+        } catch (InvalidCharacterInPathException $ex) {
1868
+            $l = \OC::$server->getL10N('lib');
1869
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1870
+        } catch (FileNameTooLongException $ex) {
1871
+            $l = \OC::$server->getL10N('lib');
1872
+            throw new InvalidPathException($l->t('File name is too long'));
1873
+        } catch (InvalidDirectoryException $ex) {
1874
+            $l = \OC::$server->getL10N('lib');
1875
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1876
+        } catch (EmptyFileNameException $ex) {
1877
+            $l = \OC::$server->getL10N('lib');
1878
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1879
+        }
1880
+    }
1881
+
1882
+    /**
1883
+     * get all parent folders of $path
1884
+     *
1885
+     * @param string $path
1886
+     * @return string[]
1887
+     */
1888
+    private function getParents($path) {
1889
+        $path = trim($path, '/');
1890
+        if (!$path) {
1891
+            return [];
1892
+        }
1893
+
1894
+        $parts = explode('/', $path);
1895
+
1896
+        // remove the single file
1897
+        array_pop($parts);
1898
+        $result = ['/'];
1899
+        $resultPath = '';
1900
+        foreach ($parts as $part) {
1901
+            if ($part) {
1902
+                $resultPath .= '/' . $part;
1903
+                $result[] = $resultPath;
1904
+            }
1905
+        }
1906
+        return $result;
1907
+    }
1908
+
1909
+    /**
1910
+     * Returns the mount point for which to lock
1911
+     *
1912
+     * @param string $absolutePath absolute path
1913
+     * @param bool $useParentMount true to return parent mount instead of whatever
1914
+     * is mounted directly on the given path, false otherwise
1915
+     * @return IMountPoint mount point for which to apply locks
1916
+     */
1917
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1918
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1919
+
1920
+        if ($useParentMount) {
1921
+            // find out if something is mounted directly on the path
1922
+            $internalPath = $mount->getInternalPath($absolutePath);
1923
+            if ($internalPath === '') {
1924
+                // resolve the parent mount instead
1925
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1926
+            }
1927
+        }
1928
+
1929
+        return $mount;
1930
+    }
1931
+
1932
+    /**
1933
+     * Lock the given path
1934
+     *
1935
+     * @param string $path the path of the file to lock, relative to the view
1936
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1937
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1938
+     *
1939
+     * @return bool False if the path is excluded from locking, true otherwise
1940
+     * @throws LockedException if the path is already locked
1941
+     */
1942
+    private function lockPath($path, $type, $lockMountPoint = false) {
1943
+        $absolutePath = $this->getAbsolutePath($path);
1944
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1945
+        if (!$this->shouldLockFile($absolutePath)) {
1946
+            return false;
1947
+        }
1948
+
1949
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1950
+        if ($mount) {
1951
+            try {
1952
+                $storage = $mount->getStorage();
1953
+                if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1954
+                    $storage->acquireLock(
1955
+                        $mount->getInternalPath($absolutePath),
1956
+                        $type,
1957
+                        $this->lockingProvider
1958
+                    );
1959
+                }
1960
+            } catch (LockedException $e) {
1961
+                // rethrow with the a human-readable path
1962
+                throw new LockedException(
1963
+                    $this->getPathRelativeToFiles($absolutePath),
1964
+                    $e,
1965
+                    $e->getExistingLock()
1966
+                );
1967
+            }
1968
+        }
1969
+
1970
+        return true;
1971
+    }
1972
+
1973
+    /**
1974
+     * Change the lock type
1975
+     *
1976
+     * @param string $path the path of the file to lock, relative to the view
1977
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1978
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1979
+     *
1980
+     * @return bool False if the path is excluded from locking, true otherwise
1981
+     * @throws LockedException if the path is already locked
1982
+     */
1983
+    public function changeLock($path, $type, $lockMountPoint = false) {
1984
+        $path = Filesystem::normalizePath($path);
1985
+        $absolutePath = $this->getAbsolutePath($path);
1986
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1987
+        if (!$this->shouldLockFile($absolutePath)) {
1988
+            return false;
1989
+        }
1990
+
1991
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1992
+        if ($mount) {
1993
+            try {
1994
+                $storage = $mount->getStorage();
1995
+                if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1996
+                    $storage->changeLock(
1997
+                        $mount->getInternalPath($absolutePath),
1998
+                        $type,
1999
+                        $this->lockingProvider
2000
+                    );
2001
+                }
2002
+            } catch (LockedException $e) {
2003
+                try {
2004
+                    // rethrow with the a human-readable path
2005
+                    throw new LockedException(
2006
+                        $this->getPathRelativeToFiles($absolutePath),
2007
+                        $e,
2008
+                        $e->getExistingLock()
2009
+                    );
2010
+                } catch (\InvalidArgumentException $ex) {
2011
+                    throw new LockedException(
2012
+                        $absolutePath,
2013
+                        $ex,
2014
+                        $e->getExistingLock()
2015
+                    );
2016
+                }
2017
+            }
2018
+        }
2019
+
2020
+        return true;
2021
+    }
2022
+
2023
+    /**
2024
+     * Unlock the given path
2025
+     *
2026
+     * @param string $path the path of the file to unlock, relative to the view
2027
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2028
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2029
+     *
2030
+     * @return bool False if the path is excluded from locking, true otherwise
2031
+     * @throws LockedException
2032
+     */
2033
+    private function unlockPath($path, $type, $lockMountPoint = false) {
2034
+        $absolutePath = $this->getAbsolutePath($path);
2035
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2036
+        if (!$this->shouldLockFile($absolutePath)) {
2037
+            return false;
2038
+        }
2039
+
2040
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2041
+        if ($mount) {
2042
+            $storage = $mount->getStorage();
2043
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2044
+                $storage->releaseLock(
2045
+                    $mount->getInternalPath($absolutePath),
2046
+                    $type,
2047
+                    $this->lockingProvider
2048
+                );
2049
+            }
2050
+        }
2051
+
2052
+        return true;
2053
+    }
2054
+
2055
+    /**
2056
+     * Lock a path and all its parents up to the root of the view
2057
+     *
2058
+     * @param string $path the path of the file to lock relative to the view
2059
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2060
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2061
+     *
2062
+     * @return bool False if the path is excluded from locking, true otherwise
2063
+     * @throws LockedException
2064
+     */
2065
+    public function lockFile($path, $type, $lockMountPoint = false) {
2066
+        $absolutePath = $this->getAbsolutePath($path);
2067
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2068
+        if (!$this->shouldLockFile($absolutePath)) {
2069
+            return false;
2070
+        }
2071
+
2072
+        $this->lockPath($path, $type, $lockMountPoint);
2073
+
2074
+        $parents = $this->getParents($path);
2075
+        foreach ($parents as $parent) {
2076
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2077
+        }
2078
+
2079
+        return true;
2080
+    }
2081
+
2082
+    /**
2083
+     * Unlock a path and all its parents up to the root of the view
2084
+     *
2085
+     * @param string $path the path of the file to lock relative to the view
2086
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2087
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2088
+     *
2089
+     * @return bool False if the path is excluded from locking, true otherwise
2090
+     * @throws LockedException
2091
+     */
2092
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2093
+        $absolutePath = $this->getAbsolutePath($path);
2094
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2095
+        if (!$this->shouldLockFile($absolutePath)) {
2096
+            return false;
2097
+        }
2098
+
2099
+        $this->unlockPath($path, $type, $lockMountPoint);
2100
+
2101
+        $parents = $this->getParents($path);
2102
+        foreach ($parents as $parent) {
2103
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2104
+        }
2105
+
2106
+        return true;
2107
+    }
2108
+
2109
+    /**
2110
+     * Only lock files in data/user/files/
2111
+     *
2112
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2113
+     * @return bool
2114
+     */
2115
+    protected function shouldLockFile($path) {
2116
+        $path = Filesystem::normalizePath($path);
2117
+
2118
+        $pathSegments = explode('/', $path);
2119
+        if (isset($pathSegments[2])) {
2120
+            // E.g.: /username/files/path-to-file
2121
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2122
+        }
2123
+
2124
+        return strpos($path, '/appdata_') !== 0;
2125
+    }
2126
+
2127
+    /**
2128
+     * Shortens the given absolute path to be relative to
2129
+     * "$user/files".
2130
+     *
2131
+     * @param string $absolutePath absolute path which is under "files"
2132
+     *
2133
+     * @return string path relative to "files" with trimmed slashes or null
2134
+     * if the path was NOT relative to files
2135
+     *
2136
+     * @throws \InvalidArgumentException if the given path was not under "files"
2137
+     * @since 8.1.0
2138
+     */
2139
+    public function getPathRelativeToFiles($absolutePath) {
2140
+        $path = Filesystem::normalizePath($absolutePath);
2141
+        $parts = explode('/', trim($path, '/'), 3);
2142
+        // "$user", "files", "path/to/dir"
2143
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2144
+            $this->logger->error(
2145
+                '$absolutePath must be relative to "files", value is "%s"',
2146
+                [
2147
+                    $absolutePath
2148
+                ]
2149
+            );
2150
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2151
+        }
2152
+        if (isset($parts[2])) {
2153
+            return $parts[2];
2154
+        }
2155
+        return '';
2156
+    }
2157
+
2158
+    /**
2159
+     * @param string $filename
2160
+     * @return array
2161
+     * @throws \OC\User\NoUserException
2162
+     * @throws NotFoundException
2163
+     */
2164
+    public function getUidAndFilename($filename) {
2165
+        $info = $this->getFileInfo($filename);
2166
+        if (!$info instanceof \OCP\Files\FileInfo) {
2167
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2168
+        }
2169
+        $uid = $info->getOwner()->getUID();
2170
+        if ($uid != \OC_User::getUser()) {
2171
+            Filesystem::initMountPoints($uid);
2172
+            $ownerView = new View('/' . $uid . '/files');
2173
+            try {
2174
+                $filename = $ownerView->getPath($info['fileid']);
2175
+            } catch (NotFoundException $e) {
2176
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2177
+            }
2178
+        }
2179
+        return [$uid, $filename];
2180
+    }
2181
+
2182
+    /**
2183
+     * Creates parent non-existing folders
2184
+     *
2185
+     * @param string $filePath
2186
+     * @return bool
2187
+     */
2188
+    private function createParentDirectories($filePath) {
2189
+        $directoryParts = explode('/', $filePath);
2190
+        $directoryParts = array_filter($directoryParts);
2191
+        foreach ($directoryParts as $key => $part) {
2192
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2193
+            $currentPath = '/' . implode('/', $currentPathElements);
2194
+            if ($this->is_file($currentPath)) {
2195
+                return false;
2196
+            }
2197
+            if (!$this->file_exists($currentPath)) {
2198
+                $this->mkdir($currentPath);
2199
+            }
2200
+        }
2201
+
2202
+        return true;
2203
+    }
2204 2204
 }
Please login to merge, or discard this patch.
Spacing   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -130,9 +130,9 @@  discard block
 block discarded – undo
130 130
 			$path = '/';
131 131
 		}
132 132
 		if ($path[0] !== '/') {
133
-			$path = '/' . $path;
133
+			$path = '/'.$path;
134 134
 		}
135
-		return $this->fakeRoot . $path;
135
+		return $this->fakeRoot.$path;
136 136
 	}
137 137
 
138 138
 	/**
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 	public function chroot($fakeRoot) {
145 145
 		if (!$fakeRoot == '') {
146 146
 			if ($fakeRoot[0] !== '/') {
147
-				$fakeRoot = '/' . $fakeRoot;
147
+				$fakeRoot = '/'.$fakeRoot;
148 148
 			}
149 149
 		}
150 150
 		$this->fakeRoot = $fakeRoot;
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 		}
177 177
 
178 178
 		// missing slashes can cause wrong matches!
179
-		$root = rtrim($this->fakeRoot, '/') . '/';
179
+		$root = rtrim($this->fakeRoot, '/').'/';
180 180
 
181 181
 		if (strpos($path, $root) !== 0) {
182 182
 			return null;
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
 		if ($mount instanceof MoveableMount) {
283 283
 			// cut of /user/files to get the relative path to data/user/files
284 284
 			$pathParts = explode('/', $path, 4);
285
-			$relPath = '/' . $pathParts[3];
285
+			$relPath = '/'.$pathParts[3];
286 286
 			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
287 287
 			\OC_Hook::emit(
288 288
 				Filesystem::CLASSNAME, "umount",
@@ -718,7 +718,7 @@  discard block
 block discarded – undo
718 718
 		}
719 719
 		$postFix = (substr($path, -1) === '/') ? '/' : '';
720 720
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
721
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
721
+		$mount = Filesystem::getMountManager()->find($absolutePath.$postFix);
722 722
 		if ($mount->getInternalPath($absolutePath) === '') {
723 723
 			return $this->removeMount($mount, $absolutePath);
724 724
 		}
@@ -995,7 +995,7 @@  discard block
 block discarded – undo
995 995
 				$hooks[] = 'write';
996 996
 				break;
997 997
 			default:
998
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, ILogger::ERROR);
998
+				\OCP\Util::writeLog('core', 'invalid mode ('.$mode.') for '.$path, ILogger::ERROR);
999 999
 		}
1000 1000
 
1001 1001
 		if ($mode !== 'r' && $mode !== 'w') {
@@ -1099,7 +1099,7 @@  discard block
 block discarded – undo
1099 1099
 					[Filesystem::signal_param_path => $this->getHookPath($path)]
1100 1100
 				);
1101 1101
 			}
1102
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1102
+			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath.$postFix);
1103 1103
 			if ($storage) {
1104 1104
 				return $storage->hash($type, $internalPath, $raw);
1105 1105
 			}
@@ -1153,7 +1153,7 @@  discard block
 block discarded – undo
1153 1153
 
1154 1154
 			$run = $this->runHooks($hooks, $path);
1155 1155
 			/** @var \OC\Files\Storage\Storage $storage */
1156
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1156
+			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath.$postFix);
1157 1157
 			if ($run and $storage) {
1158 1158
 				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1159 1159
 					try {
@@ -1198,7 +1198,7 @@  discard block
 block discarded – undo
1198 1198
 					$unlockLater = true;
1199 1199
 					// make sure our unlocking callback will still be called if connection is aborted
1200 1200
 					ignore_user_abort(true);
1201
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1201
+					$result = CallbackWrapper::wrap($result, null, null, function() use ($hooks, $path) {
1202 1202
 						if (in_array('write', $hooks)) {
1203 1203
 							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1204 1204
 						} elseif (in_array('read', $hooks)) {
@@ -1259,7 +1259,7 @@  discard block
 block discarded – undo
1259 1259
 			return true;
1260 1260
 		}
1261 1261
 
1262
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1262
+		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot.'/');
1263 1263
 	}
1264 1264
 
1265 1265
 	/**
@@ -1278,7 +1278,7 @@  discard block
 block discarded – undo
1278 1278
 				if ($hook != 'read') {
1279 1279
 					\OC_Hook::emit(
1280 1280
 						Filesystem::CLASSNAME,
1281
-						$prefix . $hook,
1281
+						$prefix.$hook,
1282 1282
 						[
1283 1283
 							Filesystem::signal_param_run => &$run,
1284 1284
 							Filesystem::signal_param_path => $path
@@ -1287,7 +1287,7 @@  discard block
 block discarded – undo
1287 1287
 				} elseif (!$post) {
1288 1288
 					\OC_Hook::emit(
1289 1289
 						Filesystem::CLASSNAME,
1290
-						$prefix . $hook,
1290
+						$prefix.$hook,
1291 1291
 						[
1292 1292
 							Filesystem::signal_param_path => $path
1293 1293
 						]
@@ -1380,7 +1380,7 @@  discard block
 block discarded – undo
1380 1380
 			return $this->getPartFileInfo($path);
1381 1381
 		}
1382 1382
 		$relativePath = $path;
1383
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1383
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1384 1384
 
1385 1385
 		$mount = Filesystem::getMountManager()->find($path);
1386 1386
 		$storage = $mount->getStorage();
@@ -1408,7 +1408,7 @@  discard block
 block discarded – undo
1408 1408
 					//add the sizes of other mount points to the folder
1409 1409
 					$extOnly = ($includeMountPoints === 'ext');
1410 1410
 					$mounts = Filesystem::getMountManager()->findIn($path);
1411
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1411
+					$info->setSubMounts(array_filter($mounts, function(IMountPoint $mount) use ($extOnly) {
1412 1412
 						$subStorage = $mount->getStorage();
1413 1413
 						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1414 1414
 					}));
@@ -1417,7 +1417,7 @@  discard block
 block discarded – undo
1417 1417
 
1418 1418
 			return $info;
1419 1419
 		} else {
1420
-			\OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
1420
+			\OC::$server->getLogger()->warning('Storage not valid for mountpoint: '.$mount->getMountPoint());
1421 1421
 		}
1422 1422
 
1423 1423
 		return false;
@@ -1458,18 +1458,18 @@  discard block
 block discarded – undo
1458 1458
 
1459 1459
 			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1460 1460
 
1461
-			$fileNames = array_map(function (ICacheEntry $content) {
1461
+			$fileNames = array_map(function(ICacheEntry $content) {
1462 1462
 				return $content->getName();
1463 1463
 			}, $contents);
1464 1464
 			/**
1465 1465
 			 * @var \OC\Files\FileInfo[] $fileInfos
1466 1466
 			 */
1467
-			$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1467
+			$fileInfos = array_map(function(ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1468 1468
 				if ($sharingDisabled) {
1469 1469
 					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1470 1470
 				}
1471 1471
 				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1472
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1472
+				return new FileInfo($path.'/'.$content['name'], $storage, $content['path'], $content, $mount, $owner);
1473 1473
 			}, $contents);
1474 1474
 			$files = array_combine($fileNames, $fileInfos);
1475 1475
 
@@ -1494,7 +1494,7 @@  discard block
 block discarded – undo
1494 1494
 						} catch (\Exception $e) {
1495 1495
 							// sometimes when the storage is not available it can be any exception
1496 1496
 							\OC::$server->getLogger()->logException($e, [
1497
-								'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
1497
+								'message' => 'Exception while scanning storage "'.$subStorage->getId().'"',
1498 1498
 								'level' => ILogger::ERROR,
1499 1499
 								'app' => 'lib',
1500 1500
 							]);
@@ -1525,7 +1525,7 @@  discard block
 block discarded – undo
1525 1525
 								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1526 1526
 							}
1527 1527
 
1528
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1528
+							$rootEntry['path'] = substr(Filesystem::normalizePath($path.'/'.$rootEntry['name']), strlen($user) + 2); // full path without /$user/
1529 1529
 
1530 1530
 							// if sharing was disabled for the user we remove the share permissions
1531 1531
 							if (\OCP\Util::isSharingDisabledForUser()) {
@@ -1533,14 +1533,14 @@  discard block
 block discarded – undo
1533 1533
 							}
1534 1534
 
1535 1535
 							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1536
-							$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1536
+							$files[$rootEntry->getName()] = new FileInfo($path.'/'.$rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1537 1537
 						}
1538 1538
 					}
1539 1539
 				}
1540 1540
 			}
1541 1541
 
1542 1542
 			if ($mimetype_filter) {
1543
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1543
+				$files = array_filter($files, function(FileInfo $file) use ($mimetype_filter) {
1544 1544
 					if (strpos($mimetype_filter, '/')) {
1545 1545
 						return $file->getMimetype() === $mimetype_filter;
1546 1546
 					} else {
@@ -1569,7 +1569,7 @@  discard block
 block discarded – undo
1569 1569
 		if ($data instanceof FileInfo) {
1570 1570
 			$data = $data->getData();
1571 1571
 		}
1572
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1572
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1573 1573
 		/**
1574 1574
 		 * @var \OC\Files\Storage\Storage $storage
1575 1575
 		 * @var string $internalPath
@@ -1596,7 +1596,7 @@  discard block
 block discarded – undo
1596 1596
 	 * @return FileInfo[]
1597 1597
 	 */
1598 1598
 	public function search($query) {
1599
-		return $this->searchCommon('search', ['%' . $query . '%']);
1599
+		return $this->searchCommon('search', ['%'.$query.'%']);
1600 1600
 	}
1601 1601
 
1602 1602
 	/**
@@ -1648,10 +1648,10 @@  discard block
 block discarded – undo
1648 1648
 
1649 1649
 			$results = call_user_func_array([$cache, $method], $args);
1650 1650
 			foreach ($results as $result) {
1651
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1651
+				if (substr($mountPoint.$result['path'], 0, $rootLength + 1) === $this->fakeRoot.'/') {
1652 1652
 					$internalPath = $result['path'];
1653
-					$path = $mountPoint . $result['path'];
1654
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1653
+					$path = $mountPoint.$result['path'];
1654
+					$result['path'] = substr($mountPoint.$result['path'], $rootLength);
1655 1655
 					$owner = $userManager->get($storage->getOwner($internalPath));
1656 1656
 					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1657 1657
 				}
@@ -1669,8 +1669,8 @@  discard block
 block discarded – undo
1669 1669
 					if ($results) {
1670 1670
 						foreach ($results as $result) {
1671 1671
 							$internalPath = $result['path'];
1672
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1673
-							$path = rtrim($mountPoint . $internalPath, '/');
1672
+							$result['path'] = rtrim($relativeMountPoint.$result['path'], '/');
1673
+							$path = rtrim($mountPoint.$internalPath, '/');
1674 1674
 							$owner = $userManager->get($storage->getOwner($internalPath));
1675 1675
 							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1676 1676
 						}
@@ -1691,11 +1691,11 @@  discard block
 block discarded – undo
1691 1691
 	public function getOwner($path) {
1692 1692
 		$info = $this->getFileInfo($path);
1693 1693
 		if (!$info) {
1694
-			throw new NotFoundException($path . ' not found while trying to get owner');
1694
+			throw new NotFoundException($path.' not found while trying to get owner');
1695 1695
 		}
1696 1696
 
1697 1697
 		if ($info->getOwner() === null) {
1698
-			throw new NotFoundException($path . ' has no owner');
1698
+			throw new NotFoundException($path.' has no owner');
1699 1699
 		}
1700 1700
 
1701 1701
 		return $info->getOwner()->getUID();
@@ -1731,7 +1731,7 @@  discard block
 block discarded – undo
1731 1731
 	 * @throws NotFoundException
1732 1732
 	 */
1733 1733
 	public function getPath($id, int $storageId = null) {
1734
-		$id = (int)$id;
1734
+		$id = (int) $id;
1735 1735
 		$manager = Filesystem::getMountManager();
1736 1736
 		$mounts = $manager->findIn($this->fakeRoot);
1737 1737
 		$mounts[] = $manager->find($this->fakeRoot);
@@ -1742,12 +1742,12 @@  discard block
 block discarded – undo
1742 1742
 
1743 1743
 		// put non-shared mounts in front of the shared mount
1744 1744
 		// this prevents unneeded recursion into shares
1745
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1745
+		usort($mounts, function(IMountPoint $a, IMountPoint $b) {
1746 1746
 			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1747 1747
 		});
1748 1748
 
1749 1749
 		if (!is_null($storageId)) {
1750
-			$mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1750
+			$mounts = array_filter($mounts, function(IMountPoint $mount) use ($storageId) {
1751 1751
 				return $mount->getNumericStorageId() === $storageId;
1752 1752
 			});
1753 1753
 		}
@@ -1760,7 +1760,7 @@  discard block
 block discarded – undo
1760 1760
 				$cache = $mount->getStorage()->getCache();
1761 1761
 				$internalPath = $cache->getPathById($id);
1762 1762
 				if (is_string($internalPath)) {
1763
-					$fullPath = $mount->getMountPoint() . $internalPath;
1763
+					$fullPath = $mount->getMountPoint().$internalPath;
1764 1764
 					if (!is_null($path = $this->getRelativePath($fullPath))) {
1765 1765
 						return $path;
1766 1766
 					}
@@ -1796,10 +1796,10 @@  discard block
 block discarded – undo
1796 1796
 	private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1797 1797
 
1798 1798
 		// note: cannot use the view because the target is already locked
1799
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1799
+		$fileId = (int) $targetStorage->getCache()->getId($targetInternalPath);
1800 1800
 		if ($fileId === -1) {
1801 1801
 			// target might not exist, need to check parent instead
1802
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1802
+			$fileId = (int) $targetStorage->getCache()->getId(dirname($targetInternalPath));
1803 1803
 		}
1804 1804
 
1805 1805
 		// check if any of the parents were shared by the current owner (include collections)
@@ -1899,7 +1899,7 @@  discard block
 block discarded – undo
1899 1899
 		$resultPath = '';
1900 1900
 		foreach ($parts as $part) {
1901 1901
 			if ($part) {
1902
-				$resultPath .= '/' . $part;
1902
+				$resultPath .= '/'.$part;
1903 1903
 				$result[] = $resultPath;
1904 1904
 			}
1905 1905
 		}
@@ -2164,16 +2164,16 @@  discard block
 block discarded – undo
2164 2164
 	public function getUidAndFilename($filename) {
2165 2165
 		$info = $this->getFileInfo($filename);
2166 2166
 		if (!$info instanceof \OCP\Files\FileInfo) {
2167
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2167
+			throw new NotFoundException($this->getAbsolutePath($filename).' not found');
2168 2168
 		}
2169 2169
 		$uid = $info->getOwner()->getUID();
2170 2170
 		if ($uid != \OC_User::getUser()) {
2171 2171
 			Filesystem::initMountPoints($uid);
2172
-			$ownerView = new View('/' . $uid . '/files');
2172
+			$ownerView = new View('/'.$uid.'/files');
2173 2173
 			try {
2174 2174
 				$filename = $ownerView->getPath($info['fileid']);
2175 2175
 			} catch (NotFoundException $e) {
2176
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2176
+				throw new NotFoundException('File with id '.$info['fileid'].' not found for user '.$uid);
2177 2177
 			}
2178 2178
 		}
2179 2179
 		return [$uid, $filename];
@@ -2190,7 +2190,7 @@  discard block
 block discarded – undo
2190 2190
 		$directoryParts = array_filter($directoryParts);
2191 2191
 		foreach ($directoryParts as $key => $part) {
2192 2192
 			$currentPathElements = array_slice($directoryParts, 0, $key);
2193
-			$currentPath = '/' . implode('/', $currentPathElements);
2193
+			$currentPath = '/'.implode('/', $currentPathElements);
2194 2194
 			if ($this->is_file($currentPath)) {
2195 2195
 				return false;
2196 2196
 			}
Please login to merge, or discard this patch.