Passed
Push — master ( cddfb0...9e7341 )
by Julius
13:55 queued 13s
created
apps/dav/lib/Connector/Sabre/Directory.php 1 patch
Indentation   +430 added lines, -430 removed lines patch added patch discarded remove patch
@@ -56,434 +56,434 @@
 block discarded – undo
56 56
 use OCP\Share\IManager as IShareManager;
57 57
 
58 58
 class Directory extends \OCA\DAV\Connector\Sabre\Node implements \Sabre\DAV\ICollection, \Sabre\DAV\IQuota, \Sabre\DAV\IMoveTarget, \Sabre\DAV\ICopyTarget {
59
-	/**
60
-	 * Cached directory content
61
-	 * @var \OCP\Files\FileInfo[]
62
-	 */
63
-	private ?array $dirContent = null;
64
-
65
-	/** Cached quota info */
66
-	private ?array $quotaInfo = null;
67
-	private ?CachingTree $tree = null;
68
-
69
-	/** @var array<string, array<int, FileMetadata>> */
70
-	private array $metadata = [];
71
-
72
-	/**
73
-	 * Sets up the node, expects a full path name
74
-	 */
75
-	public function __construct(View $view, FileInfo $info, ?CachingTree $tree = null, IShareManager $shareManager = null) {
76
-		parent::__construct($view, $info, $shareManager);
77
-		$this->tree = $tree;
78
-	}
79
-
80
-	/**
81
-	 * Creates a new file in the directory
82
-	 *
83
-	 * Data will either be supplied as a stream resource, or in certain cases
84
-	 * as a string. Keep in mind that you may have to support either.
85
-	 *
86
-	 * After successful creation of the file, you may choose to return the ETag
87
-	 * of the new file here.
88
-	 *
89
-	 * The returned ETag must be surrounded by double-quotes (The quotes should
90
-	 * be part of the actual string).
91
-	 *
92
-	 * If you cannot accurately determine the ETag, you should not return it.
93
-	 * If you don't store the file exactly as-is (you're transforming it
94
-	 * somehow) you should also not return an ETag.
95
-	 *
96
-	 * This means that if a subsequent GET to this new file does not exactly
97
-	 * return the same contents of what was submitted here, you are strongly
98
-	 * recommended to omit the ETag.
99
-	 *
100
-	 * @param string $name Name of the file
101
-	 * @param resource|string $data Initial payload
102
-	 * @return null|string
103
-	 * @throws Exception\EntityTooLarge
104
-	 * @throws Exception\UnsupportedMediaType
105
-	 * @throws FileLocked
106
-	 * @throws InvalidPath
107
-	 * @throws \Sabre\DAV\Exception
108
-	 * @throws \Sabre\DAV\Exception\BadRequest
109
-	 * @throws \Sabre\DAV\Exception\Forbidden
110
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
111
-	 */
112
-	public function createFile($name, $data = null) {
113
-		try {
114
-			// for chunked upload also updating a existing file is a "createFile"
115
-			// because we create all the chunks before re-assemble them to the existing file.
116
-			if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
117
-				// exit if we can't create a new file and we don't updatable existing file
118
-				$chunkInfo = \OC_FileChunking::decodeName($name);
119
-				if (!$this->fileView->isCreatable($this->path) &&
120
-					!$this->fileView->isUpdatable($this->path . '/' . $chunkInfo['name'])
121
-				) {
122
-					throw new \Sabre\DAV\Exception\Forbidden();
123
-				}
124
-			} else {
125
-				// For non-chunked upload it is enough to check if we can create a new file
126
-				if (!$this->fileView->isCreatable($this->path)) {
127
-					throw new \Sabre\DAV\Exception\Forbidden();
128
-				}
129
-			}
130
-
131
-			$this->fileView->verifyPath($this->path, $name);
132
-
133
-			$path = $this->fileView->getAbsolutePath($this->path) . '/' . $name;
134
-			// in case the file already exists/overwriting
135
-			$info = $this->fileView->getFileInfo($this->path . '/' . $name);
136
-			if (!$info) {
137
-				// use a dummy FileInfo which is acceptable here since it will be refreshed after the put is complete
138
-				$info = new \OC\Files\FileInfo($path, null, null, [
139
-					'type' => FileInfo::TYPE_FILE
140
-				], null);
141
-			}
142
-			$node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info);
143
-
144
-			// only allow 1 process to upload a file at once but still allow reading the file while writing the part file
145
-			$node->acquireLock(ILockingProvider::LOCK_SHARED);
146
-			$this->fileView->lockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
147
-
148
-			$result = $node->put($data);
149
-
150
-			$this->fileView->unlockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
151
-			$node->releaseLock(ILockingProvider::LOCK_SHARED);
152
-			return $result;
153
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
154
-			throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage(), $e->getCode(), $e);
155
-		} catch (InvalidPathException $ex) {
156
-			throw new InvalidPath($ex->getMessage(), false, $ex);
157
-		} catch (ForbiddenException $ex) {
158
-			throw new Forbidden($ex->getMessage(), $ex->getRetry(), $ex);
159
-		} catch (LockedException $e) {
160
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
161
-		}
162
-	}
163
-
164
-	/**
165
-	 * Creates a new subdirectory
166
-	 *
167
-	 * @param string $name
168
-	 * @throws FileLocked
169
-	 * @throws InvalidPath
170
-	 * @throws \Sabre\DAV\Exception\Forbidden
171
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
172
-	 */
173
-	public function createDirectory($name) {
174
-		try {
175
-			if (!$this->info->isCreatable()) {
176
-				throw new \Sabre\DAV\Exception\Forbidden();
177
-			}
178
-
179
-			$this->fileView->verifyPath($this->path, $name);
180
-			$newPath = $this->path . '/' . $name;
181
-			if (!$this->fileView->mkdir($newPath)) {
182
-				throw new \Sabre\DAV\Exception\Forbidden('Could not create directory ' . $newPath);
183
-			}
184
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
185
-			throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
186
-		} catch (InvalidPathException $ex) {
187
-			throw new InvalidPath($ex->getMessage());
188
-		} catch (ForbiddenException $ex) {
189
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
190
-		} catch (LockedException $e) {
191
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
192
-		}
193
-	}
194
-
195
-	/**
196
-	 * Returns a specific child node, referenced by its name
197
-	 *
198
-	 * @param string $name
199
-	 * @param \OCP\Files\FileInfo $info
200
-	 * @return \Sabre\DAV\INode
201
-	 * @throws InvalidPath
202
-	 * @throws \Sabre\DAV\Exception\NotFound
203
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
204
-	 */
205
-	public function getChild($name, $info = null) {
206
-		if (!$this->info->isReadable()) {
207
-			// avoid detecting files through this way
208
-			throw new NotFound();
209
-		}
210
-
211
-		$path = $this->path . '/' . $name;
212
-		if (is_null($info)) {
213
-			try {
214
-				$this->fileView->verifyPath($this->path, $name);
215
-				$info = $this->fileView->getFileInfo($path);
216
-			} catch (\OCP\Files\StorageNotAvailableException $e) {
217
-				throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
218
-			} catch (InvalidPathException $ex) {
219
-				throw new InvalidPath($ex->getMessage());
220
-			} catch (ForbiddenException $e) {
221
-				throw new \Sabre\DAV\Exception\Forbidden();
222
-			}
223
-		}
224
-
225
-		if (!$info) {
226
-			throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
227
-		}
228
-
229
-		if ($info->getMimeType() === FileInfo::MIMETYPE_FOLDER) {
230
-			$node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this->tree, $this->shareManager);
231
-		} else {
232
-			$node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info, $this->shareManager);
233
-		}
234
-		if ($this->tree) {
235
-			$this->tree->cacheNode($node);
236
-		}
237
-		return $node;
238
-	}
239
-
240
-	/**
241
-	 * Returns an array with all the child nodes
242
-	 *
243
-	 * @return \Sabre\DAV\INode[]
244
-	 * @throws \Sabre\DAV\Exception\Locked
245
-	 * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden
246
-	 */
247
-	public function getChildren() {
248
-		if (!is_null($this->dirContent)) {
249
-			return $this->dirContent;
250
-		}
251
-		try {
252
-			if (!$this->info->isReadable()) {
253
-				// return 403 instead of 404 because a 404 would make
254
-				// the caller believe that the collection itself does not exist
255
-				if (\OCP\Server::get(\OCP\App\IAppManager::class)->isInstalled('files_accesscontrol')) {
256
-					throw new Forbidden('No read permissions. This might be caused by files_accesscontrol, check your configured rules');
257
-				} else {
258
-					throw new Forbidden('No read permissions');
259
-				}
260
-			}
261
-			$folderContent = $this->getNode()->getDirectoryListing();
262
-		} catch (LockedException $e) {
263
-			throw new Locked();
264
-		}
265
-
266
-		$nodes = [];
267
-		foreach ($folderContent as $info) {
268
-			$node = $this->getChild($info->getName(), $info);
269
-			$nodes[] = $node;
270
-		}
271
-		$this->dirContent = $nodes;
272
-		return $this->dirContent;
273
-	}
274
-
275
-	/**
276
-	 * Checks if a child exists.
277
-	 *
278
-	 * @param string $name
279
-	 * @return bool
280
-	 */
281
-	public function childExists($name) {
282
-		// note: here we do NOT resolve the chunk file name to the real file name
283
-		// to make sure we return false when checking for file existence with a chunk
284
-		// file name.
285
-		// This is to make sure that "createFile" is still triggered
286
-		// (required old code) instead of "updateFile".
287
-		//
288
-		// TODO: resolve chunk file name here and implement "updateFile"
289
-		$path = $this->path . '/' . $name;
290
-		return $this->fileView->file_exists($path);
291
-	}
292
-
293
-	/**
294
-	 * Deletes all files in this directory, and then itself
295
-	 *
296
-	 * @return void
297
-	 * @throws FileLocked
298
-	 * @throws \Sabre\DAV\Exception\Forbidden
299
-	 */
300
-	public function delete() {
301
-		if ($this->path === '' || $this->path === '/' || !$this->info->isDeletable()) {
302
-			throw new \Sabre\DAV\Exception\Forbidden();
303
-		}
304
-
305
-		try {
306
-			if (!$this->fileView->rmdir($this->path)) {
307
-				// assume it wasn't possible to remove due to permission issue
308
-				throw new \Sabre\DAV\Exception\Forbidden();
309
-			}
310
-		} catch (ForbiddenException $ex) {
311
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
312
-		} catch (LockedException $e) {
313
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
314
-		}
315
-	}
316
-
317
-	/**
318
-	 * Returns available diskspace information
319
-	 *
320
-	 * @return array
321
-	 */
322
-	public function getQuotaInfo() {
323
-		/** @var LoggerInterface $logger */
324
-		$logger = \OC::$server->get(LoggerInterface::class);
325
-		if ($this->quotaInfo) {
326
-			return $this->quotaInfo;
327
-		}
328
-		$relativePath = $this->fileView->getRelativePath($this->info->getPath());
329
-		if ($relativePath === null) {
330
-			$logger->warning("error while getting quota as the relative path cannot be found");
331
-			return [0, 0];
332
-		}
333
-
334
-		try {
335
-			$storageInfo = \OC_Helper::getStorageInfo($relativePath, $this->info, false);
336
-			if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
337
-				$free = \OCP\Files\FileInfo::SPACE_UNLIMITED;
338
-			} else {
339
-				$free = $storageInfo['free'];
340
-			}
341
-			$this->quotaInfo = [
342
-				$storageInfo['used'],
343
-				$free
344
-			];
345
-			return $this->quotaInfo;
346
-		} catch (\OCP\Files\NotFoundException $e) {
347
-			$logger->warning("error while getting quota into", ['exception' => $e]);
348
-			return [0, 0];
349
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
350
-			$logger->warning("error while getting quota into", ['exception' => $e]);
351
-			return [0, 0];
352
-		} catch (NotPermittedException $e) {
353
-			$logger->warning("error while getting quota into", ['exception' => $e]);
354
-			return [0, 0];
355
-		}
356
-	}
357
-
358
-	/**
359
-	 * Moves a node into this collection.
360
-	 *
361
-	 * It is up to the implementors to:
362
-	 *   1. Create the new resource.
363
-	 *   2. Remove the old resource.
364
-	 *   3. Transfer any properties or other data.
365
-	 *
366
-	 * Generally you should make very sure that your collection can easily move
367
-	 * the move.
368
-	 *
369
-	 * If you don't, just return false, which will trigger sabre/dav to handle
370
-	 * the move itself. If you return true from this function, the assumption
371
-	 * is that the move was successful.
372
-	 *
373
-	 * @param string $targetName New local file/collection name.
374
-	 * @param string $fullSourcePath Full path to source node
375
-	 * @param INode $sourceNode Source node itself
376
-	 * @return bool
377
-	 * @throws BadRequest
378
-	 * @throws ServiceUnavailable
379
-	 * @throws Forbidden
380
-	 * @throws FileLocked
381
-	 * @throws \Sabre\DAV\Exception\Forbidden
382
-	 */
383
-	public function moveInto($targetName, $fullSourcePath, INode $sourceNode) {
384
-		if (!$sourceNode instanceof Node) {
385
-			// it's a file of another kind, like FutureFile
386
-			if ($sourceNode instanceof IFile) {
387
-				// fallback to default copy+delete handling
388
-				return false;
389
-			}
390
-			throw new BadRequest('Incompatible node types');
391
-		}
392
-
393
-		if (!$this->fileView) {
394
-			throw new ServiceUnavailable('filesystem not setup');
395
-		}
396
-
397
-		$destinationPath = $this->getPath() . '/' . $targetName;
398
-
399
-
400
-		$targetNodeExists = $this->childExists($targetName);
401
-
402
-		// at getNodeForPath we also check the path for isForbiddenFileOrDir
403
-		// with that we have covered both source and destination
404
-		if ($sourceNode instanceof Directory && $targetNodeExists) {
405
-			throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists');
406
-		}
407
-
408
-		[$sourceDir,] = \Sabre\Uri\split($sourceNode->getPath());
409
-		$destinationDir = $this->getPath();
410
-
411
-		$sourcePath = $sourceNode->getPath();
412
-
413
-		$isMovableMount = false;
414
-		$sourceMount = \OC::$server->getMountManager()->find($this->fileView->getAbsolutePath($sourcePath));
415
-		$internalPath = $sourceMount->getInternalPath($this->fileView->getAbsolutePath($sourcePath));
416
-		if ($sourceMount instanceof MoveableMount && $internalPath === '') {
417
-			$isMovableMount = true;
418
-		}
419
-
420
-		try {
421
-			$sameFolder = ($sourceDir === $destinationDir);
422
-			// if we're overwriting or same folder
423
-			if ($targetNodeExists || $sameFolder) {
424
-				// note that renaming a share mount point is always allowed
425
-				if (!$this->fileView->isUpdatable($destinationDir) && !$isMovableMount) {
426
-					throw new \Sabre\DAV\Exception\Forbidden();
427
-				}
428
-			} else {
429
-				if (!$this->fileView->isCreatable($destinationDir)) {
430
-					throw new \Sabre\DAV\Exception\Forbidden();
431
-				}
432
-			}
433
-
434
-			if (!$sameFolder) {
435
-				// moving to a different folder, source will be gone, like a deletion
436
-				// note that moving a share mount point is always allowed
437
-				if (!$this->fileView->isDeletable($sourcePath) && !$isMovableMount) {
438
-					throw new \Sabre\DAV\Exception\Forbidden();
439
-				}
440
-			}
441
-
442
-			$fileName = basename($destinationPath);
443
-			try {
444
-				$this->fileView->verifyPath($destinationDir, $fileName);
445
-			} catch (InvalidPathException $ex) {
446
-				throw new InvalidPath($ex->getMessage());
447
-			}
448
-
449
-			$renameOkay = $this->fileView->rename($sourcePath, $destinationPath);
450
-			if (!$renameOkay) {
451
-				throw new \Sabre\DAV\Exception\Forbidden('');
452
-			}
453
-		} catch (StorageNotAvailableException $e) {
454
-			throw new ServiceUnavailable($e->getMessage());
455
-		} catch (ForbiddenException $ex) {
456
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
457
-		} catch (LockedException $e) {
458
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
459
-		}
460
-
461
-		return true;
462
-	}
463
-
464
-
465
-	public function copyInto($targetName, $sourcePath, INode $sourceNode) {
466
-		if ($sourceNode instanceof File || $sourceNode instanceof Directory) {
467
-			$destinationPath = $this->getPath() . '/' . $targetName;
468
-			$sourcePath = $sourceNode->getPath();
469
-
470
-			if (!$this->fileView->isCreatable($this->getPath())) {
471
-				throw new \Sabre\DAV\Exception\Forbidden();
472
-			}
473
-
474
-			try {
475
-				$this->fileView->verifyPath($this->getPath(), $targetName);
476
-			} catch (InvalidPathException $ex) {
477
-				throw new InvalidPath($ex->getMessage());
478
-			}
479
-
480
-			return $this->fileView->copy($sourcePath, $destinationPath);
481
-		}
482
-
483
-		return false;
484
-	}
485
-
486
-	public function getNode(): Folder {
487
-		return $this->node;
488
-	}
59
+    /**
60
+     * Cached directory content
61
+     * @var \OCP\Files\FileInfo[]
62
+     */
63
+    private ?array $dirContent = null;
64
+
65
+    /** Cached quota info */
66
+    private ?array $quotaInfo = null;
67
+    private ?CachingTree $tree = null;
68
+
69
+    /** @var array<string, array<int, FileMetadata>> */
70
+    private array $metadata = [];
71
+
72
+    /**
73
+     * Sets up the node, expects a full path name
74
+     */
75
+    public function __construct(View $view, FileInfo $info, ?CachingTree $tree = null, IShareManager $shareManager = null) {
76
+        parent::__construct($view, $info, $shareManager);
77
+        $this->tree = $tree;
78
+    }
79
+
80
+    /**
81
+     * Creates a new file in the directory
82
+     *
83
+     * Data will either be supplied as a stream resource, or in certain cases
84
+     * as a string. Keep in mind that you may have to support either.
85
+     *
86
+     * After successful creation of the file, you may choose to return the ETag
87
+     * of the new file here.
88
+     *
89
+     * The returned ETag must be surrounded by double-quotes (The quotes should
90
+     * be part of the actual string).
91
+     *
92
+     * If you cannot accurately determine the ETag, you should not return it.
93
+     * If you don't store the file exactly as-is (you're transforming it
94
+     * somehow) you should also not return an ETag.
95
+     *
96
+     * This means that if a subsequent GET to this new file does not exactly
97
+     * return the same contents of what was submitted here, you are strongly
98
+     * recommended to omit the ETag.
99
+     *
100
+     * @param string $name Name of the file
101
+     * @param resource|string $data Initial payload
102
+     * @return null|string
103
+     * @throws Exception\EntityTooLarge
104
+     * @throws Exception\UnsupportedMediaType
105
+     * @throws FileLocked
106
+     * @throws InvalidPath
107
+     * @throws \Sabre\DAV\Exception
108
+     * @throws \Sabre\DAV\Exception\BadRequest
109
+     * @throws \Sabre\DAV\Exception\Forbidden
110
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
111
+     */
112
+    public function createFile($name, $data = null) {
113
+        try {
114
+            // for chunked upload also updating a existing file is a "createFile"
115
+            // because we create all the chunks before re-assemble them to the existing file.
116
+            if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
117
+                // exit if we can't create a new file and we don't updatable existing file
118
+                $chunkInfo = \OC_FileChunking::decodeName($name);
119
+                if (!$this->fileView->isCreatable($this->path) &&
120
+                    !$this->fileView->isUpdatable($this->path . '/' . $chunkInfo['name'])
121
+                ) {
122
+                    throw new \Sabre\DAV\Exception\Forbidden();
123
+                }
124
+            } else {
125
+                // For non-chunked upload it is enough to check if we can create a new file
126
+                if (!$this->fileView->isCreatable($this->path)) {
127
+                    throw new \Sabre\DAV\Exception\Forbidden();
128
+                }
129
+            }
130
+
131
+            $this->fileView->verifyPath($this->path, $name);
132
+
133
+            $path = $this->fileView->getAbsolutePath($this->path) . '/' . $name;
134
+            // in case the file already exists/overwriting
135
+            $info = $this->fileView->getFileInfo($this->path . '/' . $name);
136
+            if (!$info) {
137
+                // use a dummy FileInfo which is acceptable here since it will be refreshed after the put is complete
138
+                $info = new \OC\Files\FileInfo($path, null, null, [
139
+                    'type' => FileInfo::TYPE_FILE
140
+                ], null);
141
+            }
142
+            $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info);
143
+
144
+            // only allow 1 process to upload a file at once but still allow reading the file while writing the part file
145
+            $node->acquireLock(ILockingProvider::LOCK_SHARED);
146
+            $this->fileView->lockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
147
+
148
+            $result = $node->put($data);
149
+
150
+            $this->fileView->unlockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
151
+            $node->releaseLock(ILockingProvider::LOCK_SHARED);
152
+            return $result;
153
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
154
+            throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage(), $e->getCode(), $e);
155
+        } catch (InvalidPathException $ex) {
156
+            throw new InvalidPath($ex->getMessage(), false, $ex);
157
+        } catch (ForbiddenException $ex) {
158
+            throw new Forbidden($ex->getMessage(), $ex->getRetry(), $ex);
159
+        } catch (LockedException $e) {
160
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
161
+        }
162
+    }
163
+
164
+    /**
165
+     * Creates a new subdirectory
166
+     *
167
+     * @param string $name
168
+     * @throws FileLocked
169
+     * @throws InvalidPath
170
+     * @throws \Sabre\DAV\Exception\Forbidden
171
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
172
+     */
173
+    public function createDirectory($name) {
174
+        try {
175
+            if (!$this->info->isCreatable()) {
176
+                throw new \Sabre\DAV\Exception\Forbidden();
177
+            }
178
+
179
+            $this->fileView->verifyPath($this->path, $name);
180
+            $newPath = $this->path . '/' . $name;
181
+            if (!$this->fileView->mkdir($newPath)) {
182
+                throw new \Sabre\DAV\Exception\Forbidden('Could not create directory ' . $newPath);
183
+            }
184
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
185
+            throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
186
+        } catch (InvalidPathException $ex) {
187
+            throw new InvalidPath($ex->getMessage());
188
+        } catch (ForbiddenException $ex) {
189
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
190
+        } catch (LockedException $e) {
191
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
192
+        }
193
+    }
194
+
195
+    /**
196
+     * Returns a specific child node, referenced by its name
197
+     *
198
+     * @param string $name
199
+     * @param \OCP\Files\FileInfo $info
200
+     * @return \Sabre\DAV\INode
201
+     * @throws InvalidPath
202
+     * @throws \Sabre\DAV\Exception\NotFound
203
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
204
+     */
205
+    public function getChild($name, $info = null) {
206
+        if (!$this->info->isReadable()) {
207
+            // avoid detecting files through this way
208
+            throw new NotFound();
209
+        }
210
+
211
+        $path = $this->path . '/' . $name;
212
+        if (is_null($info)) {
213
+            try {
214
+                $this->fileView->verifyPath($this->path, $name);
215
+                $info = $this->fileView->getFileInfo($path);
216
+            } catch (\OCP\Files\StorageNotAvailableException $e) {
217
+                throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
218
+            } catch (InvalidPathException $ex) {
219
+                throw new InvalidPath($ex->getMessage());
220
+            } catch (ForbiddenException $e) {
221
+                throw new \Sabre\DAV\Exception\Forbidden();
222
+            }
223
+        }
224
+
225
+        if (!$info) {
226
+            throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
227
+        }
228
+
229
+        if ($info->getMimeType() === FileInfo::MIMETYPE_FOLDER) {
230
+            $node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this->tree, $this->shareManager);
231
+        } else {
232
+            $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info, $this->shareManager);
233
+        }
234
+        if ($this->tree) {
235
+            $this->tree->cacheNode($node);
236
+        }
237
+        return $node;
238
+    }
239
+
240
+    /**
241
+     * Returns an array with all the child nodes
242
+     *
243
+     * @return \Sabre\DAV\INode[]
244
+     * @throws \Sabre\DAV\Exception\Locked
245
+     * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden
246
+     */
247
+    public function getChildren() {
248
+        if (!is_null($this->dirContent)) {
249
+            return $this->dirContent;
250
+        }
251
+        try {
252
+            if (!$this->info->isReadable()) {
253
+                // return 403 instead of 404 because a 404 would make
254
+                // the caller believe that the collection itself does not exist
255
+                if (\OCP\Server::get(\OCP\App\IAppManager::class)->isInstalled('files_accesscontrol')) {
256
+                    throw new Forbidden('No read permissions. This might be caused by files_accesscontrol, check your configured rules');
257
+                } else {
258
+                    throw new Forbidden('No read permissions');
259
+                }
260
+            }
261
+            $folderContent = $this->getNode()->getDirectoryListing();
262
+        } catch (LockedException $e) {
263
+            throw new Locked();
264
+        }
265
+
266
+        $nodes = [];
267
+        foreach ($folderContent as $info) {
268
+            $node = $this->getChild($info->getName(), $info);
269
+            $nodes[] = $node;
270
+        }
271
+        $this->dirContent = $nodes;
272
+        return $this->dirContent;
273
+    }
274
+
275
+    /**
276
+     * Checks if a child exists.
277
+     *
278
+     * @param string $name
279
+     * @return bool
280
+     */
281
+    public function childExists($name) {
282
+        // note: here we do NOT resolve the chunk file name to the real file name
283
+        // to make sure we return false when checking for file existence with a chunk
284
+        // file name.
285
+        // This is to make sure that "createFile" is still triggered
286
+        // (required old code) instead of "updateFile".
287
+        //
288
+        // TODO: resolve chunk file name here and implement "updateFile"
289
+        $path = $this->path . '/' . $name;
290
+        return $this->fileView->file_exists($path);
291
+    }
292
+
293
+    /**
294
+     * Deletes all files in this directory, and then itself
295
+     *
296
+     * @return void
297
+     * @throws FileLocked
298
+     * @throws \Sabre\DAV\Exception\Forbidden
299
+     */
300
+    public function delete() {
301
+        if ($this->path === '' || $this->path === '/' || !$this->info->isDeletable()) {
302
+            throw new \Sabre\DAV\Exception\Forbidden();
303
+        }
304
+
305
+        try {
306
+            if (!$this->fileView->rmdir($this->path)) {
307
+                // assume it wasn't possible to remove due to permission issue
308
+                throw new \Sabre\DAV\Exception\Forbidden();
309
+            }
310
+        } catch (ForbiddenException $ex) {
311
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
312
+        } catch (LockedException $e) {
313
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
314
+        }
315
+    }
316
+
317
+    /**
318
+     * Returns available diskspace information
319
+     *
320
+     * @return array
321
+     */
322
+    public function getQuotaInfo() {
323
+        /** @var LoggerInterface $logger */
324
+        $logger = \OC::$server->get(LoggerInterface::class);
325
+        if ($this->quotaInfo) {
326
+            return $this->quotaInfo;
327
+        }
328
+        $relativePath = $this->fileView->getRelativePath($this->info->getPath());
329
+        if ($relativePath === null) {
330
+            $logger->warning("error while getting quota as the relative path cannot be found");
331
+            return [0, 0];
332
+        }
333
+
334
+        try {
335
+            $storageInfo = \OC_Helper::getStorageInfo($relativePath, $this->info, false);
336
+            if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
337
+                $free = \OCP\Files\FileInfo::SPACE_UNLIMITED;
338
+            } else {
339
+                $free = $storageInfo['free'];
340
+            }
341
+            $this->quotaInfo = [
342
+                $storageInfo['used'],
343
+                $free
344
+            ];
345
+            return $this->quotaInfo;
346
+        } catch (\OCP\Files\NotFoundException $e) {
347
+            $logger->warning("error while getting quota into", ['exception' => $e]);
348
+            return [0, 0];
349
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
350
+            $logger->warning("error while getting quota into", ['exception' => $e]);
351
+            return [0, 0];
352
+        } catch (NotPermittedException $e) {
353
+            $logger->warning("error while getting quota into", ['exception' => $e]);
354
+            return [0, 0];
355
+        }
356
+    }
357
+
358
+    /**
359
+     * Moves a node into this collection.
360
+     *
361
+     * It is up to the implementors to:
362
+     *   1. Create the new resource.
363
+     *   2. Remove the old resource.
364
+     *   3. Transfer any properties or other data.
365
+     *
366
+     * Generally you should make very sure that your collection can easily move
367
+     * the move.
368
+     *
369
+     * If you don't, just return false, which will trigger sabre/dav to handle
370
+     * the move itself. If you return true from this function, the assumption
371
+     * is that the move was successful.
372
+     *
373
+     * @param string $targetName New local file/collection name.
374
+     * @param string $fullSourcePath Full path to source node
375
+     * @param INode $sourceNode Source node itself
376
+     * @return bool
377
+     * @throws BadRequest
378
+     * @throws ServiceUnavailable
379
+     * @throws Forbidden
380
+     * @throws FileLocked
381
+     * @throws \Sabre\DAV\Exception\Forbidden
382
+     */
383
+    public function moveInto($targetName, $fullSourcePath, INode $sourceNode) {
384
+        if (!$sourceNode instanceof Node) {
385
+            // it's a file of another kind, like FutureFile
386
+            if ($sourceNode instanceof IFile) {
387
+                // fallback to default copy+delete handling
388
+                return false;
389
+            }
390
+            throw new BadRequest('Incompatible node types');
391
+        }
392
+
393
+        if (!$this->fileView) {
394
+            throw new ServiceUnavailable('filesystem not setup');
395
+        }
396
+
397
+        $destinationPath = $this->getPath() . '/' . $targetName;
398
+
399
+
400
+        $targetNodeExists = $this->childExists($targetName);
401
+
402
+        // at getNodeForPath we also check the path for isForbiddenFileOrDir
403
+        // with that we have covered both source and destination
404
+        if ($sourceNode instanceof Directory && $targetNodeExists) {
405
+            throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists');
406
+        }
407
+
408
+        [$sourceDir,] = \Sabre\Uri\split($sourceNode->getPath());
409
+        $destinationDir = $this->getPath();
410
+
411
+        $sourcePath = $sourceNode->getPath();
412
+
413
+        $isMovableMount = false;
414
+        $sourceMount = \OC::$server->getMountManager()->find($this->fileView->getAbsolutePath($sourcePath));
415
+        $internalPath = $sourceMount->getInternalPath($this->fileView->getAbsolutePath($sourcePath));
416
+        if ($sourceMount instanceof MoveableMount && $internalPath === '') {
417
+            $isMovableMount = true;
418
+        }
419
+
420
+        try {
421
+            $sameFolder = ($sourceDir === $destinationDir);
422
+            // if we're overwriting or same folder
423
+            if ($targetNodeExists || $sameFolder) {
424
+                // note that renaming a share mount point is always allowed
425
+                if (!$this->fileView->isUpdatable($destinationDir) && !$isMovableMount) {
426
+                    throw new \Sabre\DAV\Exception\Forbidden();
427
+                }
428
+            } else {
429
+                if (!$this->fileView->isCreatable($destinationDir)) {
430
+                    throw new \Sabre\DAV\Exception\Forbidden();
431
+                }
432
+            }
433
+
434
+            if (!$sameFolder) {
435
+                // moving to a different folder, source will be gone, like a deletion
436
+                // note that moving a share mount point is always allowed
437
+                if (!$this->fileView->isDeletable($sourcePath) && !$isMovableMount) {
438
+                    throw new \Sabre\DAV\Exception\Forbidden();
439
+                }
440
+            }
441
+
442
+            $fileName = basename($destinationPath);
443
+            try {
444
+                $this->fileView->verifyPath($destinationDir, $fileName);
445
+            } catch (InvalidPathException $ex) {
446
+                throw new InvalidPath($ex->getMessage());
447
+            }
448
+
449
+            $renameOkay = $this->fileView->rename($sourcePath, $destinationPath);
450
+            if (!$renameOkay) {
451
+                throw new \Sabre\DAV\Exception\Forbidden('');
452
+            }
453
+        } catch (StorageNotAvailableException $e) {
454
+            throw new ServiceUnavailable($e->getMessage());
455
+        } catch (ForbiddenException $ex) {
456
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
457
+        } catch (LockedException $e) {
458
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
459
+        }
460
+
461
+        return true;
462
+    }
463
+
464
+
465
+    public function copyInto($targetName, $sourcePath, INode $sourceNode) {
466
+        if ($sourceNode instanceof File || $sourceNode instanceof Directory) {
467
+            $destinationPath = $this->getPath() . '/' . $targetName;
468
+            $sourcePath = $sourceNode->getPath();
469
+
470
+            if (!$this->fileView->isCreatable($this->getPath())) {
471
+                throw new \Sabre\DAV\Exception\Forbidden();
472
+            }
473
+
474
+            try {
475
+                $this->fileView->verifyPath($this->getPath(), $targetName);
476
+            } catch (InvalidPathException $ex) {
477
+                throw new InvalidPath($ex->getMessage());
478
+            }
479
+
480
+            return $this->fileView->copy($sourcePath, $destinationPath);
481
+        }
482
+
483
+        return false;
484
+    }
485
+
486
+    public function getNode(): Folder {
487
+        return $this->node;
488
+    }
489 489
 }
Please login to merge, or discard this patch.
apps/provisioning_api/lib/Controller/UsersController.php 2 patches
Indentation   +1345 added lines, -1345 removed lines patch added patch discarded remove patch
@@ -77,1349 +77,1349 @@
 block discarded – undo
77 77
 use Psr\Log\LoggerInterface;
78 78
 
79 79
 class UsersController extends AUserData {
80
-	/** @var IURLGenerator */
81
-	protected $urlGenerator;
82
-	/** @var LoggerInterface */
83
-	private $logger;
84
-	/** @var IFactory */
85
-	protected $l10nFactory;
86
-	/** @var NewUserMailHelper */
87
-	private $newUserMailHelper;
88
-	/** @var ISecureRandom */
89
-	private $secureRandom;
90
-	/** @var RemoteWipe */
91
-	private $remoteWipe;
92
-	/** @var KnownUserService */
93
-	private $knownUserService;
94
-	/** @var IEventDispatcher */
95
-	private $eventDispatcher;
96
-
97
-	public function __construct(
98
-		string $appName,
99
-		IRequest $request,
100
-		IUserManager $userManager,
101
-		IConfig $config,
102
-		IGroupManager $groupManager,
103
-		IUserSession $userSession,
104
-		IAccountManager $accountManager,
105
-		IURLGenerator $urlGenerator,
106
-		LoggerInterface $logger,
107
-		IFactory $l10nFactory,
108
-		NewUserMailHelper $newUserMailHelper,
109
-		ISecureRandom $secureRandom,
110
-		RemoteWipe $remoteWipe,
111
-		KnownUserService $knownUserService,
112
-		IEventDispatcher $eventDispatcher
113
-	) {
114
-		parent::__construct(
115
-			$appName,
116
-			$request,
117
-			$userManager,
118
-			$config,
119
-			$groupManager,
120
-			$userSession,
121
-			$accountManager,
122
-			$l10nFactory
123
-		);
124
-
125
-		$this->urlGenerator = $urlGenerator;
126
-		$this->logger = $logger;
127
-		$this->l10nFactory = $l10nFactory;
128
-		$this->newUserMailHelper = $newUserMailHelper;
129
-		$this->secureRandom = $secureRandom;
130
-		$this->remoteWipe = $remoteWipe;
131
-		$this->knownUserService = $knownUserService;
132
-		$this->eventDispatcher = $eventDispatcher;
133
-	}
134
-
135
-	/**
136
-	 * @NoAdminRequired
137
-	 *
138
-	 * returns a list of users
139
-	 *
140
-	 * @param string $search
141
-	 * @param int $limit
142
-	 * @param int $offset
143
-	 * @return DataResponse
144
-	 */
145
-	public function getUsers(string $search = '', int $limit = null, int $offset = 0): DataResponse {
146
-		$user = $this->userSession->getUser();
147
-		$users = [];
148
-
149
-		// Admin? Or SubAdmin?
150
-		$uid = $user->getUID();
151
-		$subAdminManager = $this->groupManager->getSubAdmin();
152
-		if ($this->groupManager->isAdmin($uid)) {
153
-			$users = $this->userManager->search($search, $limit, $offset);
154
-		} elseif ($subAdminManager->isSubAdmin($user)) {
155
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
156
-			foreach ($subAdminOfGroups as $key => $group) {
157
-				$subAdminOfGroups[$key] = $group->getGID();
158
-			}
159
-
160
-			$users = [];
161
-			foreach ($subAdminOfGroups as $group) {
162
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
163
-			}
164
-		}
165
-
166
-		$users = array_keys($users);
167
-
168
-		return new DataResponse([
169
-			'users' => $users
170
-		]);
171
-	}
172
-
173
-	/**
174
-	 * @NoAdminRequired
175
-	 *
176
-	 * returns a list of users and their data
177
-	 */
178
-	public function getUsersDetails(string $search = '', int $limit = null, int $offset = 0): DataResponse {
179
-		$currentUser = $this->userSession->getUser();
180
-		$users = [];
181
-
182
-		// Admin? Or SubAdmin?
183
-		$uid = $currentUser->getUID();
184
-		$subAdminManager = $this->groupManager->getSubAdmin();
185
-		if ($this->groupManager->isAdmin($uid)) {
186
-			$users = $this->userManager->search($search, $limit, $offset);
187
-			$users = array_keys($users);
188
-		} elseif ($subAdminManager->isSubAdmin($currentUser)) {
189
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($currentUser);
190
-			foreach ($subAdminOfGroups as $key => $group) {
191
-				$subAdminOfGroups[$key] = $group->getGID();
192
-			}
193
-
194
-			$users = [];
195
-			foreach ($subAdminOfGroups as $group) {
196
-				$users[] = array_keys($this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
197
-			}
198
-			$users = array_merge(...$users);
199
-		}
200
-
201
-		$usersDetails = [];
202
-		foreach ($users as $userId) {
203
-			$userId = (string) $userId;
204
-			$userData = $this->getUserData($userId);
205
-			// Do not insert empty entry
206
-			if (!empty($userData)) {
207
-				$usersDetails[$userId] = $userData;
208
-			} else {
209
-				// Logged user does not have permissions to see this user
210
-				// only showing its id
211
-				$usersDetails[$userId] = ['id' => $userId];
212
-			}
213
-		}
214
-
215
-		return new DataResponse([
216
-			'users' => $usersDetails
217
-		]);
218
-	}
219
-
220
-
221
-	/**
222
-	 * @NoAdminRequired
223
-	 * @NoSubAdminRequired
224
-	 *
225
-	 * @param string $location
226
-	 * @param array $search
227
-	 * @return DataResponse
228
-	 */
229
-	public function searchByPhoneNumbers(string $location, array $search): DataResponse {
230
-		$phoneUtil = PhoneNumberUtil::getInstance();
231
-
232
-		if ($phoneUtil->getCountryCodeForRegion($location) === 0) {
233
-			// Not a valid region code
234
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
235
-		}
236
-
237
-		/** @var IUser $user */
238
-		$user = $this->userSession->getUser();
239
-		$knownTo = $user->getUID();
240
-		$defaultPhoneRegion = $this->config->getSystemValueString('default_phone_region');
241
-
242
-		$normalizedNumberToKey = [];
243
-		foreach ($search as $key => $phoneNumbers) {
244
-			foreach ($phoneNumbers as $phone) {
245
-				try {
246
-					$phoneNumber = $phoneUtil->parse($phone, $location);
247
-					if ($phoneNumber instanceof PhoneNumber && $phoneUtil->isValidNumber($phoneNumber)) {
248
-						$normalizedNumber = $phoneUtil->format($phoneNumber, PhoneNumberFormat::E164);
249
-						$normalizedNumberToKey[$normalizedNumber] = (string) $key;
250
-					}
251
-				} catch (NumberParseException $e) {
252
-				}
253
-
254
-				if ($defaultPhoneRegion !== '' && $defaultPhoneRegion !== $location && strpos($phone, '0') === 0) {
255
-					// If the number has a leading zero (no country code),
256
-					// we also check the default phone region of the instance,
257
-					// when it's different to the user's given region.
258
-					try {
259
-						$phoneNumber = $phoneUtil->parse($phone, $defaultPhoneRegion);
260
-						if ($phoneNumber instanceof PhoneNumber && $phoneUtil->isValidNumber($phoneNumber)) {
261
-							$normalizedNumber = $phoneUtil->format($phoneNumber, PhoneNumberFormat::E164);
262
-							$normalizedNumberToKey[$normalizedNumber] = (string) $key;
263
-						}
264
-					} catch (NumberParseException $e) {
265
-					}
266
-				}
267
-			}
268
-		}
269
-
270
-		$phoneNumbers = array_keys($normalizedNumberToKey);
271
-
272
-		if (empty($phoneNumbers)) {
273
-			return new DataResponse();
274
-		}
275
-
276
-		// Cleanup all previous entries and only allow new matches
277
-		$this->knownUserService->deleteKnownTo($knownTo);
278
-
279
-		$userMatches = $this->accountManager->searchUsers(IAccountManager::PROPERTY_PHONE, $phoneNumbers);
280
-
281
-		if (empty($userMatches)) {
282
-			return new DataResponse();
283
-		}
284
-
285
-		$cloudUrl = rtrim($this->urlGenerator->getAbsoluteURL('/'), '/');
286
-		if (strpos($cloudUrl, 'http://') === 0) {
287
-			$cloudUrl = substr($cloudUrl, strlen('http://'));
288
-		} elseif (strpos($cloudUrl, 'https://') === 0) {
289
-			$cloudUrl = substr($cloudUrl, strlen('https://'));
290
-		}
291
-
292
-		$matches = [];
293
-		foreach ($userMatches as $phone => $userId) {
294
-			// Not using the ICloudIdManager as that would run a search for each contact to find the display name in the address book
295
-			$matches[$normalizedNumberToKey[$phone]] = $userId . '@' . $cloudUrl;
296
-			$this->knownUserService->storeIsKnownToUser($knownTo, $userId);
297
-		}
298
-
299
-		return new DataResponse($matches);
300
-	}
301
-
302
-	/**
303
-	 * @throws OCSException
304
-	 */
305
-	private function createNewUserId(): string {
306
-		$attempts = 0;
307
-		do {
308
-			$uidCandidate = $this->secureRandom->generate(10, ISecureRandom::CHAR_HUMAN_READABLE);
309
-			if (!$this->userManager->userExists($uidCandidate)) {
310
-				return $uidCandidate;
311
-			}
312
-			$attempts++;
313
-		} while ($attempts < 10);
314
-		throw new OCSException('Could not create non-existing user id', 111);
315
-	}
316
-
317
-	/**
318
-	 * @PasswordConfirmationRequired
319
-	 * @NoAdminRequired
320
-	 *
321
-	 * @param string $userid
322
-	 * @param string $password
323
-	 * @param string $displayName
324
-	 * @param string $email
325
-	 * @param array $groups
326
-	 * @param array $subadmin
327
-	 * @param string $quota
328
-	 * @param string $language
329
-	 * @return DataResponse
330
-	 * @throws OCSException
331
-	 */
332
-	public function addUser(
333
-		string $userid,
334
-		string $password = '',
335
-		string $displayName = '',
336
-		string $email = '',
337
-		array $groups = [],
338
-		array $subadmin = [],
339
-		string $quota = '',
340
-		string $language = ''
341
-	): DataResponse {
342
-		$user = $this->userSession->getUser();
343
-		$isAdmin = $this->groupManager->isAdmin($user->getUID());
344
-		$subAdminManager = $this->groupManager->getSubAdmin();
345
-
346
-		if (empty($userid) && $this->config->getAppValue('core', 'newUser.generateUserID', 'no') === 'yes') {
347
-			$userid = $this->createNewUserId();
348
-		}
349
-
350
-		if ($this->userManager->userExists($userid)) {
351
-			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
352
-			throw new OCSException($this->l10nFactory->get('provisioning_api')->t('User already exists'), 102);
353
-		}
354
-
355
-		if ($groups !== []) {
356
-			foreach ($groups as $group) {
357
-				if (!$this->groupManager->groupExists($group)) {
358
-					throw new OCSException('group ' . $group . ' does not exist', 104);
359
-				}
360
-				if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
361
-					throw new OCSException('insufficient privileges for group ' . $group, 105);
362
-				}
363
-			}
364
-		} else {
365
-			if (!$isAdmin) {
366
-				throw new OCSException('no group specified (required for subadmins)', 106);
367
-			}
368
-		}
369
-
370
-		$subadminGroups = [];
371
-		if ($subadmin !== []) {
372
-			foreach ($subadmin as $groupid) {
373
-				$group = $this->groupManager->get($groupid);
374
-				// Check if group exists
375
-				if ($group === null) {
376
-					throw new OCSException('Subadmin group does not exist', 102);
377
-				}
378
-				// Check if trying to make subadmin of admin group
379
-				if ($group->getGID() === 'admin') {
380
-					throw new OCSException('Cannot create subadmins for admin group', 103);
381
-				}
382
-				// Check if has permission to promote subadmins
383
-				if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) {
384
-					throw new OCSForbiddenException('No permissions to promote subadmins');
385
-				}
386
-				$subadminGroups[] = $group;
387
-			}
388
-		}
389
-
390
-		$generatePasswordResetToken = false;
391
-		if (strlen($password) > IUserManager::MAX_PASSWORD_LENGTH) {
392
-			throw new OCSException('Invalid password value', 101);
393
-		}
394
-		if ($password === '') {
395
-			if ($email === '') {
396
-				throw new OCSException('To send a password link to the user an email address is required.', 108);
397
-			}
398
-
399
-			$passwordEvent = new GenerateSecurePasswordEvent();
400
-			$this->eventDispatcher->dispatchTyped($passwordEvent);
401
-
402
-			$password = $passwordEvent->getPassword();
403
-			if ($password === null) {
404
-				// Fallback: ensure to pass password_policy in any case
405
-				$password = $this->secureRandom->generate(10)
406
-					. $this->secureRandom->generate(1, ISecureRandom::CHAR_UPPER)
407
-					. $this->secureRandom->generate(1, ISecureRandom::CHAR_LOWER)
408
-					. $this->secureRandom->generate(1, ISecureRandom::CHAR_DIGITS)
409
-					. $this->secureRandom->generate(1, ISecureRandom::CHAR_SYMBOLS);
410
-			}
411
-			$generatePasswordResetToken = true;
412
-		}
413
-
414
-		if ($email === '' && $this->config->getAppValue('core', 'newUser.requireEmail', 'no') === 'yes') {
415
-			throw new OCSException('Required email address was not provided', 110);
416
-		}
417
-
418
-		try {
419
-			$newUser = $this->userManager->createUser($userid, $password);
420
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
421
-
422
-			foreach ($groups as $group) {
423
-				$this->groupManager->get($group)->addUser($newUser);
424
-				$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
425
-			}
426
-			foreach ($subadminGroups as $group) {
427
-				$subAdminManager->createSubAdmin($newUser, $group);
428
-			}
429
-
430
-			if ($displayName !== '') {
431
-				try {
432
-					$this->editUser($userid, self::USER_FIELD_DISPLAYNAME, $displayName);
433
-				} catch (OCSException $e) {
434
-					if ($newUser instanceof IUser) {
435
-						$newUser->delete();
436
-					}
437
-					throw $e;
438
-				}
439
-			}
440
-
441
-			if ($quota !== '') {
442
-				$this->editUser($userid, self::USER_FIELD_QUOTA, $quota);
443
-			}
444
-
445
-			if ($language !== '') {
446
-				$this->editUser($userid, self::USER_FIELD_LANGUAGE, $language);
447
-			}
448
-
449
-			// Send new user mail only if a mail is set
450
-			if ($email !== '') {
451
-				$newUser->setEMailAddress($email);
452
-				if ($this->config->getAppValue('core', 'newUser.sendEmail', 'yes') === 'yes') {
453
-					try {
454
-						$emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
455
-						$this->newUserMailHelper->sendMail($newUser, $emailTemplate);
456
-					} catch (\Exception $e) {
457
-						// Mail could be failing hard or just be plain not configured
458
-						// Logging error as it is the hardest of the two
459
-						$this->logger->error(
460
-							"Unable to send the invitation mail to $email",
461
-							[
462
-								'app' => 'ocs_api',
463
-								'exception' => $e,
464
-							]
465
-						);
466
-					}
467
-				}
468
-			}
469
-
470
-			return new DataResponse(['id' => $userid]);
471
-		} catch (HintException $e) {
472
-			$this->logger->warning(
473
-				'Failed addUser attempt with hint exception.',
474
-				[
475
-					'app' => 'ocs_api',
476
-					'exception' => $e,
477
-				]
478
-			);
479
-			throw new OCSException($e->getHint(), 107);
480
-		} catch (OCSException $e) {
481
-			$this->logger->warning(
482
-				'Failed addUser attempt with ocs exception.',
483
-				[
484
-					'app' => 'ocs_api',
485
-					'exception' => $e,
486
-				]
487
-			);
488
-			throw $e;
489
-		} catch (InvalidArgumentException $e) {
490
-			$this->logger->error(
491
-				'Failed addUser attempt with invalid argument exception.',
492
-				[
493
-					'app' => 'ocs_api',
494
-					'exception' => $e,
495
-				]
496
-			);
497
-			throw new OCSException($e->getMessage(), 101);
498
-		} catch (\Exception $e) {
499
-			$this->logger->error(
500
-				'Failed addUser attempt with exception.',
501
-				[
502
-					'app' => 'ocs_api',
503
-					'exception' => $e
504
-				]
505
-			);
506
-			throw new OCSException('Bad request', 101);
507
-		}
508
-	}
509
-
510
-	/**
511
-	 * @NoAdminRequired
512
-	 * @NoSubAdminRequired
513
-	 *
514
-	 * gets user info
515
-	 *
516
-	 * @param string $userId
517
-	 * @return DataResponse
518
-	 * @throws OCSException
519
-	 */
520
-	public function getUser(string $userId): DataResponse {
521
-		$includeScopes = false;
522
-		$currentUser = $this->userSession->getUser();
523
-		if ($currentUser && $currentUser->getUID() === $userId) {
524
-			$includeScopes = true;
525
-		}
526
-
527
-		$data = $this->getUserData($userId, $includeScopes);
528
-		// getUserData returns empty array if not enough permissions
529
-		if (empty($data)) {
530
-			throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
531
-		}
532
-		return new DataResponse($data);
533
-	}
534
-
535
-	/**
536
-	 * @NoAdminRequired
537
-	 * @NoSubAdminRequired
538
-	 *
539
-	 * gets user info from the currently logged in user
540
-	 *
541
-	 * @return DataResponse
542
-	 * @throws OCSException
543
-	 */
544
-	public function getCurrentUser(): DataResponse {
545
-		$user = $this->userSession->getUser();
546
-		if ($user) {
547
-			$data = $this->getUserData($user->getUID(), true);
548
-			// rename "displayname" to "display-name" only for this call to keep
549
-			// the API stable.
550
-			$data['display-name'] = $data['displayname'];
551
-			unset($data['displayname']);
552
-			return new DataResponse($data);
553
-		}
554
-
555
-		throw new OCSException('', OCSController::RESPOND_UNAUTHORISED);
556
-	}
557
-
558
-	/**
559
-	 * @NoAdminRequired
560
-	 * @NoSubAdminRequired
561
-	 *
562
-	 * @return DataResponse
563
-	 * @throws OCSException
564
-	 */
565
-	public function getEditableFields(): DataResponse {
566
-		$currentLoggedInUser = $this->userSession->getUser();
567
-		if (!$currentLoggedInUser instanceof IUser) {
568
-			throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
569
-		}
570
-
571
-		return $this->getEditableFieldsForUser($currentLoggedInUser->getUID());
572
-	}
573
-
574
-	/**
575
-	 * @NoAdminRequired
576
-	 * @NoSubAdminRequired
577
-	 *
578
-	 * @param string $userId
579
-	 * @return DataResponse
580
-	 * @throws OCSException
581
-	 */
582
-	public function getEditableFieldsForUser(string $userId): DataResponse {
583
-		$currentLoggedInUser = $this->userSession->getUser();
584
-		if (!$currentLoggedInUser instanceof IUser) {
585
-			throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
586
-		}
587
-
588
-		$permittedFields = [];
589
-
590
-		if ($userId !== $currentLoggedInUser->getUID()) {
591
-			$targetUser = $this->userManager->get($userId);
592
-			if (!$targetUser instanceof IUser) {
593
-				throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
594
-			}
595
-
596
-			$subAdminManager = $this->groupManager->getSubAdmin();
597
-			if (
598
-				!$this->groupManager->isAdmin($currentLoggedInUser->getUID())
599
-				&& !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
600
-			) {
601
-				throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
602
-			}
603
-		} else {
604
-			$targetUser = $currentLoggedInUser;
605
-		}
606
-
607
-		// Editing self (display, email)
608
-		if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
609
-			if (
610
-				$targetUser->getBackend() instanceof ISetDisplayNameBackend
611
-				|| $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME)
612
-			) {
613
-				$permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME;
614
-			}
615
-			$permittedFields[] = IAccountManager::PROPERTY_EMAIL;
616
-		}
617
-
618
-		$permittedFields[] = IAccountManager::COLLECTION_EMAIL;
619
-		$permittedFields[] = IAccountManager::PROPERTY_PHONE;
620
-		$permittedFields[] = IAccountManager::PROPERTY_ADDRESS;
621
-		$permittedFields[] = IAccountManager::PROPERTY_WEBSITE;
622
-		$permittedFields[] = IAccountManager::PROPERTY_TWITTER;
623
-		$permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE;
624
-		$permittedFields[] = IAccountManager::PROPERTY_ORGANISATION;
625
-		$permittedFields[] = IAccountManager::PROPERTY_ROLE;
626
-		$permittedFields[] = IAccountManager::PROPERTY_HEADLINE;
627
-		$permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY;
628
-		$permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED;
629
-
630
-		return new DataResponse($permittedFields);
631
-	}
632
-
633
-	/**
634
-	 * @NoAdminRequired
635
-	 * @NoSubAdminRequired
636
-	 * @PasswordConfirmationRequired
637
-	 *
638
-	 * @throws OCSException
639
-	 */
640
-	public function editUserMultiValue(
641
-		string $userId,
642
-		string $collectionName,
643
-		string $key,
644
-		string $value
645
-	): DataResponse {
646
-		$currentLoggedInUser = $this->userSession->getUser();
647
-		if ($currentLoggedInUser === null) {
648
-			throw new OCSException('', OCSController::RESPOND_UNAUTHORISED);
649
-		}
650
-
651
-		$targetUser = $this->userManager->get($userId);
652
-		if ($targetUser === null) {
653
-			throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
654
-		}
655
-
656
-		$subAdminManager = $this->groupManager->getSubAdmin();
657
-		$isAdminOrSubadmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID())
658
-			|| $subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser);
659
-
660
-		$permittedFields = [];
661
-		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
662
-			// Editing self (display, email)
663
-			$permittedFields[] = IAccountManager::COLLECTION_EMAIL;
664
-			$permittedFields[] = IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX;
665
-		} else {
666
-			// Check if admin / subadmin
667
-			if ($isAdminOrSubadmin) {
668
-				// They have permissions over the user
669
-				$permittedFields[] = IAccountManager::COLLECTION_EMAIL;
670
-			} else {
671
-				// No rights
672
-				throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
673
-			}
674
-		}
675
-
676
-		// Check if permitted to edit this field
677
-		if (!in_array($collectionName, $permittedFields)) {
678
-			throw new OCSException('', 103);
679
-		}
680
-
681
-		switch ($collectionName) {
682
-			case IAccountManager::COLLECTION_EMAIL:
683
-				$userAccount = $this->accountManager->getAccount($targetUser);
684
-				$mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
685
-				$mailCollection->removePropertyByValue($key);
686
-				if ($value !== '') {
687
-					$mailCollection->addPropertyWithDefaults($value);
688
-					$property = $mailCollection->getPropertyByValue($key);
689
-					if ($isAdminOrSubadmin && $property) {
690
-						// admin set mails are auto-verified
691
-						$property->setLocallyVerified(IAccountManager::VERIFIED);
692
-					}
693
-				}
694
-				$this->accountManager->updateAccount($userAccount);
695
-				break;
696
-
697
-			case IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX:
698
-				$userAccount = $this->accountManager->getAccount($targetUser);
699
-				$mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
700
-				$targetProperty = null;
701
-				foreach ($mailCollection->getProperties() as $property) {
702
-					if ($property->getValue() === $key) {
703
-						$targetProperty = $property;
704
-						break;
705
-					}
706
-				}
707
-				if ($targetProperty instanceof IAccountProperty) {
708
-					try {
709
-						$targetProperty->setScope($value);
710
-						$this->accountManager->updateAccount($userAccount);
711
-					} catch (InvalidArgumentException $e) {
712
-						throw new OCSException('', 102);
713
-					}
714
-				} else {
715
-					throw new OCSException('', 102);
716
-				}
717
-				break;
718
-
719
-			default:
720
-				throw new OCSException('', 103);
721
-		}
722
-		return new DataResponse();
723
-	}
724
-
725
-	/**
726
-	 * @NoAdminRequired
727
-	 * @NoSubAdminRequired
728
-	 * @PasswordConfirmationRequired
729
-	 *
730
-	 * edit users
731
-	 *
732
-	 * @param string $userId
733
-	 * @param string $key
734
-	 * @param string $value
735
-	 * @return DataResponse
736
-	 * @throws OCSException
737
-	 */
738
-	public function editUser(string $userId, string $key, string $value): DataResponse {
739
-		$currentLoggedInUser = $this->userSession->getUser();
740
-
741
-		$targetUser = $this->userManager->get($userId);
742
-		if ($targetUser === null) {
743
-			throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
744
-		}
745
-
746
-		$permittedFields = [];
747
-		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
748
-			// Editing self (display, email)
749
-			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
750
-				if (
751
-					$targetUser->getBackend() instanceof ISetDisplayNameBackend
752
-					|| $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME)
753
-				) {
754
-					$permittedFields[] = self::USER_FIELD_DISPLAYNAME;
755
-					$permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME;
756
-				}
757
-				$permittedFields[] = IAccountManager::PROPERTY_EMAIL;
758
-			}
759
-
760
-			$permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX;
761
-			$permittedFields[] = IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX;
762
-
763
-			$permittedFields[] = IAccountManager::COLLECTION_EMAIL;
764
-
765
-			$permittedFields[] = self::USER_FIELD_PASSWORD;
766
-			$permittedFields[] = self::USER_FIELD_NOTIFICATION_EMAIL;
767
-			if (
768
-				$this->config->getSystemValue('force_language', false) === false ||
769
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())
770
-			) {
771
-				$permittedFields[] = self::USER_FIELD_LANGUAGE;
772
-			}
773
-
774
-			if (
775
-				$this->config->getSystemValue('force_locale', false) === false ||
776
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())
777
-			) {
778
-				$permittedFields[] = self::USER_FIELD_LOCALE;
779
-			}
780
-
781
-			$permittedFields[] = IAccountManager::PROPERTY_PHONE;
782
-			$permittedFields[] = IAccountManager::PROPERTY_ADDRESS;
783
-			$permittedFields[] = IAccountManager::PROPERTY_WEBSITE;
784
-			$permittedFields[] = IAccountManager::PROPERTY_TWITTER;
785
-			$permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE;
786
-			$permittedFields[] = IAccountManager::PROPERTY_ORGANISATION;
787
-			$permittedFields[] = IAccountManager::PROPERTY_ROLE;
788
-			$permittedFields[] = IAccountManager::PROPERTY_HEADLINE;
789
-			$permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY;
790
-			$permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED;
791
-			$permittedFields[] = IAccountManager::PROPERTY_PHONE . self::SCOPE_SUFFIX;
792
-			$permittedFields[] = IAccountManager::PROPERTY_ADDRESS . self::SCOPE_SUFFIX;
793
-			$permittedFields[] = IAccountManager::PROPERTY_WEBSITE . self::SCOPE_SUFFIX;
794
-			$permittedFields[] = IAccountManager::PROPERTY_TWITTER . self::SCOPE_SUFFIX;
795
-			$permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE . self::SCOPE_SUFFIX;
796
-			$permittedFields[] = IAccountManager::PROPERTY_ORGANISATION . self::SCOPE_SUFFIX;
797
-			$permittedFields[] = IAccountManager::PROPERTY_ROLE . self::SCOPE_SUFFIX;
798
-			$permittedFields[] = IAccountManager::PROPERTY_HEADLINE . self::SCOPE_SUFFIX;
799
-			$permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY . self::SCOPE_SUFFIX;
800
-			$permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED . self::SCOPE_SUFFIX;
801
-
802
-			$permittedFields[] = IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX;
803
-
804
-			// If admin they can edit their own quota
805
-			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
806
-				$permittedFields[] = self::USER_FIELD_QUOTA;
807
-			}
808
-		} else {
809
-			// Check if admin / subadmin
810
-			$subAdminManager = $this->groupManager->getSubAdmin();
811
-			if (
812
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())
813
-				|| $subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
814
-			) {
815
-				// They have permissions over the user
816
-				if (
817
-					$targetUser->getBackend() instanceof ISetDisplayNameBackend
818
-					|| $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME)
819
-				) {
820
-					$permittedFields[] = self::USER_FIELD_DISPLAYNAME;
821
-					$permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME;
822
-				}
823
-				$permittedFields[] = IAccountManager::PROPERTY_EMAIL;
824
-				$permittedFields[] = IAccountManager::COLLECTION_EMAIL;
825
-				$permittedFields[] = self::USER_FIELD_PASSWORD;
826
-				$permittedFields[] = self::USER_FIELD_LANGUAGE;
827
-				$permittedFields[] = self::USER_FIELD_LOCALE;
828
-				$permittedFields[] = IAccountManager::PROPERTY_PHONE;
829
-				$permittedFields[] = IAccountManager::PROPERTY_ADDRESS;
830
-				$permittedFields[] = IAccountManager::PROPERTY_WEBSITE;
831
-				$permittedFields[] = IAccountManager::PROPERTY_TWITTER;
832
-				$permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE;
833
-				$permittedFields[] = IAccountManager::PROPERTY_ORGANISATION;
834
-				$permittedFields[] = IAccountManager::PROPERTY_ROLE;
835
-				$permittedFields[] = IAccountManager::PROPERTY_HEADLINE;
836
-				$permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY;
837
-				$permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED;
838
-				$permittedFields[] = self::USER_FIELD_QUOTA;
839
-				$permittedFields[] = self::USER_FIELD_NOTIFICATION_EMAIL;
840
-			} else {
841
-				// No rights
842
-				throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
843
-			}
844
-		}
845
-		// Check if permitted to edit this field
846
-		if (!in_array($key, $permittedFields)) {
847
-			throw new OCSException('', 103);
848
-		}
849
-		// Process the edit
850
-		switch ($key) {
851
-			case self::USER_FIELD_DISPLAYNAME:
852
-			case IAccountManager::PROPERTY_DISPLAYNAME:
853
-				try {
854
-					$targetUser->setDisplayName($value);
855
-				} catch (InvalidArgumentException $e) {
856
-					throw new OCSException($e->getMessage(), 101);
857
-				}
858
-				break;
859
-			case self::USER_FIELD_QUOTA:
860
-				$quota = $value;
861
-				if ($quota !== 'none' && $quota !== 'default') {
862
-					if (is_numeric($quota)) {
863
-						$quota = (float) $quota;
864
-					} else {
865
-						$quota = \OCP\Util::computerFileSize($quota);
866
-					}
867
-					if ($quota === false) {
868
-						throw new OCSException('Invalid quota value ' . $value, 102);
869
-					}
870
-					if ($quota === -1) {
871
-						$quota = 'none';
872
-					} else {
873
-						$maxQuota = (int) $this->config->getAppValue('files', 'max_quota', '-1');
874
-						if ($maxQuota !== -1 && $quota > $maxQuota) {
875
-							throw new OCSException('Invalid quota value. ' . $value . ' is exceeding the maximum quota', 102);
876
-						}
877
-						$quota = \OCP\Util::humanFileSize($quota);
878
-					}
879
-				}
880
-				// no else block because quota can be set to 'none' in previous if
881
-				if ($quota === 'none') {
882
-					$allowUnlimitedQuota = $this->config->getAppValue('files', 'allow_unlimited_quota', '1') === '1';
883
-					if (!$allowUnlimitedQuota) {
884
-						throw new OCSException('Unlimited quota is forbidden on this instance', 102);
885
-					}
886
-				}
887
-				$targetUser->setQuota($quota);
888
-				break;
889
-			case self::USER_FIELD_PASSWORD:
890
-				try {
891
-					if (strlen($value) > IUserManager::MAX_PASSWORD_LENGTH) {
892
-						throw new OCSException('Invalid password value', 102);
893
-					}
894
-					if (!$targetUser->canChangePassword()) {
895
-						throw new OCSException('Setting the password is not supported by the users backend', 103);
896
-					}
897
-					$targetUser->setPassword($value);
898
-				} catch (HintException $e) { // password policy error
899
-					throw new OCSException($e->getMessage(), 103);
900
-				}
901
-				break;
902
-			case self::USER_FIELD_LANGUAGE:
903
-				$languagesCodes = $this->l10nFactory->findAvailableLanguages();
904
-				if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
905
-					throw new OCSException('Invalid language', 102);
906
-				}
907
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
908
-				break;
909
-			case self::USER_FIELD_LOCALE:
910
-				if (!$this->l10nFactory->localeExists($value)) {
911
-					throw new OCSException('Invalid locale', 102);
912
-				}
913
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value);
914
-				break;
915
-			case self::USER_FIELD_NOTIFICATION_EMAIL:
916
-				$success = false;
917
-				if ($value === '' || filter_var($value, FILTER_VALIDATE_EMAIL)) {
918
-					try {
919
-						$targetUser->setPrimaryEMailAddress($value);
920
-						$success = true;
921
-					} catch (InvalidArgumentException $e) {
922
-						$this->logger->info(
923
-							'Cannot set primary email, because provided address is not verified',
924
-							[
925
-								'app' => 'provisioning_api',
926
-								'exception' => $e,
927
-							]
928
-						);
929
-					}
930
-				}
931
-				if (!$success) {
932
-					throw new OCSException('', 102);
933
-				}
934
-				break;
935
-			case IAccountManager::PROPERTY_EMAIL:
936
-				if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
937
-					$targetUser->setEMailAddress($value);
938
-				} else {
939
-					throw new OCSException('', 102);
940
-				}
941
-				break;
942
-			case IAccountManager::COLLECTION_EMAIL:
943
-				if (filter_var($value, FILTER_VALIDATE_EMAIL) && $value !== $targetUser->getSystemEMailAddress()) {
944
-					$userAccount = $this->accountManager->getAccount($targetUser);
945
-					$mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
946
-					foreach ($mailCollection->getProperties() as $property) {
947
-						if ($property->getValue() === $value) {
948
-							break;
949
-						}
950
-					}
951
-					$mailCollection->addPropertyWithDefaults($value);
952
-					$this->accountManager->updateAccount($userAccount);
953
-				} else {
954
-					throw new OCSException('', 102);
955
-				}
956
-				break;
957
-			case IAccountManager::PROPERTY_PHONE:
958
-			case IAccountManager::PROPERTY_ADDRESS:
959
-			case IAccountManager::PROPERTY_WEBSITE:
960
-			case IAccountManager::PROPERTY_TWITTER:
961
-			case IAccountManager::PROPERTY_FEDIVERSE:
962
-			case IAccountManager::PROPERTY_ORGANISATION:
963
-			case IAccountManager::PROPERTY_ROLE:
964
-			case IAccountManager::PROPERTY_HEADLINE:
965
-			case IAccountManager::PROPERTY_BIOGRAPHY:
966
-				$userAccount = $this->accountManager->getAccount($targetUser);
967
-				try {
968
-					$userProperty = $userAccount->getProperty($key);
969
-					if ($userProperty->getValue() !== $value) {
970
-						try {
971
-							$userProperty->setValue($value);
972
-							if ($userProperty->getName() === IAccountManager::PROPERTY_PHONE) {
973
-								$this->knownUserService->deleteByContactUserId($targetUser->getUID());
974
-							}
975
-						} catch (InvalidArgumentException $e) {
976
-							throw new OCSException('Invalid ' . $e->getMessage(), 102);
977
-						}
978
-					}
979
-				} catch (PropertyDoesNotExistException $e) {
980
-					$userAccount->setProperty($key, $value, IAccountManager::SCOPE_PRIVATE, IAccountManager::NOT_VERIFIED);
981
-				}
982
-				try {
983
-					$this->accountManager->updateAccount($userAccount);
984
-				} catch (InvalidArgumentException $e) {
985
-					throw new OCSException('Invalid ' . $e->getMessage(), 102);
986
-				}
987
-				break;
988
-			case IAccountManager::PROPERTY_PROFILE_ENABLED:
989
-				$userAccount = $this->accountManager->getAccount($targetUser);
990
-				try {
991
-					$userProperty = $userAccount->getProperty($key);
992
-					if ($userProperty->getValue() !== $value) {
993
-						$userProperty->setValue($value);
994
-					}
995
-				} catch (PropertyDoesNotExistException $e) {
996
-					$userAccount->setProperty($key, $value, IAccountManager::SCOPE_LOCAL, IAccountManager::NOT_VERIFIED);
997
-				}
998
-				$this->accountManager->updateAccount($userAccount);
999
-				break;
1000
-			case IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX:
1001
-			case IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX:
1002
-			case IAccountManager::PROPERTY_PHONE . self::SCOPE_SUFFIX:
1003
-			case IAccountManager::PROPERTY_ADDRESS . self::SCOPE_SUFFIX:
1004
-			case IAccountManager::PROPERTY_WEBSITE . self::SCOPE_SUFFIX:
1005
-			case IAccountManager::PROPERTY_TWITTER . self::SCOPE_SUFFIX:
1006
-			case IAccountManager::PROPERTY_FEDIVERSE . self::SCOPE_SUFFIX:
1007
-			case IAccountManager::PROPERTY_ORGANISATION . self::SCOPE_SUFFIX:
1008
-			case IAccountManager::PROPERTY_ROLE . self::SCOPE_SUFFIX:
1009
-			case IAccountManager::PROPERTY_HEADLINE . self::SCOPE_SUFFIX:
1010
-			case IAccountManager::PROPERTY_BIOGRAPHY . self::SCOPE_SUFFIX:
1011
-			case IAccountManager::PROPERTY_PROFILE_ENABLED . self::SCOPE_SUFFIX:
1012
-			case IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX:
1013
-				$propertyName = substr($key, 0, strlen($key) - strlen(self::SCOPE_SUFFIX));
1014
-				$userAccount = $this->accountManager->getAccount($targetUser);
1015
-				$userProperty = $userAccount->getProperty($propertyName);
1016
-				if ($userProperty->getScope() !== $value) {
1017
-					try {
1018
-						$userProperty->setScope($value);
1019
-						$this->accountManager->updateAccount($userAccount);
1020
-					} catch (InvalidArgumentException $e) {
1021
-						throw new OCSException('Invalid ' . $e->getMessage(), 102);
1022
-					}
1023
-				}
1024
-				break;
1025
-			default:
1026
-				throw new OCSException('', 103);
1027
-		}
1028
-		return new DataResponse();
1029
-	}
1030
-
1031
-	/**
1032
-	 * @PasswordConfirmationRequired
1033
-	 * @NoAdminRequired
1034
-	 *
1035
-	 * @param string $userId
1036
-	 *
1037
-	 * @return DataResponse
1038
-	 *
1039
-	 * @throws OCSException
1040
-	 */
1041
-	public function wipeUserDevices(string $userId): DataResponse {
1042
-		/** @var IUser $currentLoggedInUser */
1043
-		$currentLoggedInUser = $this->userSession->getUser();
1044
-
1045
-		$targetUser = $this->userManager->get($userId);
1046
-
1047
-		if ($targetUser === null) {
1048
-			throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1049
-		}
1050
-
1051
-		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
1052
-			throw new OCSException('', 101);
1053
-		}
1054
-
1055
-		// If not permitted
1056
-		$subAdminManager = $this->groupManager->getSubAdmin();
1057
-		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
1058
-			throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1059
-		}
1060
-
1061
-		$this->remoteWipe->markAllTokensForWipe($targetUser);
1062
-
1063
-		return new DataResponse();
1064
-	}
1065
-
1066
-	/**
1067
-	 * @PasswordConfirmationRequired
1068
-	 * @NoAdminRequired
1069
-	 *
1070
-	 * @param string $userId
1071
-	 * @return DataResponse
1072
-	 * @throws OCSException
1073
-	 */
1074
-	public function deleteUser(string $userId): DataResponse {
1075
-		$currentLoggedInUser = $this->userSession->getUser();
1076
-
1077
-		$targetUser = $this->userManager->get($userId);
1078
-
1079
-		if ($targetUser === null) {
1080
-			throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1081
-		}
1082
-
1083
-		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
1084
-			throw new OCSException('', 101);
1085
-		}
1086
-
1087
-		// If not permitted
1088
-		$subAdminManager = $this->groupManager->getSubAdmin();
1089
-		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
1090
-			throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1091
-		}
1092
-
1093
-		// Go ahead with the delete
1094
-		if ($targetUser->delete()) {
1095
-			return new DataResponse();
1096
-		} else {
1097
-			throw new OCSException('', 101);
1098
-		}
1099
-	}
1100
-
1101
-	/**
1102
-	 * @PasswordConfirmationRequired
1103
-	 * @NoAdminRequired
1104
-	 *
1105
-	 * @param string $userId
1106
-	 * @return DataResponse
1107
-	 * @throws OCSException
1108
-	 * @throws OCSForbiddenException
1109
-	 */
1110
-	public function disableUser(string $userId): DataResponse {
1111
-		return $this->setEnabled($userId, false);
1112
-	}
1113
-
1114
-	/**
1115
-	 * @PasswordConfirmationRequired
1116
-	 * @NoAdminRequired
1117
-	 *
1118
-	 * @param string $userId
1119
-	 * @return DataResponse
1120
-	 * @throws OCSException
1121
-	 * @throws OCSForbiddenException
1122
-	 */
1123
-	public function enableUser(string $userId): DataResponse {
1124
-		return $this->setEnabled($userId, true);
1125
-	}
1126
-
1127
-	/**
1128
-	 * @param string $userId
1129
-	 * @param bool $value
1130
-	 * @return DataResponse
1131
-	 * @throws OCSException
1132
-	 */
1133
-	private function setEnabled(string $userId, bool $value): DataResponse {
1134
-		$currentLoggedInUser = $this->userSession->getUser();
1135
-
1136
-		$targetUser = $this->userManager->get($userId);
1137
-		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
1138
-			throw new OCSException('', 101);
1139
-		}
1140
-
1141
-		// If not permitted
1142
-		$subAdminManager = $this->groupManager->getSubAdmin();
1143
-		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
1144
-			throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1145
-		}
1146
-
1147
-		// enable/disable the user now
1148
-		$targetUser->setEnabled($value);
1149
-		return new DataResponse();
1150
-	}
1151
-
1152
-	/**
1153
-	 * @NoAdminRequired
1154
-	 * @NoSubAdminRequired
1155
-	 *
1156
-	 * @param string $userId
1157
-	 * @return DataResponse
1158
-	 * @throws OCSException
1159
-	 */
1160
-	public function getUsersGroups(string $userId): DataResponse {
1161
-		$loggedInUser = $this->userSession->getUser();
1162
-
1163
-		$targetUser = $this->userManager->get($userId);
1164
-		if ($targetUser === null) {
1165
-			throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1166
-		}
1167
-
1168
-		if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
1169
-			// Self lookup or admin lookup
1170
-			return new DataResponse([
1171
-				'groups' => $this->groupManager->getUserGroupIds($targetUser)
1172
-			]);
1173
-		} else {
1174
-			$subAdminManager = $this->groupManager->getSubAdmin();
1175
-
1176
-			// Looking up someone else
1177
-			if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
1178
-				// Return the group that the method caller is subadmin of for the user in question
1179
-				/** @var IGroup[] $getSubAdminsGroups */
1180
-				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
1181
-				foreach ($getSubAdminsGroups as $key => $group) {
1182
-					$getSubAdminsGroups[$key] = $group->getGID();
1183
-				}
1184
-				$groups = array_intersect(
1185
-					$getSubAdminsGroups,
1186
-					$this->groupManager->getUserGroupIds($targetUser)
1187
-				);
1188
-				return new DataResponse(['groups' => $groups]);
1189
-			} else {
1190
-				// Not permitted
1191
-				throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1192
-			}
1193
-		}
1194
-	}
1195
-
1196
-	/**
1197
-	 * @PasswordConfirmationRequired
1198
-	 * @NoAdminRequired
1199
-	 *
1200
-	 * @param string $userId
1201
-	 * @param string $groupid
1202
-	 * @return DataResponse
1203
-	 * @throws OCSException
1204
-	 */
1205
-	public function addToGroup(string $userId, string $groupid = ''): DataResponse {
1206
-		if ($groupid === '') {
1207
-			throw new OCSException('', 101);
1208
-		}
1209
-
1210
-		$group = $this->groupManager->get($groupid);
1211
-		$targetUser = $this->userManager->get($userId);
1212
-		if ($group === null) {
1213
-			throw new OCSException('', 102);
1214
-		}
1215
-		if ($targetUser === null) {
1216
-			throw new OCSException('', 103);
1217
-		}
1218
-
1219
-		// If they're not an admin, check they are a subadmin of the group in question
1220
-		$loggedInUser = $this->userSession->getUser();
1221
-		$subAdminManager = $this->groupManager->getSubAdmin();
1222
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
1223
-			throw new OCSException('', 104);
1224
-		}
1225
-
1226
-		// Add user to group
1227
-		$group->addUser($targetUser);
1228
-		return new DataResponse();
1229
-	}
1230
-
1231
-	/**
1232
-	 * @PasswordConfirmationRequired
1233
-	 * @NoAdminRequired
1234
-	 *
1235
-	 * @param string $userId
1236
-	 * @param string $groupid
1237
-	 * @return DataResponse
1238
-	 * @throws OCSException
1239
-	 */
1240
-	public function removeFromGroup(string $userId, string $groupid): DataResponse {
1241
-		$loggedInUser = $this->userSession->getUser();
1242
-
1243
-		if ($groupid === null || trim($groupid) === '') {
1244
-			throw new OCSException('', 101);
1245
-		}
1246
-
1247
-		$group = $this->groupManager->get($groupid);
1248
-		if ($group === null) {
1249
-			throw new OCSException('', 102);
1250
-		}
1251
-
1252
-		$targetUser = $this->userManager->get($userId);
1253
-		if ($targetUser === null) {
1254
-			throw new OCSException('', 103);
1255
-		}
1256
-
1257
-		// If they're not an admin, check they are a subadmin of the group in question
1258
-		$subAdminManager = $this->groupManager->getSubAdmin();
1259
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
1260
-			throw new OCSException('', 104);
1261
-		}
1262
-
1263
-		// Check they aren't removing themselves from 'admin' or their 'subadmin; group
1264
-		if ($targetUser->getUID() === $loggedInUser->getUID()) {
1265
-			if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
1266
-				if ($group->getGID() === 'admin') {
1267
-					throw new OCSException('Cannot remove yourself from the admin group', 105);
1268
-				}
1269
-			} else {
1270
-				// Not an admin, so the user must be a subadmin of this group, but that is not allowed.
1271
-				throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
1272
-			}
1273
-		} elseif (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
1274
-			/** @var IGroup[] $subAdminGroups */
1275
-			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
1276
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
1277
-				return $subAdminGroup->getGID();
1278
-			}, $subAdminGroups);
1279
-			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
1280
-			$userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
1281
-
1282
-			if (count($userSubAdminGroups) <= 1) {
1283
-				// Subadmin must not be able to remove a user from all their subadmin groups.
1284
-				throw new OCSException('Not viable to remove user from the last group you are SubAdmin of', 105);
1285
-			}
1286
-		}
1287
-
1288
-		// Remove user from group
1289
-		$group->removeUser($targetUser);
1290
-		return new DataResponse();
1291
-	}
1292
-
1293
-	/**
1294
-	 * Creates a subadmin
1295
-	 *
1296
-	 * @PasswordConfirmationRequired
1297
-	 *
1298
-	 * @param string $userId
1299
-	 * @param string $groupid
1300
-	 * @return DataResponse
1301
-	 * @throws OCSException
1302
-	 */
1303
-	public function addSubAdmin(string $userId, string $groupid): DataResponse {
1304
-		$group = $this->groupManager->get($groupid);
1305
-		$user = $this->userManager->get($userId);
1306
-
1307
-		// Check if the user exists
1308
-		if ($user === null) {
1309
-			throw new OCSException('User does not exist', 101);
1310
-		}
1311
-		// Check if group exists
1312
-		if ($group === null) {
1313
-			throw new OCSException('Group does not exist', 102);
1314
-		}
1315
-		// Check if trying to make subadmin of admin group
1316
-		if ($group->getGID() === 'admin') {
1317
-			throw new OCSException('Cannot create subadmins for admin group', 103);
1318
-		}
1319
-
1320
-		$subAdminManager = $this->groupManager->getSubAdmin();
1321
-
1322
-		// We cannot be subadmin twice
1323
-		if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
1324
-			return new DataResponse();
1325
-		}
1326
-		// Go
1327
-		$subAdminManager->createSubAdmin($user, $group);
1328
-		return new DataResponse();
1329
-	}
1330
-
1331
-	/**
1332
-	 * Removes a subadmin from a group
1333
-	 *
1334
-	 * @PasswordConfirmationRequired
1335
-	 *
1336
-	 * @param string $userId
1337
-	 * @param string $groupid
1338
-	 * @return DataResponse
1339
-	 * @throws OCSException
1340
-	 */
1341
-	public function removeSubAdmin(string $userId, string $groupid): DataResponse {
1342
-		$group = $this->groupManager->get($groupid);
1343
-		$user = $this->userManager->get($userId);
1344
-		$subAdminManager = $this->groupManager->getSubAdmin();
1345
-
1346
-		// Check if the user exists
1347
-		if ($user === null) {
1348
-			throw new OCSException('User does not exist', 101);
1349
-		}
1350
-		// Check if the group exists
1351
-		if ($group === null) {
1352
-			throw new OCSException('Group does not exist', 101);
1353
-		}
1354
-		// Check if they are a subadmin of this said group
1355
-		if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
1356
-			throw new OCSException('User is not a subadmin of this group', 102);
1357
-		}
1358
-
1359
-		// Go
1360
-		$subAdminManager->deleteSubAdmin($user, $group);
1361
-		return new DataResponse();
1362
-	}
1363
-
1364
-	/**
1365
-	 * Get the groups a user is a subadmin of
1366
-	 *
1367
-	 * @param string $userId
1368
-	 * @return DataResponse
1369
-	 * @throws OCSException
1370
-	 */
1371
-	public function getUserSubAdminGroups(string $userId): DataResponse {
1372
-		$groups = $this->getUserSubAdminGroupsData($userId);
1373
-		return new DataResponse($groups);
1374
-	}
1375
-
1376
-	/**
1377
-	 * @NoAdminRequired
1378
-	 * @PasswordConfirmationRequired
1379
-	 *
1380
-	 * resend welcome message
1381
-	 *
1382
-	 * @param string $userId
1383
-	 * @return DataResponse
1384
-	 * @throws OCSException
1385
-	 */
1386
-	public function resendWelcomeMessage(string $userId): DataResponse {
1387
-		$currentLoggedInUser = $this->userSession->getUser();
1388
-
1389
-		$targetUser = $this->userManager->get($userId);
1390
-		if ($targetUser === null) {
1391
-			throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1392
-		}
1393
-
1394
-		// Check if admin / subadmin
1395
-		$subAdminManager = $this->groupManager->getSubAdmin();
1396
-		if (
1397
-			!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
1398
-			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())
1399
-		) {
1400
-			// No rights
1401
-			throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1402
-		}
1403
-
1404
-		$email = $targetUser->getEMailAddress();
1405
-		if ($email === '' || $email === null) {
1406
-			throw new OCSException('Email address not available', 101);
1407
-		}
1408
-
1409
-		try {
1410
-			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
1411
-			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
1412
-		} catch (\Exception $e) {
1413
-			$this->logger->error(
1414
-				"Can't send new user mail to $email",
1415
-				[
1416
-					'app' => 'settings',
1417
-					'exception' => $e,
1418
-				]
1419
-			);
1420
-			throw new OCSException('Sending email failed', 102);
1421
-		}
1422
-
1423
-		return new DataResponse();
1424
-	}
80
+    /** @var IURLGenerator */
81
+    protected $urlGenerator;
82
+    /** @var LoggerInterface */
83
+    private $logger;
84
+    /** @var IFactory */
85
+    protected $l10nFactory;
86
+    /** @var NewUserMailHelper */
87
+    private $newUserMailHelper;
88
+    /** @var ISecureRandom */
89
+    private $secureRandom;
90
+    /** @var RemoteWipe */
91
+    private $remoteWipe;
92
+    /** @var KnownUserService */
93
+    private $knownUserService;
94
+    /** @var IEventDispatcher */
95
+    private $eventDispatcher;
96
+
97
+    public function __construct(
98
+        string $appName,
99
+        IRequest $request,
100
+        IUserManager $userManager,
101
+        IConfig $config,
102
+        IGroupManager $groupManager,
103
+        IUserSession $userSession,
104
+        IAccountManager $accountManager,
105
+        IURLGenerator $urlGenerator,
106
+        LoggerInterface $logger,
107
+        IFactory $l10nFactory,
108
+        NewUserMailHelper $newUserMailHelper,
109
+        ISecureRandom $secureRandom,
110
+        RemoteWipe $remoteWipe,
111
+        KnownUserService $knownUserService,
112
+        IEventDispatcher $eventDispatcher
113
+    ) {
114
+        parent::__construct(
115
+            $appName,
116
+            $request,
117
+            $userManager,
118
+            $config,
119
+            $groupManager,
120
+            $userSession,
121
+            $accountManager,
122
+            $l10nFactory
123
+        );
124
+
125
+        $this->urlGenerator = $urlGenerator;
126
+        $this->logger = $logger;
127
+        $this->l10nFactory = $l10nFactory;
128
+        $this->newUserMailHelper = $newUserMailHelper;
129
+        $this->secureRandom = $secureRandom;
130
+        $this->remoteWipe = $remoteWipe;
131
+        $this->knownUserService = $knownUserService;
132
+        $this->eventDispatcher = $eventDispatcher;
133
+    }
134
+
135
+    /**
136
+     * @NoAdminRequired
137
+     *
138
+     * returns a list of users
139
+     *
140
+     * @param string $search
141
+     * @param int $limit
142
+     * @param int $offset
143
+     * @return DataResponse
144
+     */
145
+    public function getUsers(string $search = '', int $limit = null, int $offset = 0): DataResponse {
146
+        $user = $this->userSession->getUser();
147
+        $users = [];
148
+
149
+        // Admin? Or SubAdmin?
150
+        $uid = $user->getUID();
151
+        $subAdminManager = $this->groupManager->getSubAdmin();
152
+        if ($this->groupManager->isAdmin($uid)) {
153
+            $users = $this->userManager->search($search, $limit, $offset);
154
+        } elseif ($subAdminManager->isSubAdmin($user)) {
155
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
156
+            foreach ($subAdminOfGroups as $key => $group) {
157
+                $subAdminOfGroups[$key] = $group->getGID();
158
+            }
159
+
160
+            $users = [];
161
+            foreach ($subAdminOfGroups as $group) {
162
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
163
+            }
164
+        }
165
+
166
+        $users = array_keys($users);
167
+
168
+        return new DataResponse([
169
+            'users' => $users
170
+        ]);
171
+    }
172
+
173
+    /**
174
+     * @NoAdminRequired
175
+     *
176
+     * returns a list of users and their data
177
+     */
178
+    public function getUsersDetails(string $search = '', int $limit = null, int $offset = 0): DataResponse {
179
+        $currentUser = $this->userSession->getUser();
180
+        $users = [];
181
+
182
+        // Admin? Or SubAdmin?
183
+        $uid = $currentUser->getUID();
184
+        $subAdminManager = $this->groupManager->getSubAdmin();
185
+        if ($this->groupManager->isAdmin($uid)) {
186
+            $users = $this->userManager->search($search, $limit, $offset);
187
+            $users = array_keys($users);
188
+        } elseif ($subAdminManager->isSubAdmin($currentUser)) {
189
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($currentUser);
190
+            foreach ($subAdminOfGroups as $key => $group) {
191
+                $subAdminOfGroups[$key] = $group->getGID();
192
+            }
193
+
194
+            $users = [];
195
+            foreach ($subAdminOfGroups as $group) {
196
+                $users[] = array_keys($this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
197
+            }
198
+            $users = array_merge(...$users);
199
+        }
200
+
201
+        $usersDetails = [];
202
+        foreach ($users as $userId) {
203
+            $userId = (string) $userId;
204
+            $userData = $this->getUserData($userId);
205
+            // Do not insert empty entry
206
+            if (!empty($userData)) {
207
+                $usersDetails[$userId] = $userData;
208
+            } else {
209
+                // Logged user does not have permissions to see this user
210
+                // only showing its id
211
+                $usersDetails[$userId] = ['id' => $userId];
212
+            }
213
+        }
214
+
215
+        return new DataResponse([
216
+            'users' => $usersDetails
217
+        ]);
218
+    }
219
+
220
+
221
+    /**
222
+     * @NoAdminRequired
223
+     * @NoSubAdminRequired
224
+     *
225
+     * @param string $location
226
+     * @param array $search
227
+     * @return DataResponse
228
+     */
229
+    public function searchByPhoneNumbers(string $location, array $search): DataResponse {
230
+        $phoneUtil = PhoneNumberUtil::getInstance();
231
+
232
+        if ($phoneUtil->getCountryCodeForRegion($location) === 0) {
233
+            // Not a valid region code
234
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
235
+        }
236
+
237
+        /** @var IUser $user */
238
+        $user = $this->userSession->getUser();
239
+        $knownTo = $user->getUID();
240
+        $defaultPhoneRegion = $this->config->getSystemValueString('default_phone_region');
241
+
242
+        $normalizedNumberToKey = [];
243
+        foreach ($search as $key => $phoneNumbers) {
244
+            foreach ($phoneNumbers as $phone) {
245
+                try {
246
+                    $phoneNumber = $phoneUtil->parse($phone, $location);
247
+                    if ($phoneNumber instanceof PhoneNumber && $phoneUtil->isValidNumber($phoneNumber)) {
248
+                        $normalizedNumber = $phoneUtil->format($phoneNumber, PhoneNumberFormat::E164);
249
+                        $normalizedNumberToKey[$normalizedNumber] = (string) $key;
250
+                    }
251
+                } catch (NumberParseException $e) {
252
+                }
253
+
254
+                if ($defaultPhoneRegion !== '' && $defaultPhoneRegion !== $location && strpos($phone, '0') === 0) {
255
+                    // If the number has a leading zero (no country code),
256
+                    // we also check the default phone region of the instance,
257
+                    // when it's different to the user's given region.
258
+                    try {
259
+                        $phoneNumber = $phoneUtil->parse($phone, $defaultPhoneRegion);
260
+                        if ($phoneNumber instanceof PhoneNumber && $phoneUtil->isValidNumber($phoneNumber)) {
261
+                            $normalizedNumber = $phoneUtil->format($phoneNumber, PhoneNumberFormat::E164);
262
+                            $normalizedNumberToKey[$normalizedNumber] = (string) $key;
263
+                        }
264
+                    } catch (NumberParseException $e) {
265
+                    }
266
+                }
267
+            }
268
+        }
269
+
270
+        $phoneNumbers = array_keys($normalizedNumberToKey);
271
+
272
+        if (empty($phoneNumbers)) {
273
+            return new DataResponse();
274
+        }
275
+
276
+        // Cleanup all previous entries and only allow new matches
277
+        $this->knownUserService->deleteKnownTo($knownTo);
278
+
279
+        $userMatches = $this->accountManager->searchUsers(IAccountManager::PROPERTY_PHONE, $phoneNumbers);
280
+
281
+        if (empty($userMatches)) {
282
+            return new DataResponse();
283
+        }
284
+
285
+        $cloudUrl = rtrim($this->urlGenerator->getAbsoluteURL('/'), '/');
286
+        if (strpos($cloudUrl, 'http://') === 0) {
287
+            $cloudUrl = substr($cloudUrl, strlen('http://'));
288
+        } elseif (strpos($cloudUrl, 'https://') === 0) {
289
+            $cloudUrl = substr($cloudUrl, strlen('https://'));
290
+        }
291
+
292
+        $matches = [];
293
+        foreach ($userMatches as $phone => $userId) {
294
+            // Not using the ICloudIdManager as that would run a search for each contact to find the display name in the address book
295
+            $matches[$normalizedNumberToKey[$phone]] = $userId . '@' . $cloudUrl;
296
+            $this->knownUserService->storeIsKnownToUser($knownTo, $userId);
297
+        }
298
+
299
+        return new DataResponse($matches);
300
+    }
301
+
302
+    /**
303
+     * @throws OCSException
304
+     */
305
+    private function createNewUserId(): string {
306
+        $attempts = 0;
307
+        do {
308
+            $uidCandidate = $this->secureRandom->generate(10, ISecureRandom::CHAR_HUMAN_READABLE);
309
+            if (!$this->userManager->userExists($uidCandidate)) {
310
+                return $uidCandidate;
311
+            }
312
+            $attempts++;
313
+        } while ($attempts < 10);
314
+        throw new OCSException('Could not create non-existing user id', 111);
315
+    }
316
+
317
+    /**
318
+     * @PasswordConfirmationRequired
319
+     * @NoAdminRequired
320
+     *
321
+     * @param string $userid
322
+     * @param string $password
323
+     * @param string $displayName
324
+     * @param string $email
325
+     * @param array $groups
326
+     * @param array $subadmin
327
+     * @param string $quota
328
+     * @param string $language
329
+     * @return DataResponse
330
+     * @throws OCSException
331
+     */
332
+    public function addUser(
333
+        string $userid,
334
+        string $password = '',
335
+        string $displayName = '',
336
+        string $email = '',
337
+        array $groups = [],
338
+        array $subadmin = [],
339
+        string $quota = '',
340
+        string $language = ''
341
+    ): DataResponse {
342
+        $user = $this->userSession->getUser();
343
+        $isAdmin = $this->groupManager->isAdmin($user->getUID());
344
+        $subAdminManager = $this->groupManager->getSubAdmin();
345
+
346
+        if (empty($userid) && $this->config->getAppValue('core', 'newUser.generateUserID', 'no') === 'yes') {
347
+            $userid = $this->createNewUserId();
348
+        }
349
+
350
+        if ($this->userManager->userExists($userid)) {
351
+            $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
352
+            throw new OCSException($this->l10nFactory->get('provisioning_api')->t('User already exists'), 102);
353
+        }
354
+
355
+        if ($groups !== []) {
356
+            foreach ($groups as $group) {
357
+                if (!$this->groupManager->groupExists($group)) {
358
+                    throw new OCSException('group ' . $group . ' does not exist', 104);
359
+                }
360
+                if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
361
+                    throw new OCSException('insufficient privileges for group ' . $group, 105);
362
+                }
363
+            }
364
+        } else {
365
+            if (!$isAdmin) {
366
+                throw new OCSException('no group specified (required for subadmins)', 106);
367
+            }
368
+        }
369
+
370
+        $subadminGroups = [];
371
+        if ($subadmin !== []) {
372
+            foreach ($subadmin as $groupid) {
373
+                $group = $this->groupManager->get($groupid);
374
+                // Check if group exists
375
+                if ($group === null) {
376
+                    throw new OCSException('Subadmin group does not exist', 102);
377
+                }
378
+                // Check if trying to make subadmin of admin group
379
+                if ($group->getGID() === 'admin') {
380
+                    throw new OCSException('Cannot create subadmins for admin group', 103);
381
+                }
382
+                // Check if has permission to promote subadmins
383
+                if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) {
384
+                    throw new OCSForbiddenException('No permissions to promote subadmins');
385
+                }
386
+                $subadminGroups[] = $group;
387
+            }
388
+        }
389
+
390
+        $generatePasswordResetToken = false;
391
+        if (strlen($password) > IUserManager::MAX_PASSWORD_LENGTH) {
392
+            throw new OCSException('Invalid password value', 101);
393
+        }
394
+        if ($password === '') {
395
+            if ($email === '') {
396
+                throw new OCSException('To send a password link to the user an email address is required.', 108);
397
+            }
398
+
399
+            $passwordEvent = new GenerateSecurePasswordEvent();
400
+            $this->eventDispatcher->dispatchTyped($passwordEvent);
401
+
402
+            $password = $passwordEvent->getPassword();
403
+            if ($password === null) {
404
+                // Fallback: ensure to pass password_policy in any case
405
+                $password = $this->secureRandom->generate(10)
406
+                    . $this->secureRandom->generate(1, ISecureRandom::CHAR_UPPER)
407
+                    . $this->secureRandom->generate(1, ISecureRandom::CHAR_LOWER)
408
+                    . $this->secureRandom->generate(1, ISecureRandom::CHAR_DIGITS)
409
+                    . $this->secureRandom->generate(1, ISecureRandom::CHAR_SYMBOLS);
410
+            }
411
+            $generatePasswordResetToken = true;
412
+        }
413
+
414
+        if ($email === '' && $this->config->getAppValue('core', 'newUser.requireEmail', 'no') === 'yes') {
415
+            throw new OCSException('Required email address was not provided', 110);
416
+        }
417
+
418
+        try {
419
+            $newUser = $this->userManager->createUser($userid, $password);
420
+            $this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
421
+
422
+            foreach ($groups as $group) {
423
+                $this->groupManager->get($group)->addUser($newUser);
424
+                $this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
425
+            }
426
+            foreach ($subadminGroups as $group) {
427
+                $subAdminManager->createSubAdmin($newUser, $group);
428
+            }
429
+
430
+            if ($displayName !== '') {
431
+                try {
432
+                    $this->editUser($userid, self::USER_FIELD_DISPLAYNAME, $displayName);
433
+                } catch (OCSException $e) {
434
+                    if ($newUser instanceof IUser) {
435
+                        $newUser->delete();
436
+                    }
437
+                    throw $e;
438
+                }
439
+            }
440
+
441
+            if ($quota !== '') {
442
+                $this->editUser($userid, self::USER_FIELD_QUOTA, $quota);
443
+            }
444
+
445
+            if ($language !== '') {
446
+                $this->editUser($userid, self::USER_FIELD_LANGUAGE, $language);
447
+            }
448
+
449
+            // Send new user mail only if a mail is set
450
+            if ($email !== '') {
451
+                $newUser->setEMailAddress($email);
452
+                if ($this->config->getAppValue('core', 'newUser.sendEmail', 'yes') === 'yes') {
453
+                    try {
454
+                        $emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
455
+                        $this->newUserMailHelper->sendMail($newUser, $emailTemplate);
456
+                    } catch (\Exception $e) {
457
+                        // Mail could be failing hard or just be plain not configured
458
+                        // Logging error as it is the hardest of the two
459
+                        $this->logger->error(
460
+                            "Unable to send the invitation mail to $email",
461
+                            [
462
+                                'app' => 'ocs_api',
463
+                                'exception' => $e,
464
+                            ]
465
+                        );
466
+                    }
467
+                }
468
+            }
469
+
470
+            return new DataResponse(['id' => $userid]);
471
+        } catch (HintException $e) {
472
+            $this->logger->warning(
473
+                'Failed addUser attempt with hint exception.',
474
+                [
475
+                    'app' => 'ocs_api',
476
+                    'exception' => $e,
477
+                ]
478
+            );
479
+            throw new OCSException($e->getHint(), 107);
480
+        } catch (OCSException $e) {
481
+            $this->logger->warning(
482
+                'Failed addUser attempt with ocs exception.',
483
+                [
484
+                    'app' => 'ocs_api',
485
+                    'exception' => $e,
486
+                ]
487
+            );
488
+            throw $e;
489
+        } catch (InvalidArgumentException $e) {
490
+            $this->logger->error(
491
+                'Failed addUser attempt with invalid argument exception.',
492
+                [
493
+                    'app' => 'ocs_api',
494
+                    'exception' => $e,
495
+                ]
496
+            );
497
+            throw new OCSException($e->getMessage(), 101);
498
+        } catch (\Exception $e) {
499
+            $this->logger->error(
500
+                'Failed addUser attempt with exception.',
501
+                [
502
+                    'app' => 'ocs_api',
503
+                    'exception' => $e
504
+                ]
505
+            );
506
+            throw new OCSException('Bad request', 101);
507
+        }
508
+    }
509
+
510
+    /**
511
+     * @NoAdminRequired
512
+     * @NoSubAdminRequired
513
+     *
514
+     * gets user info
515
+     *
516
+     * @param string $userId
517
+     * @return DataResponse
518
+     * @throws OCSException
519
+     */
520
+    public function getUser(string $userId): DataResponse {
521
+        $includeScopes = false;
522
+        $currentUser = $this->userSession->getUser();
523
+        if ($currentUser && $currentUser->getUID() === $userId) {
524
+            $includeScopes = true;
525
+        }
526
+
527
+        $data = $this->getUserData($userId, $includeScopes);
528
+        // getUserData returns empty array if not enough permissions
529
+        if (empty($data)) {
530
+            throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
531
+        }
532
+        return new DataResponse($data);
533
+    }
534
+
535
+    /**
536
+     * @NoAdminRequired
537
+     * @NoSubAdminRequired
538
+     *
539
+     * gets user info from the currently logged in user
540
+     *
541
+     * @return DataResponse
542
+     * @throws OCSException
543
+     */
544
+    public function getCurrentUser(): DataResponse {
545
+        $user = $this->userSession->getUser();
546
+        if ($user) {
547
+            $data = $this->getUserData($user->getUID(), true);
548
+            // rename "displayname" to "display-name" only for this call to keep
549
+            // the API stable.
550
+            $data['display-name'] = $data['displayname'];
551
+            unset($data['displayname']);
552
+            return new DataResponse($data);
553
+        }
554
+
555
+        throw new OCSException('', OCSController::RESPOND_UNAUTHORISED);
556
+    }
557
+
558
+    /**
559
+     * @NoAdminRequired
560
+     * @NoSubAdminRequired
561
+     *
562
+     * @return DataResponse
563
+     * @throws OCSException
564
+     */
565
+    public function getEditableFields(): DataResponse {
566
+        $currentLoggedInUser = $this->userSession->getUser();
567
+        if (!$currentLoggedInUser instanceof IUser) {
568
+            throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
569
+        }
570
+
571
+        return $this->getEditableFieldsForUser($currentLoggedInUser->getUID());
572
+    }
573
+
574
+    /**
575
+     * @NoAdminRequired
576
+     * @NoSubAdminRequired
577
+     *
578
+     * @param string $userId
579
+     * @return DataResponse
580
+     * @throws OCSException
581
+     */
582
+    public function getEditableFieldsForUser(string $userId): DataResponse {
583
+        $currentLoggedInUser = $this->userSession->getUser();
584
+        if (!$currentLoggedInUser instanceof IUser) {
585
+            throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
586
+        }
587
+
588
+        $permittedFields = [];
589
+
590
+        if ($userId !== $currentLoggedInUser->getUID()) {
591
+            $targetUser = $this->userManager->get($userId);
592
+            if (!$targetUser instanceof IUser) {
593
+                throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
594
+            }
595
+
596
+            $subAdminManager = $this->groupManager->getSubAdmin();
597
+            if (
598
+                !$this->groupManager->isAdmin($currentLoggedInUser->getUID())
599
+                && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
600
+            ) {
601
+                throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
602
+            }
603
+        } else {
604
+            $targetUser = $currentLoggedInUser;
605
+        }
606
+
607
+        // Editing self (display, email)
608
+        if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
609
+            if (
610
+                $targetUser->getBackend() instanceof ISetDisplayNameBackend
611
+                || $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME)
612
+            ) {
613
+                $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME;
614
+            }
615
+            $permittedFields[] = IAccountManager::PROPERTY_EMAIL;
616
+        }
617
+
618
+        $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
619
+        $permittedFields[] = IAccountManager::PROPERTY_PHONE;
620
+        $permittedFields[] = IAccountManager::PROPERTY_ADDRESS;
621
+        $permittedFields[] = IAccountManager::PROPERTY_WEBSITE;
622
+        $permittedFields[] = IAccountManager::PROPERTY_TWITTER;
623
+        $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE;
624
+        $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION;
625
+        $permittedFields[] = IAccountManager::PROPERTY_ROLE;
626
+        $permittedFields[] = IAccountManager::PROPERTY_HEADLINE;
627
+        $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY;
628
+        $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED;
629
+
630
+        return new DataResponse($permittedFields);
631
+    }
632
+
633
+    /**
634
+     * @NoAdminRequired
635
+     * @NoSubAdminRequired
636
+     * @PasswordConfirmationRequired
637
+     *
638
+     * @throws OCSException
639
+     */
640
+    public function editUserMultiValue(
641
+        string $userId,
642
+        string $collectionName,
643
+        string $key,
644
+        string $value
645
+    ): DataResponse {
646
+        $currentLoggedInUser = $this->userSession->getUser();
647
+        if ($currentLoggedInUser === null) {
648
+            throw new OCSException('', OCSController::RESPOND_UNAUTHORISED);
649
+        }
650
+
651
+        $targetUser = $this->userManager->get($userId);
652
+        if ($targetUser === null) {
653
+            throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
654
+        }
655
+
656
+        $subAdminManager = $this->groupManager->getSubAdmin();
657
+        $isAdminOrSubadmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID())
658
+            || $subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser);
659
+
660
+        $permittedFields = [];
661
+        if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
662
+            // Editing self (display, email)
663
+            $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
664
+            $permittedFields[] = IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX;
665
+        } else {
666
+            // Check if admin / subadmin
667
+            if ($isAdminOrSubadmin) {
668
+                // They have permissions over the user
669
+                $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
670
+            } else {
671
+                // No rights
672
+                throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
673
+            }
674
+        }
675
+
676
+        // Check if permitted to edit this field
677
+        if (!in_array($collectionName, $permittedFields)) {
678
+            throw new OCSException('', 103);
679
+        }
680
+
681
+        switch ($collectionName) {
682
+            case IAccountManager::COLLECTION_EMAIL:
683
+                $userAccount = $this->accountManager->getAccount($targetUser);
684
+                $mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
685
+                $mailCollection->removePropertyByValue($key);
686
+                if ($value !== '') {
687
+                    $mailCollection->addPropertyWithDefaults($value);
688
+                    $property = $mailCollection->getPropertyByValue($key);
689
+                    if ($isAdminOrSubadmin && $property) {
690
+                        // admin set mails are auto-verified
691
+                        $property->setLocallyVerified(IAccountManager::VERIFIED);
692
+                    }
693
+                }
694
+                $this->accountManager->updateAccount($userAccount);
695
+                break;
696
+
697
+            case IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX:
698
+                $userAccount = $this->accountManager->getAccount($targetUser);
699
+                $mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
700
+                $targetProperty = null;
701
+                foreach ($mailCollection->getProperties() as $property) {
702
+                    if ($property->getValue() === $key) {
703
+                        $targetProperty = $property;
704
+                        break;
705
+                    }
706
+                }
707
+                if ($targetProperty instanceof IAccountProperty) {
708
+                    try {
709
+                        $targetProperty->setScope($value);
710
+                        $this->accountManager->updateAccount($userAccount);
711
+                    } catch (InvalidArgumentException $e) {
712
+                        throw new OCSException('', 102);
713
+                    }
714
+                } else {
715
+                    throw new OCSException('', 102);
716
+                }
717
+                break;
718
+
719
+            default:
720
+                throw new OCSException('', 103);
721
+        }
722
+        return new DataResponse();
723
+    }
724
+
725
+    /**
726
+     * @NoAdminRequired
727
+     * @NoSubAdminRequired
728
+     * @PasswordConfirmationRequired
729
+     *
730
+     * edit users
731
+     *
732
+     * @param string $userId
733
+     * @param string $key
734
+     * @param string $value
735
+     * @return DataResponse
736
+     * @throws OCSException
737
+     */
738
+    public function editUser(string $userId, string $key, string $value): DataResponse {
739
+        $currentLoggedInUser = $this->userSession->getUser();
740
+
741
+        $targetUser = $this->userManager->get($userId);
742
+        if ($targetUser === null) {
743
+            throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
744
+        }
745
+
746
+        $permittedFields = [];
747
+        if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
748
+            // Editing self (display, email)
749
+            if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
750
+                if (
751
+                    $targetUser->getBackend() instanceof ISetDisplayNameBackend
752
+                    || $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME)
753
+                ) {
754
+                    $permittedFields[] = self::USER_FIELD_DISPLAYNAME;
755
+                    $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME;
756
+                }
757
+                $permittedFields[] = IAccountManager::PROPERTY_EMAIL;
758
+            }
759
+
760
+            $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX;
761
+            $permittedFields[] = IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX;
762
+
763
+            $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
764
+
765
+            $permittedFields[] = self::USER_FIELD_PASSWORD;
766
+            $permittedFields[] = self::USER_FIELD_NOTIFICATION_EMAIL;
767
+            if (
768
+                $this->config->getSystemValue('force_language', false) === false ||
769
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())
770
+            ) {
771
+                $permittedFields[] = self::USER_FIELD_LANGUAGE;
772
+            }
773
+
774
+            if (
775
+                $this->config->getSystemValue('force_locale', false) === false ||
776
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())
777
+            ) {
778
+                $permittedFields[] = self::USER_FIELD_LOCALE;
779
+            }
780
+
781
+            $permittedFields[] = IAccountManager::PROPERTY_PHONE;
782
+            $permittedFields[] = IAccountManager::PROPERTY_ADDRESS;
783
+            $permittedFields[] = IAccountManager::PROPERTY_WEBSITE;
784
+            $permittedFields[] = IAccountManager::PROPERTY_TWITTER;
785
+            $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE;
786
+            $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION;
787
+            $permittedFields[] = IAccountManager::PROPERTY_ROLE;
788
+            $permittedFields[] = IAccountManager::PROPERTY_HEADLINE;
789
+            $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY;
790
+            $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED;
791
+            $permittedFields[] = IAccountManager::PROPERTY_PHONE . self::SCOPE_SUFFIX;
792
+            $permittedFields[] = IAccountManager::PROPERTY_ADDRESS . self::SCOPE_SUFFIX;
793
+            $permittedFields[] = IAccountManager::PROPERTY_WEBSITE . self::SCOPE_SUFFIX;
794
+            $permittedFields[] = IAccountManager::PROPERTY_TWITTER . self::SCOPE_SUFFIX;
795
+            $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE . self::SCOPE_SUFFIX;
796
+            $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION . self::SCOPE_SUFFIX;
797
+            $permittedFields[] = IAccountManager::PROPERTY_ROLE . self::SCOPE_SUFFIX;
798
+            $permittedFields[] = IAccountManager::PROPERTY_HEADLINE . self::SCOPE_SUFFIX;
799
+            $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY . self::SCOPE_SUFFIX;
800
+            $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED . self::SCOPE_SUFFIX;
801
+
802
+            $permittedFields[] = IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX;
803
+
804
+            // If admin they can edit their own quota
805
+            if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
806
+                $permittedFields[] = self::USER_FIELD_QUOTA;
807
+            }
808
+        } else {
809
+            // Check if admin / subadmin
810
+            $subAdminManager = $this->groupManager->getSubAdmin();
811
+            if (
812
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())
813
+                || $subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
814
+            ) {
815
+                // They have permissions over the user
816
+                if (
817
+                    $targetUser->getBackend() instanceof ISetDisplayNameBackend
818
+                    || $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME)
819
+                ) {
820
+                    $permittedFields[] = self::USER_FIELD_DISPLAYNAME;
821
+                    $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME;
822
+                }
823
+                $permittedFields[] = IAccountManager::PROPERTY_EMAIL;
824
+                $permittedFields[] = IAccountManager::COLLECTION_EMAIL;
825
+                $permittedFields[] = self::USER_FIELD_PASSWORD;
826
+                $permittedFields[] = self::USER_FIELD_LANGUAGE;
827
+                $permittedFields[] = self::USER_FIELD_LOCALE;
828
+                $permittedFields[] = IAccountManager::PROPERTY_PHONE;
829
+                $permittedFields[] = IAccountManager::PROPERTY_ADDRESS;
830
+                $permittedFields[] = IAccountManager::PROPERTY_WEBSITE;
831
+                $permittedFields[] = IAccountManager::PROPERTY_TWITTER;
832
+                $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE;
833
+                $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION;
834
+                $permittedFields[] = IAccountManager::PROPERTY_ROLE;
835
+                $permittedFields[] = IAccountManager::PROPERTY_HEADLINE;
836
+                $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY;
837
+                $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED;
838
+                $permittedFields[] = self::USER_FIELD_QUOTA;
839
+                $permittedFields[] = self::USER_FIELD_NOTIFICATION_EMAIL;
840
+            } else {
841
+                // No rights
842
+                throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
843
+            }
844
+        }
845
+        // Check if permitted to edit this field
846
+        if (!in_array($key, $permittedFields)) {
847
+            throw new OCSException('', 103);
848
+        }
849
+        // Process the edit
850
+        switch ($key) {
851
+            case self::USER_FIELD_DISPLAYNAME:
852
+            case IAccountManager::PROPERTY_DISPLAYNAME:
853
+                try {
854
+                    $targetUser->setDisplayName($value);
855
+                } catch (InvalidArgumentException $e) {
856
+                    throw new OCSException($e->getMessage(), 101);
857
+                }
858
+                break;
859
+            case self::USER_FIELD_QUOTA:
860
+                $quota = $value;
861
+                if ($quota !== 'none' && $quota !== 'default') {
862
+                    if (is_numeric($quota)) {
863
+                        $quota = (float) $quota;
864
+                    } else {
865
+                        $quota = \OCP\Util::computerFileSize($quota);
866
+                    }
867
+                    if ($quota === false) {
868
+                        throw new OCSException('Invalid quota value ' . $value, 102);
869
+                    }
870
+                    if ($quota === -1) {
871
+                        $quota = 'none';
872
+                    } else {
873
+                        $maxQuota = (int) $this->config->getAppValue('files', 'max_quota', '-1');
874
+                        if ($maxQuota !== -1 && $quota > $maxQuota) {
875
+                            throw new OCSException('Invalid quota value. ' . $value . ' is exceeding the maximum quota', 102);
876
+                        }
877
+                        $quota = \OCP\Util::humanFileSize($quota);
878
+                    }
879
+                }
880
+                // no else block because quota can be set to 'none' in previous if
881
+                if ($quota === 'none') {
882
+                    $allowUnlimitedQuota = $this->config->getAppValue('files', 'allow_unlimited_quota', '1') === '1';
883
+                    if (!$allowUnlimitedQuota) {
884
+                        throw new OCSException('Unlimited quota is forbidden on this instance', 102);
885
+                    }
886
+                }
887
+                $targetUser->setQuota($quota);
888
+                break;
889
+            case self::USER_FIELD_PASSWORD:
890
+                try {
891
+                    if (strlen($value) > IUserManager::MAX_PASSWORD_LENGTH) {
892
+                        throw new OCSException('Invalid password value', 102);
893
+                    }
894
+                    if (!$targetUser->canChangePassword()) {
895
+                        throw new OCSException('Setting the password is not supported by the users backend', 103);
896
+                    }
897
+                    $targetUser->setPassword($value);
898
+                } catch (HintException $e) { // password policy error
899
+                    throw new OCSException($e->getMessage(), 103);
900
+                }
901
+                break;
902
+            case self::USER_FIELD_LANGUAGE:
903
+                $languagesCodes = $this->l10nFactory->findAvailableLanguages();
904
+                if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
905
+                    throw new OCSException('Invalid language', 102);
906
+                }
907
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
908
+                break;
909
+            case self::USER_FIELD_LOCALE:
910
+                if (!$this->l10nFactory->localeExists($value)) {
911
+                    throw new OCSException('Invalid locale', 102);
912
+                }
913
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value);
914
+                break;
915
+            case self::USER_FIELD_NOTIFICATION_EMAIL:
916
+                $success = false;
917
+                if ($value === '' || filter_var($value, FILTER_VALIDATE_EMAIL)) {
918
+                    try {
919
+                        $targetUser->setPrimaryEMailAddress($value);
920
+                        $success = true;
921
+                    } catch (InvalidArgumentException $e) {
922
+                        $this->logger->info(
923
+                            'Cannot set primary email, because provided address is not verified',
924
+                            [
925
+                                'app' => 'provisioning_api',
926
+                                'exception' => $e,
927
+                            ]
928
+                        );
929
+                    }
930
+                }
931
+                if (!$success) {
932
+                    throw new OCSException('', 102);
933
+                }
934
+                break;
935
+            case IAccountManager::PROPERTY_EMAIL:
936
+                if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
937
+                    $targetUser->setEMailAddress($value);
938
+                } else {
939
+                    throw new OCSException('', 102);
940
+                }
941
+                break;
942
+            case IAccountManager::COLLECTION_EMAIL:
943
+                if (filter_var($value, FILTER_VALIDATE_EMAIL) && $value !== $targetUser->getSystemEMailAddress()) {
944
+                    $userAccount = $this->accountManager->getAccount($targetUser);
945
+                    $mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
946
+                    foreach ($mailCollection->getProperties() as $property) {
947
+                        if ($property->getValue() === $value) {
948
+                            break;
949
+                        }
950
+                    }
951
+                    $mailCollection->addPropertyWithDefaults($value);
952
+                    $this->accountManager->updateAccount($userAccount);
953
+                } else {
954
+                    throw new OCSException('', 102);
955
+                }
956
+                break;
957
+            case IAccountManager::PROPERTY_PHONE:
958
+            case IAccountManager::PROPERTY_ADDRESS:
959
+            case IAccountManager::PROPERTY_WEBSITE:
960
+            case IAccountManager::PROPERTY_TWITTER:
961
+            case IAccountManager::PROPERTY_FEDIVERSE:
962
+            case IAccountManager::PROPERTY_ORGANISATION:
963
+            case IAccountManager::PROPERTY_ROLE:
964
+            case IAccountManager::PROPERTY_HEADLINE:
965
+            case IAccountManager::PROPERTY_BIOGRAPHY:
966
+                $userAccount = $this->accountManager->getAccount($targetUser);
967
+                try {
968
+                    $userProperty = $userAccount->getProperty($key);
969
+                    if ($userProperty->getValue() !== $value) {
970
+                        try {
971
+                            $userProperty->setValue($value);
972
+                            if ($userProperty->getName() === IAccountManager::PROPERTY_PHONE) {
973
+                                $this->knownUserService->deleteByContactUserId($targetUser->getUID());
974
+                            }
975
+                        } catch (InvalidArgumentException $e) {
976
+                            throw new OCSException('Invalid ' . $e->getMessage(), 102);
977
+                        }
978
+                    }
979
+                } catch (PropertyDoesNotExistException $e) {
980
+                    $userAccount->setProperty($key, $value, IAccountManager::SCOPE_PRIVATE, IAccountManager::NOT_VERIFIED);
981
+                }
982
+                try {
983
+                    $this->accountManager->updateAccount($userAccount);
984
+                } catch (InvalidArgumentException $e) {
985
+                    throw new OCSException('Invalid ' . $e->getMessage(), 102);
986
+                }
987
+                break;
988
+            case IAccountManager::PROPERTY_PROFILE_ENABLED:
989
+                $userAccount = $this->accountManager->getAccount($targetUser);
990
+                try {
991
+                    $userProperty = $userAccount->getProperty($key);
992
+                    if ($userProperty->getValue() !== $value) {
993
+                        $userProperty->setValue($value);
994
+                    }
995
+                } catch (PropertyDoesNotExistException $e) {
996
+                    $userAccount->setProperty($key, $value, IAccountManager::SCOPE_LOCAL, IAccountManager::NOT_VERIFIED);
997
+                }
998
+                $this->accountManager->updateAccount($userAccount);
999
+                break;
1000
+            case IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX:
1001
+            case IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX:
1002
+            case IAccountManager::PROPERTY_PHONE . self::SCOPE_SUFFIX:
1003
+            case IAccountManager::PROPERTY_ADDRESS . self::SCOPE_SUFFIX:
1004
+            case IAccountManager::PROPERTY_WEBSITE . self::SCOPE_SUFFIX:
1005
+            case IAccountManager::PROPERTY_TWITTER . self::SCOPE_SUFFIX:
1006
+            case IAccountManager::PROPERTY_FEDIVERSE . self::SCOPE_SUFFIX:
1007
+            case IAccountManager::PROPERTY_ORGANISATION . self::SCOPE_SUFFIX:
1008
+            case IAccountManager::PROPERTY_ROLE . self::SCOPE_SUFFIX:
1009
+            case IAccountManager::PROPERTY_HEADLINE . self::SCOPE_SUFFIX:
1010
+            case IAccountManager::PROPERTY_BIOGRAPHY . self::SCOPE_SUFFIX:
1011
+            case IAccountManager::PROPERTY_PROFILE_ENABLED . self::SCOPE_SUFFIX:
1012
+            case IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX:
1013
+                $propertyName = substr($key, 0, strlen($key) - strlen(self::SCOPE_SUFFIX));
1014
+                $userAccount = $this->accountManager->getAccount($targetUser);
1015
+                $userProperty = $userAccount->getProperty($propertyName);
1016
+                if ($userProperty->getScope() !== $value) {
1017
+                    try {
1018
+                        $userProperty->setScope($value);
1019
+                        $this->accountManager->updateAccount($userAccount);
1020
+                    } catch (InvalidArgumentException $e) {
1021
+                        throw new OCSException('Invalid ' . $e->getMessage(), 102);
1022
+                    }
1023
+                }
1024
+                break;
1025
+            default:
1026
+                throw new OCSException('', 103);
1027
+        }
1028
+        return new DataResponse();
1029
+    }
1030
+
1031
+    /**
1032
+     * @PasswordConfirmationRequired
1033
+     * @NoAdminRequired
1034
+     *
1035
+     * @param string $userId
1036
+     *
1037
+     * @return DataResponse
1038
+     *
1039
+     * @throws OCSException
1040
+     */
1041
+    public function wipeUserDevices(string $userId): DataResponse {
1042
+        /** @var IUser $currentLoggedInUser */
1043
+        $currentLoggedInUser = $this->userSession->getUser();
1044
+
1045
+        $targetUser = $this->userManager->get($userId);
1046
+
1047
+        if ($targetUser === null) {
1048
+            throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1049
+        }
1050
+
1051
+        if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
1052
+            throw new OCSException('', 101);
1053
+        }
1054
+
1055
+        // If not permitted
1056
+        $subAdminManager = $this->groupManager->getSubAdmin();
1057
+        if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
1058
+            throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1059
+        }
1060
+
1061
+        $this->remoteWipe->markAllTokensForWipe($targetUser);
1062
+
1063
+        return new DataResponse();
1064
+    }
1065
+
1066
+    /**
1067
+     * @PasswordConfirmationRequired
1068
+     * @NoAdminRequired
1069
+     *
1070
+     * @param string $userId
1071
+     * @return DataResponse
1072
+     * @throws OCSException
1073
+     */
1074
+    public function deleteUser(string $userId): DataResponse {
1075
+        $currentLoggedInUser = $this->userSession->getUser();
1076
+
1077
+        $targetUser = $this->userManager->get($userId);
1078
+
1079
+        if ($targetUser === null) {
1080
+            throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1081
+        }
1082
+
1083
+        if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
1084
+            throw new OCSException('', 101);
1085
+        }
1086
+
1087
+        // If not permitted
1088
+        $subAdminManager = $this->groupManager->getSubAdmin();
1089
+        if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
1090
+            throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1091
+        }
1092
+
1093
+        // Go ahead with the delete
1094
+        if ($targetUser->delete()) {
1095
+            return new DataResponse();
1096
+        } else {
1097
+            throw new OCSException('', 101);
1098
+        }
1099
+    }
1100
+
1101
+    /**
1102
+     * @PasswordConfirmationRequired
1103
+     * @NoAdminRequired
1104
+     *
1105
+     * @param string $userId
1106
+     * @return DataResponse
1107
+     * @throws OCSException
1108
+     * @throws OCSForbiddenException
1109
+     */
1110
+    public function disableUser(string $userId): DataResponse {
1111
+        return $this->setEnabled($userId, false);
1112
+    }
1113
+
1114
+    /**
1115
+     * @PasswordConfirmationRequired
1116
+     * @NoAdminRequired
1117
+     *
1118
+     * @param string $userId
1119
+     * @return DataResponse
1120
+     * @throws OCSException
1121
+     * @throws OCSForbiddenException
1122
+     */
1123
+    public function enableUser(string $userId): DataResponse {
1124
+        return $this->setEnabled($userId, true);
1125
+    }
1126
+
1127
+    /**
1128
+     * @param string $userId
1129
+     * @param bool $value
1130
+     * @return DataResponse
1131
+     * @throws OCSException
1132
+     */
1133
+    private function setEnabled(string $userId, bool $value): DataResponse {
1134
+        $currentLoggedInUser = $this->userSession->getUser();
1135
+
1136
+        $targetUser = $this->userManager->get($userId);
1137
+        if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
1138
+            throw new OCSException('', 101);
1139
+        }
1140
+
1141
+        // If not permitted
1142
+        $subAdminManager = $this->groupManager->getSubAdmin();
1143
+        if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
1144
+            throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1145
+        }
1146
+
1147
+        // enable/disable the user now
1148
+        $targetUser->setEnabled($value);
1149
+        return new DataResponse();
1150
+    }
1151
+
1152
+    /**
1153
+     * @NoAdminRequired
1154
+     * @NoSubAdminRequired
1155
+     *
1156
+     * @param string $userId
1157
+     * @return DataResponse
1158
+     * @throws OCSException
1159
+     */
1160
+    public function getUsersGroups(string $userId): DataResponse {
1161
+        $loggedInUser = $this->userSession->getUser();
1162
+
1163
+        $targetUser = $this->userManager->get($userId);
1164
+        if ($targetUser === null) {
1165
+            throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1166
+        }
1167
+
1168
+        if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
1169
+            // Self lookup or admin lookup
1170
+            return new DataResponse([
1171
+                'groups' => $this->groupManager->getUserGroupIds($targetUser)
1172
+            ]);
1173
+        } else {
1174
+            $subAdminManager = $this->groupManager->getSubAdmin();
1175
+
1176
+            // Looking up someone else
1177
+            if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
1178
+                // Return the group that the method caller is subadmin of for the user in question
1179
+                /** @var IGroup[] $getSubAdminsGroups */
1180
+                $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
1181
+                foreach ($getSubAdminsGroups as $key => $group) {
1182
+                    $getSubAdminsGroups[$key] = $group->getGID();
1183
+                }
1184
+                $groups = array_intersect(
1185
+                    $getSubAdminsGroups,
1186
+                    $this->groupManager->getUserGroupIds($targetUser)
1187
+                );
1188
+                return new DataResponse(['groups' => $groups]);
1189
+            } else {
1190
+                // Not permitted
1191
+                throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1192
+            }
1193
+        }
1194
+    }
1195
+
1196
+    /**
1197
+     * @PasswordConfirmationRequired
1198
+     * @NoAdminRequired
1199
+     *
1200
+     * @param string $userId
1201
+     * @param string $groupid
1202
+     * @return DataResponse
1203
+     * @throws OCSException
1204
+     */
1205
+    public function addToGroup(string $userId, string $groupid = ''): DataResponse {
1206
+        if ($groupid === '') {
1207
+            throw new OCSException('', 101);
1208
+        }
1209
+
1210
+        $group = $this->groupManager->get($groupid);
1211
+        $targetUser = $this->userManager->get($userId);
1212
+        if ($group === null) {
1213
+            throw new OCSException('', 102);
1214
+        }
1215
+        if ($targetUser === null) {
1216
+            throw new OCSException('', 103);
1217
+        }
1218
+
1219
+        // If they're not an admin, check they are a subadmin of the group in question
1220
+        $loggedInUser = $this->userSession->getUser();
1221
+        $subAdminManager = $this->groupManager->getSubAdmin();
1222
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
1223
+            throw new OCSException('', 104);
1224
+        }
1225
+
1226
+        // Add user to group
1227
+        $group->addUser($targetUser);
1228
+        return new DataResponse();
1229
+    }
1230
+
1231
+    /**
1232
+     * @PasswordConfirmationRequired
1233
+     * @NoAdminRequired
1234
+     *
1235
+     * @param string $userId
1236
+     * @param string $groupid
1237
+     * @return DataResponse
1238
+     * @throws OCSException
1239
+     */
1240
+    public function removeFromGroup(string $userId, string $groupid): DataResponse {
1241
+        $loggedInUser = $this->userSession->getUser();
1242
+
1243
+        if ($groupid === null || trim($groupid) === '') {
1244
+            throw new OCSException('', 101);
1245
+        }
1246
+
1247
+        $group = $this->groupManager->get($groupid);
1248
+        if ($group === null) {
1249
+            throw new OCSException('', 102);
1250
+        }
1251
+
1252
+        $targetUser = $this->userManager->get($userId);
1253
+        if ($targetUser === null) {
1254
+            throw new OCSException('', 103);
1255
+        }
1256
+
1257
+        // If they're not an admin, check they are a subadmin of the group in question
1258
+        $subAdminManager = $this->groupManager->getSubAdmin();
1259
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
1260
+            throw new OCSException('', 104);
1261
+        }
1262
+
1263
+        // Check they aren't removing themselves from 'admin' or their 'subadmin; group
1264
+        if ($targetUser->getUID() === $loggedInUser->getUID()) {
1265
+            if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
1266
+                if ($group->getGID() === 'admin') {
1267
+                    throw new OCSException('Cannot remove yourself from the admin group', 105);
1268
+                }
1269
+            } else {
1270
+                // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
1271
+                throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
1272
+            }
1273
+        } elseif (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
1274
+            /** @var IGroup[] $subAdminGroups */
1275
+            $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
1276
+            $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
1277
+                return $subAdminGroup->getGID();
1278
+            }, $subAdminGroups);
1279
+            $userGroups = $this->groupManager->getUserGroupIds($targetUser);
1280
+            $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
1281
+
1282
+            if (count($userSubAdminGroups) <= 1) {
1283
+                // Subadmin must not be able to remove a user from all their subadmin groups.
1284
+                throw new OCSException('Not viable to remove user from the last group you are SubAdmin of', 105);
1285
+            }
1286
+        }
1287
+
1288
+        // Remove user from group
1289
+        $group->removeUser($targetUser);
1290
+        return new DataResponse();
1291
+    }
1292
+
1293
+    /**
1294
+     * Creates a subadmin
1295
+     *
1296
+     * @PasswordConfirmationRequired
1297
+     *
1298
+     * @param string $userId
1299
+     * @param string $groupid
1300
+     * @return DataResponse
1301
+     * @throws OCSException
1302
+     */
1303
+    public function addSubAdmin(string $userId, string $groupid): DataResponse {
1304
+        $group = $this->groupManager->get($groupid);
1305
+        $user = $this->userManager->get($userId);
1306
+
1307
+        // Check if the user exists
1308
+        if ($user === null) {
1309
+            throw new OCSException('User does not exist', 101);
1310
+        }
1311
+        // Check if group exists
1312
+        if ($group === null) {
1313
+            throw new OCSException('Group does not exist', 102);
1314
+        }
1315
+        // Check if trying to make subadmin of admin group
1316
+        if ($group->getGID() === 'admin') {
1317
+            throw new OCSException('Cannot create subadmins for admin group', 103);
1318
+        }
1319
+
1320
+        $subAdminManager = $this->groupManager->getSubAdmin();
1321
+
1322
+        // We cannot be subadmin twice
1323
+        if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
1324
+            return new DataResponse();
1325
+        }
1326
+        // Go
1327
+        $subAdminManager->createSubAdmin($user, $group);
1328
+        return new DataResponse();
1329
+    }
1330
+
1331
+    /**
1332
+     * Removes a subadmin from a group
1333
+     *
1334
+     * @PasswordConfirmationRequired
1335
+     *
1336
+     * @param string $userId
1337
+     * @param string $groupid
1338
+     * @return DataResponse
1339
+     * @throws OCSException
1340
+     */
1341
+    public function removeSubAdmin(string $userId, string $groupid): DataResponse {
1342
+        $group = $this->groupManager->get($groupid);
1343
+        $user = $this->userManager->get($userId);
1344
+        $subAdminManager = $this->groupManager->getSubAdmin();
1345
+
1346
+        // Check if the user exists
1347
+        if ($user === null) {
1348
+            throw new OCSException('User does not exist', 101);
1349
+        }
1350
+        // Check if the group exists
1351
+        if ($group === null) {
1352
+            throw new OCSException('Group does not exist', 101);
1353
+        }
1354
+        // Check if they are a subadmin of this said group
1355
+        if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
1356
+            throw new OCSException('User is not a subadmin of this group', 102);
1357
+        }
1358
+
1359
+        // Go
1360
+        $subAdminManager->deleteSubAdmin($user, $group);
1361
+        return new DataResponse();
1362
+    }
1363
+
1364
+    /**
1365
+     * Get the groups a user is a subadmin of
1366
+     *
1367
+     * @param string $userId
1368
+     * @return DataResponse
1369
+     * @throws OCSException
1370
+     */
1371
+    public function getUserSubAdminGroups(string $userId): DataResponse {
1372
+        $groups = $this->getUserSubAdminGroupsData($userId);
1373
+        return new DataResponse($groups);
1374
+    }
1375
+
1376
+    /**
1377
+     * @NoAdminRequired
1378
+     * @PasswordConfirmationRequired
1379
+     *
1380
+     * resend welcome message
1381
+     *
1382
+     * @param string $userId
1383
+     * @return DataResponse
1384
+     * @throws OCSException
1385
+     */
1386
+    public function resendWelcomeMessage(string $userId): DataResponse {
1387
+        $currentLoggedInUser = $this->userSession->getUser();
1388
+
1389
+        $targetUser = $this->userManager->get($userId);
1390
+        if ($targetUser === null) {
1391
+            throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1392
+        }
1393
+
1394
+        // Check if admin / subadmin
1395
+        $subAdminManager = $this->groupManager->getSubAdmin();
1396
+        if (
1397
+            !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
1398
+            && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())
1399
+        ) {
1400
+            // No rights
1401
+            throw new OCSException('', OCSController::RESPOND_NOT_FOUND);
1402
+        }
1403
+
1404
+        $email = $targetUser->getEMailAddress();
1405
+        if ($email === '' || $email === null) {
1406
+            throw new OCSException('Email address not available', 101);
1407
+        }
1408
+
1409
+        try {
1410
+            $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
1411
+            $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
1412
+        } catch (\Exception $e) {
1413
+            $this->logger->error(
1414
+                "Can't send new user mail to $email",
1415
+                [
1416
+                    'app' => 'settings',
1417
+                    'exception' => $e,
1418
+                ]
1419
+            );
1420
+            throw new OCSException('Sending email failed', 102);
1421
+        }
1422
+
1423
+        return new DataResponse();
1424
+    }
1425 1425
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
 		$matches = [];
293 293
 		foreach ($userMatches as $phone => $userId) {
294 294
 			// Not using the ICloudIdManager as that would run a search for each contact to find the display name in the address book
295
-			$matches[$normalizedNumberToKey[$phone]] = $userId . '@' . $cloudUrl;
295
+			$matches[$normalizedNumberToKey[$phone]] = $userId.'@'.$cloudUrl;
296 296
 			$this->knownUserService->storeIsKnownToUser($knownTo, $userId);
297 297
 		}
298 298
 
@@ -355,10 +355,10 @@  discard block
 block discarded – undo
355 355
 		if ($groups !== []) {
356 356
 			foreach ($groups as $group) {
357 357
 				if (!$this->groupManager->groupExists($group)) {
358
-					throw new OCSException('group ' . $group . ' does not exist', 104);
358
+					throw new OCSException('group '.$group.' does not exist', 104);
359 359
 				}
360 360
 				if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
361
-					throw new OCSException('insufficient privileges for group ' . $group, 105);
361
+					throw new OCSException('insufficient privileges for group '.$group, 105);
362 362
 				}
363 363
 			}
364 364
 		} else {
@@ -417,11 +417,11 @@  discard block
 block discarded – undo
417 417
 
418 418
 		try {
419 419
 			$newUser = $this->userManager->createUser($userid, $password);
420
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
420
+			$this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
421 421
 
422 422
 			foreach ($groups as $group) {
423 423
 				$this->groupManager->get($group)->addUser($newUser);
424
-				$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
424
+				$this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
425 425
 			}
426 426
 			foreach ($subadminGroups as $group) {
427 427
 				$subAdminManager->createSubAdmin($newUser, $group);
@@ -661,7 +661,7 @@  discard block
 block discarded – undo
661 661
 		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
662 662
 			// Editing self (display, email)
663 663
 			$permittedFields[] = IAccountManager::COLLECTION_EMAIL;
664
-			$permittedFields[] = IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX;
664
+			$permittedFields[] = IAccountManager::COLLECTION_EMAIL.self::SCOPE_SUFFIX;
665 665
 		} else {
666 666
 			// Check if admin / subadmin
667 667
 			if ($isAdminOrSubadmin) {
@@ -694,7 +694,7 @@  discard block
 block discarded – undo
694 694
 				$this->accountManager->updateAccount($userAccount);
695 695
 				break;
696 696
 
697
-			case IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX:
697
+			case IAccountManager::COLLECTION_EMAIL.self::SCOPE_SUFFIX:
698 698
 				$userAccount = $this->accountManager->getAccount($targetUser);
699 699
 				$mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL);
700 700
 				$targetProperty = null;
@@ -757,8 +757,8 @@  discard block
 block discarded – undo
757 757
 				$permittedFields[] = IAccountManager::PROPERTY_EMAIL;
758 758
 			}
759 759
 
760
-			$permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX;
761
-			$permittedFields[] = IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX;
760
+			$permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME.self::SCOPE_SUFFIX;
761
+			$permittedFields[] = IAccountManager::PROPERTY_EMAIL.self::SCOPE_SUFFIX;
762 762
 
763 763
 			$permittedFields[] = IAccountManager::COLLECTION_EMAIL;
764 764
 
@@ -788,18 +788,18 @@  discard block
 block discarded – undo
788 788
 			$permittedFields[] = IAccountManager::PROPERTY_HEADLINE;
789 789
 			$permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY;
790 790
 			$permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED;
791
-			$permittedFields[] = IAccountManager::PROPERTY_PHONE . self::SCOPE_SUFFIX;
792
-			$permittedFields[] = IAccountManager::PROPERTY_ADDRESS . self::SCOPE_SUFFIX;
793
-			$permittedFields[] = IAccountManager::PROPERTY_WEBSITE . self::SCOPE_SUFFIX;
794
-			$permittedFields[] = IAccountManager::PROPERTY_TWITTER . self::SCOPE_SUFFIX;
795
-			$permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE . self::SCOPE_SUFFIX;
796
-			$permittedFields[] = IAccountManager::PROPERTY_ORGANISATION . self::SCOPE_SUFFIX;
797
-			$permittedFields[] = IAccountManager::PROPERTY_ROLE . self::SCOPE_SUFFIX;
798
-			$permittedFields[] = IAccountManager::PROPERTY_HEADLINE . self::SCOPE_SUFFIX;
799
-			$permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY . self::SCOPE_SUFFIX;
800
-			$permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED . self::SCOPE_SUFFIX;
801
-
802
-			$permittedFields[] = IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX;
791
+			$permittedFields[] = IAccountManager::PROPERTY_PHONE.self::SCOPE_SUFFIX;
792
+			$permittedFields[] = IAccountManager::PROPERTY_ADDRESS.self::SCOPE_SUFFIX;
793
+			$permittedFields[] = IAccountManager::PROPERTY_WEBSITE.self::SCOPE_SUFFIX;
794
+			$permittedFields[] = IAccountManager::PROPERTY_TWITTER.self::SCOPE_SUFFIX;
795
+			$permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE.self::SCOPE_SUFFIX;
796
+			$permittedFields[] = IAccountManager::PROPERTY_ORGANISATION.self::SCOPE_SUFFIX;
797
+			$permittedFields[] = IAccountManager::PROPERTY_ROLE.self::SCOPE_SUFFIX;
798
+			$permittedFields[] = IAccountManager::PROPERTY_HEADLINE.self::SCOPE_SUFFIX;
799
+			$permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY.self::SCOPE_SUFFIX;
800
+			$permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED.self::SCOPE_SUFFIX;
801
+
802
+			$permittedFields[] = IAccountManager::PROPERTY_AVATAR.self::SCOPE_SUFFIX;
803 803
 
804 804
 			// If admin they can edit their own quota
805 805
 			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
@@ -865,14 +865,14 @@  discard block
 block discarded – undo
865 865
 						$quota = \OCP\Util::computerFileSize($quota);
866 866
 					}
867 867
 					if ($quota === false) {
868
-						throw new OCSException('Invalid quota value ' . $value, 102);
868
+						throw new OCSException('Invalid quota value '.$value, 102);
869 869
 					}
870 870
 					if ($quota === -1) {
871 871
 						$quota = 'none';
872 872
 					} else {
873 873
 						$maxQuota = (int) $this->config->getAppValue('files', 'max_quota', '-1');
874 874
 						if ($maxQuota !== -1 && $quota > $maxQuota) {
875
-							throw new OCSException('Invalid quota value. ' . $value . ' is exceeding the maximum quota', 102);
875
+							throw new OCSException('Invalid quota value. '.$value.' is exceeding the maximum quota', 102);
876 876
 						}
877 877
 						$quota = \OCP\Util::humanFileSize($quota);
878 878
 					}
@@ -973,7 +973,7 @@  discard block
 block discarded – undo
973 973
 								$this->knownUserService->deleteByContactUserId($targetUser->getUID());
974 974
 							}
975 975
 						} catch (InvalidArgumentException $e) {
976
-							throw new OCSException('Invalid ' . $e->getMessage(), 102);
976
+							throw new OCSException('Invalid '.$e->getMessage(), 102);
977 977
 						}
978 978
 					}
979 979
 				} catch (PropertyDoesNotExistException $e) {
@@ -982,7 +982,7 @@  discard block
 block discarded – undo
982 982
 				try {
983 983
 					$this->accountManager->updateAccount($userAccount);
984 984
 				} catch (InvalidArgumentException $e) {
985
-					throw new OCSException('Invalid ' . $e->getMessage(), 102);
985
+					throw new OCSException('Invalid '.$e->getMessage(), 102);
986 986
 				}
987 987
 				break;
988 988
 			case IAccountManager::PROPERTY_PROFILE_ENABLED:
@@ -997,19 +997,19 @@  discard block
 block discarded – undo
997 997
 				}
998 998
 				$this->accountManager->updateAccount($userAccount);
999 999
 				break;
1000
-			case IAccountManager::PROPERTY_DISPLAYNAME . self::SCOPE_SUFFIX:
1001
-			case IAccountManager::PROPERTY_EMAIL . self::SCOPE_SUFFIX:
1002
-			case IAccountManager::PROPERTY_PHONE . self::SCOPE_SUFFIX:
1003
-			case IAccountManager::PROPERTY_ADDRESS . self::SCOPE_SUFFIX:
1004
-			case IAccountManager::PROPERTY_WEBSITE . self::SCOPE_SUFFIX:
1005
-			case IAccountManager::PROPERTY_TWITTER . self::SCOPE_SUFFIX:
1006
-			case IAccountManager::PROPERTY_FEDIVERSE . self::SCOPE_SUFFIX:
1007
-			case IAccountManager::PROPERTY_ORGANISATION . self::SCOPE_SUFFIX:
1008
-			case IAccountManager::PROPERTY_ROLE . self::SCOPE_SUFFIX:
1009
-			case IAccountManager::PROPERTY_HEADLINE . self::SCOPE_SUFFIX:
1010
-			case IAccountManager::PROPERTY_BIOGRAPHY . self::SCOPE_SUFFIX:
1011
-			case IAccountManager::PROPERTY_PROFILE_ENABLED . self::SCOPE_SUFFIX:
1012
-			case IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX:
1000
+			case IAccountManager::PROPERTY_DISPLAYNAME.self::SCOPE_SUFFIX:
1001
+			case IAccountManager::PROPERTY_EMAIL.self::SCOPE_SUFFIX:
1002
+			case IAccountManager::PROPERTY_PHONE.self::SCOPE_SUFFIX:
1003
+			case IAccountManager::PROPERTY_ADDRESS.self::SCOPE_SUFFIX:
1004
+			case IAccountManager::PROPERTY_WEBSITE.self::SCOPE_SUFFIX:
1005
+			case IAccountManager::PROPERTY_TWITTER.self::SCOPE_SUFFIX:
1006
+			case IAccountManager::PROPERTY_FEDIVERSE.self::SCOPE_SUFFIX:
1007
+			case IAccountManager::PROPERTY_ORGANISATION.self::SCOPE_SUFFIX:
1008
+			case IAccountManager::PROPERTY_ROLE.self::SCOPE_SUFFIX:
1009
+			case IAccountManager::PROPERTY_HEADLINE.self::SCOPE_SUFFIX:
1010
+			case IAccountManager::PROPERTY_BIOGRAPHY.self::SCOPE_SUFFIX:
1011
+			case IAccountManager::PROPERTY_PROFILE_ENABLED.self::SCOPE_SUFFIX:
1012
+			case IAccountManager::PROPERTY_AVATAR.self::SCOPE_SUFFIX:
1013 1013
 				$propertyName = substr($key, 0, strlen($key) - strlen(self::SCOPE_SUFFIX));
1014 1014
 				$userAccount = $this->accountManager->getAccount($targetUser);
1015 1015
 				$userProperty = $userAccount->getProperty($propertyName);
@@ -1018,7 +1018,7 @@  discard block
 block discarded – undo
1018 1018
 						$userProperty->setScope($value);
1019 1019
 						$this->accountManager->updateAccount($userAccount);
1020 1020
 					} catch (InvalidArgumentException $e) {
1021
-						throw new OCSException('Invalid ' . $e->getMessage(), 102);
1021
+						throw new OCSException('Invalid '.$e->getMessage(), 102);
1022 1022
 					}
1023 1023
 				}
1024 1024
 				break;
@@ -1273,7 +1273,7 @@  discard block
 block discarded – undo
1273 1273
 		} elseif (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
1274 1274
 			/** @var IGroup[] $subAdminGroups */
1275 1275
 			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
1276
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
1276
+			$subAdminGroups = array_map(function(IGroup $subAdminGroup) {
1277 1277
 				return $subAdminGroup->getGID();
1278 1278
 			}, $subAdminGroups);
1279 1279
 			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
Please login to merge, or discard this patch.
lib/private/User/User.php 2 patches
Indentation   +527 added lines, -527 removed lines patch added patch discarded remove patch
@@ -61,531 +61,531 @@
 block discarded – undo
61 61
 use Symfony\Component\EventDispatcher\GenericEvent;
62 62
 
63 63
 class User implements IUser {
64
-	/** @var IAccountManager */
65
-	protected $accountManager;
66
-	/** @var string */
67
-	private $uid;
68
-
69
-	/** @var string|null */
70
-	private $displayName;
71
-
72
-	/** @var UserInterface|null */
73
-	private $backend;
74
-	/** @var EventDispatcherInterface */
75
-	private $legacyDispatcher;
76
-
77
-	/** @var IEventDispatcher */
78
-	private $dispatcher;
79
-
80
-	/** @var bool|null */
81
-	private $enabled;
82
-
83
-	/** @var Emitter|Manager */
84
-	private $emitter;
85
-
86
-	/** @var string */
87
-	private $home;
88
-
89
-	/** @var int|null */
90
-	private $lastLogin;
91
-
92
-	/** @var \OCP\IConfig */
93
-	private $config;
94
-
95
-	/** @var IAvatarManager */
96
-	private $avatarManager;
97
-
98
-	/** @var IURLGenerator */
99
-	private $urlGenerator;
100
-
101
-	public function __construct(string $uid, ?UserInterface $backend, EventDispatcherInterface $dispatcher, $emitter = null, IConfig $config = null, $urlGenerator = null) {
102
-		$this->uid = $uid;
103
-		$this->backend = $backend;
104
-		$this->legacyDispatcher = $dispatcher;
105
-		$this->emitter = $emitter;
106
-		if (is_null($config)) {
107
-			$config = \OC::$server->getConfig();
108
-		}
109
-		$this->config = $config;
110
-		$this->urlGenerator = $urlGenerator;
111
-		if (is_null($this->urlGenerator)) {
112
-			$this->urlGenerator = \OC::$server->getURLGenerator();
113
-		}
114
-		// TODO: inject
115
-		$this->dispatcher = \OC::$server->query(IEventDispatcher::class);
116
-	}
117
-
118
-	/**
119
-	 * get the user id
120
-	 *
121
-	 * @return string
122
-	 */
123
-	public function getUID() {
124
-		return $this->uid;
125
-	}
126
-
127
-	/**
128
-	 * get the display name for the user, if no specific display name is set it will fallback to the user id
129
-	 *
130
-	 * @return string
131
-	 */
132
-	public function getDisplayName() {
133
-		if ($this->displayName === null) {
134
-			$displayName = '';
135
-			if ($this->backend && $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) {
136
-				// get display name and strip whitespace from the beginning and end of it
137
-				$backendDisplayName = $this->backend->getDisplayName($this->uid);
138
-				if (is_string($backendDisplayName)) {
139
-					$displayName = trim($backendDisplayName);
140
-				}
141
-			}
142
-
143
-			if (!empty($displayName)) {
144
-				$this->displayName = $displayName;
145
-			} else {
146
-				$this->displayName = $this->uid;
147
-			}
148
-		}
149
-		return $this->displayName;
150
-	}
151
-
152
-	/**
153
-	 * set the displayname for the user
154
-	 *
155
-	 * @param string $displayName
156
-	 * @return bool
157
-	 *
158
-	 * @since 25.0.0 Throw InvalidArgumentException
159
-	 * @throws \InvalidArgumentException
160
-	 */
161
-	public function setDisplayName($displayName) {
162
-		$displayName = trim($displayName);
163
-		$oldDisplayName = $this->getDisplayName();
164
-		if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName) && $displayName !== $oldDisplayName) {
165
-			/** @var ISetDisplayNameBackend $backend */
166
-			$backend = $this->backend;
167
-			$result = $backend->setDisplayName($this->uid, $displayName);
168
-			if ($result) {
169
-				$this->displayName = $displayName;
170
-				$this->triggerChange('displayName', $displayName, $oldDisplayName);
171
-			}
172
-			return $result !== false;
173
-		}
174
-		return false;
175
-	}
176
-
177
-	/**
178
-	 * @inheritDoc
179
-	 */
180
-	public function setEMailAddress($mailAddress) {
181
-		$this->setSystemEMailAddress($mailAddress);
182
-	}
183
-
184
-	/**
185
-	 * @inheritDoc
186
-	 */
187
-	public function setSystemEMailAddress(string $mailAddress): void {
188
-		$oldMailAddress = $this->getSystemEMailAddress();
189
-
190
-		if ($mailAddress === '') {
191
-			$this->config->deleteUserValue($this->uid, 'settings', 'email');
192
-		} else {
193
-			$this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
194
-		}
195
-
196
-		$primaryAddress = $this->getPrimaryEMailAddress();
197
-		if ($primaryAddress === $mailAddress) {
198
-			// on match no dedicated primary settings is necessary
199
-			$this->setPrimaryEMailAddress('');
200
-		}
201
-
202
-		if ($oldMailAddress !== strtolower($mailAddress)) {
203
-			$this->triggerChange('eMailAddress', $mailAddress, $oldMailAddress);
204
-		}
205
-	}
206
-
207
-	/**
208
-	 * @inheritDoc
209
-	 */
210
-	public function setPrimaryEMailAddress(string $mailAddress): void {
211
-		if ($mailAddress === '') {
212
-			$this->config->deleteUserValue($this->uid, 'settings', 'primary_email');
213
-			return;
214
-		}
215
-
216
-		$this->ensureAccountManager();
217
-		$account = $this->accountManager->getAccount($this);
218
-		$property = $account->getPropertyCollection(IAccountManager::COLLECTION_EMAIL)
219
-			->getPropertyByValue($mailAddress);
220
-
221
-		if ($property === null || $property->getLocallyVerified() !== IAccountManager::VERIFIED) {
222
-			throw new InvalidArgumentException('Only verified emails can be set as primary');
223
-		}
224
-		$this->config->setUserValue($this->uid, 'settings', 'primary_email', $mailAddress);
225
-	}
226
-
227
-	private function ensureAccountManager() {
228
-		if (!$this->accountManager instanceof IAccountManager) {
229
-			$this->accountManager = \OC::$server->get(IAccountManager::class);
230
-		}
231
-	}
232
-
233
-	/**
234
-	 * returns the timestamp of the user's last login or 0 if the user did never
235
-	 * login
236
-	 *
237
-	 * @return int
238
-	 */
239
-	public function getLastLogin() {
240
-		if ($this->lastLogin === null) {
241
-			$this->lastLogin = (int) $this->config->getUserValue($this->uid, 'login', 'lastLogin', 0);
242
-		}
243
-		return (int) $this->lastLogin;
244
-	}
245
-
246
-	/**
247
-	 * updates the timestamp of the most recent login of this user
248
-	 */
249
-	public function updateLastLoginTimestamp() {
250
-		$previousLogin = $this->getLastLogin();
251
-		$now = time();
252
-		$firstTimeLogin = $previousLogin === 0;
253
-
254
-		if ($now - $previousLogin > 60) {
255
-			$this->lastLogin = time();
256
-			$this->config->setUserValue(
257
-				$this->uid, 'login', 'lastLogin', (string)$this->lastLogin);
258
-		}
259
-
260
-		return $firstTimeLogin;
261
-	}
262
-
263
-	/**
264
-	 * Delete the user
265
-	 *
266
-	 * @return bool
267
-	 */
268
-	public function delete() {
269
-		/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
270
-		$this->legacyDispatcher->dispatch(IUser::class . '::preDelete', new GenericEvent($this));
271
-		if ($this->emitter) {
272
-			/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
273
-			$this->emitter->emit('\OC\User', 'preDelete', [$this]);
274
-		}
275
-		$this->dispatcher->dispatchTyped(new BeforeUserDeletedEvent($this));
276
-		$result = $this->backend->deleteUser($this->uid);
277
-		if ($result) {
278
-			// FIXME: Feels like an hack - suggestions?
279
-
280
-			$groupManager = \OC::$server->getGroupManager();
281
-			// We have to delete the user from all groups
282
-			foreach ($groupManager->getUserGroupIds($this) as $groupId) {
283
-				$group = $groupManager->get($groupId);
284
-				if ($group) {
285
-					$this->dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $this));
286
-					$group->removeUser($this);
287
-					$this->dispatcher->dispatchTyped(new UserRemovedEvent($group, $this));
288
-				}
289
-			}
290
-			// Delete the user's keys in preferences
291
-			\OC::$server->getConfig()->deleteAllUserValues($this->uid);
292
-
293
-			\OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
294
-			\OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
295
-
296
-			/** @var AvatarManager $avatarManager */
297
-			$avatarManager = \OC::$server->query(AvatarManager::class);
298
-			$avatarManager->deleteUserAvatar($this->uid);
299
-
300
-			$notification = \OC::$server->getNotificationManager()->createNotification();
301
-			$notification->setUser($this->uid);
302
-			\OC::$server->getNotificationManager()->markProcessed($notification);
303
-
304
-			/** @var AccountManager $accountManager */
305
-			$accountManager = \OC::$server->query(AccountManager::class);
306
-			$accountManager->deleteUser($this);
307
-
308
-			/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
309
-			$this->legacyDispatcher->dispatch(IUser::class . '::postDelete', new GenericEvent($this));
310
-			if ($this->emitter) {
311
-				/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
312
-				$this->emitter->emit('\OC\User', 'postDelete', [$this]);
313
-			}
314
-			$this->dispatcher->dispatchTyped(new UserDeletedEvent($this));
315
-		}
316
-		return !($result === false);
317
-	}
318
-
319
-	/**
320
-	 * Set the password of the user
321
-	 *
322
-	 * @param string $password
323
-	 * @param string $recoveryPassword for the encryption app to reset encryption keys
324
-	 * @return bool
325
-	 */
326
-	public function setPassword($password, $recoveryPassword = null) {
327
-		$this->legacyDispatcher->dispatch(IUser::class . '::preSetPassword', new GenericEvent($this, [
328
-			'password' => $password,
329
-			'recoveryPassword' => $recoveryPassword,
330
-		]));
331
-		if ($this->emitter) {
332
-			$this->emitter->emit('\OC\User', 'preSetPassword', [$this, $password, $recoveryPassword]);
333
-		}
334
-		if ($this->backend->implementsActions(Backend::SET_PASSWORD)) {
335
-			/** @var ISetPasswordBackend $backend */
336
-			$backend = $this->backend;
337
-			$result = $backend->setPassword($this->uid, $password);
338
-
339
-			if ($result !== false) {
340
-				$this->legacyDispatcher->dispatch(IUser::class . '::postSetPassword', new GenericEvent($this, [
341
-					'password' => $password,
342
-					'recoveryPassword' => $recoveryPassword,
343
-				]));
344
-				if ($this->emitter) {
345
-					$this->emitter->emit('\OC\User', 'postSetPassword', [$this, $password, $recoveryPassword]);
346
-				}
347
-			}
348
-
349
-			return !($result === false);
350
-		} else {
351
-			return false;
352
-		}
353
-	}
354
-
355
-	/**
356
-	 * get the users home folder to mount
357
-	 *
358
-	 * @return string
359
-	 */
360
-	public function getHome() {
361
-		if (!$this->home) {
362
-			/** @psalm-suppress UndefinedInterfaceMethod Once we get rid of the legacy implementsActions, psalm won't complain anymore */
363
-			if (($this->backend instanceof IGetHomeBackend || $this->backend->implementsActions(Backend::GET_HOME)) && $home = $this->backend->getHome($this->uid)) {
364
-				$this->home = $home;
365
-			} elseif ($this->config) {
366
-				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
367
-			} else {
368
-				$this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
369
-			}
370
-		}
371
-		return $this->home;
372
-	}
373
-
374
-	/**
375
-	 * Get the name of the backend class the user is connected with
376
-	 *
377
-	 * @return string
378
-	 */
379
-	public function getBackendClassName() {
380
-		if ($this->backend instanceof IUserBackend) {
381
-			return $this->backend->getBackendName();
382
-		}
383
-		return get_class($this->backend);
384
-	}
385
-
386
-	public function getBackend(): ?UserInterface {
387
-		return $this->backend;
388
-	}
389
-
390
-	/**
391
-	 * Check if the backend allows the user to change his avatar on Personal page
392
-	 *
393
-	 * @return bool
394
-	 */
395
-	public function canChangeAvatar() {
396
-		if ($this->backend instanceof IProvideAvatarBackend || $this->backend->implementsActions(Backend::PROVIDE_AVATAR)) {
397
-			/** @var IProvideAvatarBackend $backend */
398
-			$backend = $this->backend;
399
-			return $backend->canChangeAvatar($this->uid);
400
-		}
401
-		return true;
402
-	}
403
-
404
-	/**
405
-	 * check if the backend supports changing passwords
406
-	 *
407
-	 * @return bool
408
-	 */
409
-	public function canChangePassword() {
410
-		return $this->backend->implementsActions(Backend::SET_PASSWORD);
411
-	}
412
-
413
-	/**
414
-	 * check if the backend supports changing display names
415
-	 *
416
-	 * @return bool
417
-	 */
418
-	public function canChangeDisplayName() {
419
-		if ($this->config->getSystemValue('allow_user_to_change_display_name') === false) {
420
-			return false;
421
-		}
422
-		return $this->backend->implementsActions(Backend::SET_DISPLAYNAME);
423
-	}
424
-
425
-	/**
426
-	 * check if the user is enabled
427
-	 *
428
-	 * @return bool
429
-	 */
430
-	public function isEnabled() {
431
-		if ($this->enabled === null) {
432
-			$enabled = $this->config->getUserValue($this->uid, 'core', 'enabled', 'true');
433
-			$this->enabled = $enabled === 'true';
434
-		}
435
-		return (bool) $this->enabled;
436
-	}
437
-
438
-	/**
439
-	 * set the enabled status for the user
440
-	 *
441
-	 * @param bool $enabled
442
-	 */
443
-	public function setEnabled(bool $enabled = true) {
444
-		$oldStatus = $this->isEnabled();
445
-		$this->enabled = $enabled;
446
-		if ($oldStatus !== $this->enabled) {
447
-			// TODO: First change the value, then trigger the event as done for all other properties.
448
-			$this->triggerChange('enabled', $enabled, $oldStatus);
449
-			$this->config->setUserValue($this->uid, 'core', 'enabled', $enabled ? 'true' : 'false');
450
-		}
451
-	}
452
-
453
-	/**
454
-	 * get the users email address
455
-	 *
456
-	 * @return string|null
457
-	 * @since 9.0.0
458
-	 */
459
-	public function getEMailAddress() {
460
-		return $this->getPrimaryEMailAddress() ?? $this->getSystemEMailAddress();
461
-	}
462
-
463
-	/**
464
-	 * @inheritDoc
465
-	 */
466
-	public function getSystemEMailAddress(): ?string {
467
-		return $this->config->getUserValue($this->uid, 'settings', 'email', null);
468
-	}
469
-
470
-	/**
471
-	 * @inheritDoc
472
-	 */
473
-	public function getPrimaryEMailAddress(): ?string {
474
-		return $this->config->getUserValue($this->uid, 'settings', 'primary_email', null);
475
-	}
476
-
477
-	/**
478
-	 * get the users' quota
479
-	 *
480
-	 * @return string
481
-	 * @since 9.0.0
482
-	 */
483
-	public function getQuota() {
484
-		// allow apps to modify the user quota by hooking into the event
485
-		$event = new GetQuotaEvent($this);
486
-		$this->dispatcher->dispatchTyped($event);
487
-		$overwriteQuota = $event->getQuota();
488
-		if ($overwriteQuota) {
489
-			$quota = $overwriteQuota;
490
-		} else {
491
-			$quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
492
-		}
493
-		if ($quota === 'default') {
494
-			$quota = $this->config->getAppValue('files', 'default_quota', 'none');
495
-
496
-			// if unlimited quota is not allowed => avoid getting 'unlimited' as default_quota fallback value
497
-			// use the first preset instead
498
-			$allowUnlimitedQuota = $this->config->getAppValue('files', 'allow_unlimited_quota', '1') === '1';
499
-			if (!$allowUnlimitedQuota) {
500
-				$presets = $this->config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
501
-				$presets = array_filter(array_map('trim', explode(',', $presets)));
502
-				$quotaPreset = array_values(array_diff($presets, ['default', 'none']));
503
-				if (count($quotaPreset) > 0) {
504
-					$quota = $this->config->getAppValue('files', 'default_quota', $quotaPreset[0]);
505
-				}
506
-			}
507
-		}
508
-		return $quota;
509
-	}
510
-
511
-	/**
512
-	 * set the users' quota
513
-	 *
514
-	 * @param string $quota
515
-	 * @return void
516
-	 * @throws InvalidArgumentException
517
-	 * @since 9.0.0
518
-	 */
519
-	public function setQuota($quota) {
520
-		$oldQuota = $this->config->getUserValue($this->uid, 'files', 'quota', '');
521
-		if ($quota !== 'none' and $quota !== 'default') {
522
-			$bytesQuota = OC_Helper::computerFileSize($quota);
523
-			if ($bytesQuota === false) {
524
-				throw new InvalidArgumentException('Failed to set quota to invalid value '.$quota);
525
-			}
526
-			$quota = OC_Helper::humanFileSize($bytesQuota);
527
-		}
528
-		if ($quota !== $oldQuota) {
529
-			$this->config->setUserValue($this->uid, 'files', 'quota', $quota);
530
-			$this->triggerChange('quota', $quota, $oldQuota);
531
-		}
532
-		\OC_Helper::clearStorageInfo('/' . $this->uid . '/files');
533
-	}
534
-
535
-	/**
536
-	 * get the avatar image if it exists
537
-	 *
538
-	 * @param int $size
539
-	 * @return IImage|null
540
-	 * @since 9.0.0
541
-	 */
542
-	public function getAvatarImage($size) {
543
-		// delay the initialization
544
-		if (is_null($this->avatarManager)) {
545
-			$this->avatarManager = \OC::$server->getAvatarManager();
546
-		}
547
-
548
-		$avatar = $this->avatarManager->getAvatar($this->uid);
549
-		$image = $avatar->get(-1);
550
-		if ($image) {
551
-			return $image;
552
-		}
553
-
554
-		return null;
555
-	}
556
-
557
-	/**
558
-	 * get the federation cloud id
559
-	 *
560
-	 * @return string
561
-	 * @since 9.0.0
562
-	 */
563
-	public function getCloudId() {
564
-		$uid = $this->getUID();
565
-		$server = rtrim($this->urlGenerator->getAbsoluteURL('/'), '/');
566
-		if (substr($server, -10) === '/index.php') {
567
-			$server = substr($server, 0, -10);
568
-		}
569
-		$server = $this->removeProtocolFromUrl($server);
570
-		return $uid . '@' . $server;
571
-	}
572
-
573
-	private function removeProtocolFromUrl(string $url): string {
574
-		if (strpos($url, 'https://') === 0) {
575
-			return substr($url, strlen('https://'));
576
-		}
577
-
578
-		return $url;
579
-	}
580
-
581
-	public function triggerChange($feature, $value = null, $oldValue = null) {
582
-		$this->legacyDispatcher->dispatch(IUser::class . '::changeUser', new GenericEvent($this, [
583
-			'feature' => $feature,
584
-			'value' => $value,
585
-			'oldValue' => $oldValue,
586
-		]));
587
-		if ($this->emitter) {
588
-			$this->emitter->emit('\OC\User', 'changeUser', [$this, $feature, $value, $oldValue]);
589
-		}
590
-	}
64
+    /** @var IAccountManager */
65
+    protected $accountManager;
66
+    /** @var string */
67
+    private $uid;
68
+
69
+    /** @var string|null */
70
+    private $displayName;
71
+
72
+    /** @var UserInterface|null */
73
+    private $backend;
74
+    /** @var EventDispatcherInterface */
75
+    private $legacyDispatcher;
76
+
77
+    /** @var IEventDispatcher */
78
+    private $dispatcher;
79
+
80
+    /** @var bool|null */
81
+    private $enabled;
82
+
83
+    /** @var Emitter|Manager */
84
+    private $emitter;
85
+
86
+    /** @var string */
87
+    private $home;
88
+
89
+    /** @var int|null */
90
+    private $lastLogin;
91
+
92
+    /** @var \OCP\IConfig */
93
+    private $config;
94
+
95
+    /** @var IAvatarManager */
96
+    private $avatarManager;
97
+
98
+    /** @var IURLGenerator */
99
+    private $urlGenerator;
100
+
101
+    public function __construct(string $uid, ?UserInterface $backend, EventDispatcherInterface $dispatcher, $emitter = null, IConfig $config = null, $urlGenerator = null) {
102
+        $this->uid = $uid;
103
+        $this->backend = $backend;
104
+        $this->legacyDispatcher = $dispatcher;
105
+        $this->emitter = $emitter;
106
+        if (is_null($config)) {
107
+            $config = \OC::$server->getConfig();
108
+        }
109
+        $this->config = $config;
110
+        $this->urlGenerator = $urlGenerator;
111
+        if (is_null($this->urlGenerator)) {
112
+            $this->urlGenerator = \OC::$server->getURLGenerator();
113
+        }
114
+        // TODO: inject
115
+        $this->dispatcher = \OC::$server->query(IEventDispatcher::class);
116
+    }
117
+
118
+    /**
119
+     * get the user id
120
+     *
121
+     * @return string
122
+     */
123
+    public function getUID() {
124
+        return $this->uid;
125
+    }
126
+
127
+    /**
128
+     * get the display name for the user, if no specific display name is set it will fallback to the user id
129
+     *
130
+     * @return string
131
+     */
132
+    public function getDisplayName() {
133
+        if ($this->displayName === null) {
134
+            $displayName = '';
135
+            if ($this->backend && $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) {
136
+                // get display name and strip whitespace from the beginning and end of it
137
+                $backendDisplayName = $this->backend->getDisplayName($this->uid);
138
+                if (is_string($backendDisplayName)) {
139
+                    $displayName = trim($backendDisplayName);
140
+                }
141
+            }
142
+
143
+            if (!empty($displayName)) {
144
+                $this->displayName = $displayName;
145
+            } else {
146
+                $this->displayName = $this->uid;
147
+            }
148
+        }
149
+        return $this->displayName;
150
+    }
151
+
152
+    /**
153
+     * set the displayname for the user
154
+     *
155
+     * @param string $displayName
156
+     * @return bool
157
+     *
158
+     * @since 25.0.0 Throw InvalidArgumentException
159
+     * @throws \InvalidArgumentException
160
+     */
161
+    public function setDisplayName($displayName) {
162
+        $displayName = trim($displayName);
163
+        $oldDisplayName = $this->getDisplayName();
164
+        if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName) && $displayName !== $oldDisplayName) {
165
+            /** @var ISetDisplayNameBackend $backend */
166
+            $backend = $this->backend;
167
+            $result = $backend->setDisplayName($this->uid, $displayName);
168
+            if ($result) {
169
+                $this->displayName = $displayName;
170
+                $this->triggerChange('displayName', $displayName, $oldDisplayName);
171
+            }
172
+            return $result !== false;
173
+        }
174
+        return false;
175
+    }
176
+
177
+    /**
178
+     * @inheritDoc
179
+     */
180
+    public function setEMailAddress($mailAddress) {
181
+        $this->setSystemEMailAddress($mailAddress);
182
+    }
183
+
184
+    /**
185
+     * @inheritDoc
186
+     */
187
+    public function setSystemEMailAddress(string $mailAddress): void {
188
+        $oldMailAddress = $this->getSystemEMailAddress();
189
+
190
+        if ($mailAddress === '') {
191
+            $this->config->deleteUserValue($this->uid, 'settings', 'email');
192
+        } else {
193
+            $this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
194
+        }
195
+
196
+        $primaryAddress = $this->getPrimaryEMailAddress();
197
+        if ($primaryAddress === $mailAddress) {
198
+            // on match no dedicated primary settings is necessary
199
+            $this->setPrimaryEMailAddress('');
200
+        }
201
+
202
+        if ($oldMailAddress !== strtolower($mailAddress)) {
203
+            $this->triggerChange('eMailAddress', $mailAddress, $oldMailAddress);
204
+        }
205
+    }
206
+
207
+    /**
208
+     * @inheritDoc
209
+     */
210
+    public function setPrimaryEMailAddress(string $mailAddress): void {
211
+        if ($mailAddress === '') {
212
+            $this->config->deleteUserValue($this->uid, 'settings', 'primary_email');
213
+            return;
214
+        }
215
+
216
+        $this->ensureAccountManager();
217
+        $account = $this->accountManager->getAccount($this);
218
+        $property = $account->getPropertyCollection(IAccountManager::COLLECTION_EMAIL)
219
+            ->getPropertyByValue($mailAddress);
220
+
221
+        if ($property === null || $property->getLocallyVerified() !== IAccountManager::VERIFIED) {
222
+            throw new InvalidArgumentException('Only verified emails can be set as primary');
223
+        }
224
+        $this->config->setUserValue($this->uid, 'settings', 'primary_email', $mailAddress);
225
+    }
226
+
227
+    private function ensureAccountManager() {
228
+        if (!$this->accountManager instanceof IAccountManager) {
229
+            $this->accountManager = \OC::$server->get(IAccountManager::class);
230
+        }
231
+    }
232
+
233
+    /**
234
+     * returns the timestamp of the user's last login or 0 if the user did never
235
+     * login
236
+     *
237
+     * @return int
238
+     */
239
+    public function getLastLogin() {
240
+        if ($this->lastLogin === null) {
241
+            $this->lastLogin = (int) $this->config->getUserValue($this->uid, 'login', 'lastLogin', 0);
242
+        }
243
+        return (int) $this->lastLogin;
244
+    }
245
+
246
+    /**
247
+     * updates the timestamp of the most recent login of this user
248
+     */
249
+    public function updateLastLoginTimestamp() {
250
+        $previousLogin = $this->getLastLogin();
251
+        $now = time();
252
+        $firstTimeLogin = $previousLogin === 0;
253
+
254
+        if ($now - $previousLogin > 60) {
255
+            $this->lastLogin = time();
256
+            $this->config->setUserValue(
257
+                $this->uid, 'login', 'lastLogin', (string)$this->lastLogin);
258
+        }
259
+
260
+        return $firstTimeLogin;
261
+    }
262
+
263
+    /**
264
+     * Delete the user
265
+     *
266
+     * @return bool
267
+     */
268
+    public function delete() {
269
+        /** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
270
+        $this->legacyDispatcher->dispatch(IUser::class . '::preDelete', new GenericEvent($this));
271
+        if ($this->emitter) {
272
+            /** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
273
+            $this->emitter->emit('\OC\User', 'preDelete', [$this]);
274
+        }
275
+        $this->dispatcher->dispatchTyped(new BeforeUserDeletedEvent($this));
276
+        $result = $this->backend->deleteUser($this->uid);
277
+        if ($result) {
278
+            // FIXME: Feels like an hack - suggestions?
279
+
280
+            $groupManager = \OC::$server->getGroupManager();
281
+            // We have to delete the user from all groups
282
+            foreach ($groupManager->getUserGroupIds($this) as $groupId) {
283
+                $group = $groupManager->get($groupId);
284
+                if ($group) {
285
+                    $this->dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $this));
286
+                    $group->removeUser($this);
287
+                    $this->dispatcher->dispatchTyped(new UserRemovedEvent($group, $this));
288
+                }
289
+            }
290
+            // Delete the user's keys in preferences
291
+            \OC::$server->getConfig()->deleteAllUserValues($this->uid);
292
+
293
+            \OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
294
+            \OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
295
+
296
+            /** @var AvatarManager $avatarManager */
297
+            $avatarManager = \OC::$server->query(AvatarManager::class);
298
+            $avatarManager->deleteUserAvatar($this->uid);
299
+
300
+            $notification = \OC::$server->getNotificationManager()->createNotification();
301
+            $notification->setUser($this->uid);
302
+            \OC::$server->getNotificationManager()->markProcessed($notification);
303
+
304
+            /** @var AccountManager $accountManager */
305
+            $accountManager = \OC::$server->query(AccountManager::class);
306
+            $accountManager->deleteUser($this);
307
+
308
+            /** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
309
+            $this->legacyDispatcher->dispatch(IUser::class . '::postDelete', new GenericEvent($this));
310
+            if ($this->emitter) {
311
+                /** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
312
+                $this->emitter->emit('\OC\User', 'postDelete', [$this]);
313
+            }
314
+            $this->dispatcher->dispatchTyped(new UserDeletedEvent($this));
315
+        }
316
+        return !($result === false);
317
+    }
318
+
319
+    /**
320
+     * Set the password of the user
321
+     *
322
+     * @param string $password
323
+     * @param string $recoveryPassword for the encryption app to reset encryption keys
324
+     * @return bool
325
+     */
326
+    public function setPassword($password, $recoveryPassword = null) {
327
+        $this->legacyDispatcher->dispatch(IUser::class . '::preSetPassword', new GenericEvent($this, [
328
+            'password' => $password,
329
+            'recoveryPassword' => $recoveryPassword,
330
+        ]));
331
+        if ($this->emitter) {
332
+            $this->emitter->emit('\OC\User', 'preSetPassword', [$this, $password, $recoveryPassword]);
333
+        }
334
+        if ($this->backend->implementsActions(Backend::SET_PASSWORD)) {
335
+            /** @var ISetPasswordBackend $backend */
336
+            $backend = $this->backend;
337
+            $result = $backend->setPassword($this->uid, $password);
338
+
339
+            if ($result !== false) {
340
+                $this->legacyDispatcher->dispatch(IUser::class . '::postSetPassword', new GenericEvent($this, [
341
+                    'password' => $password,
342
+                    'recoveryPassword' => $recoveryPassword,
343
+                ]));
344
+                if ($this->emitter) {
345
+                    $this->emitter->emit('\OC\User', 'postSetPassword', [$this, $password, $recoveryPassword]);
346
+                }
347
+            }
348
+
349
+            return !($result === false);
350
+        } else {
351
+            return false;
352
+        }
353
+    }
354
+
355
+    /**
356
+     * get the users home folder to mount
357
+     *
358
+     * @return string
359
+     */
360
+    public function getHome() {
361
+        if (!$this->home) {
362
+            /** @psalm-suppress UndefinedInterfaceMethod Once we get rid of the legacy implementsActions, psalm won't complain anymore */
363
+            if (($this->backend instanceof IGetHomeBackend || $this->backend->implementsActions(Backend::GET_HOME)) && $home = $this->backend->getHome($this->uid)) {
364
+                $this->home = $home;
365
+            } elseif ($this->config) {
366
+                $this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
367
+            } else {
368
+                $this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
369
+            }
370
+        }
371
+        return $this->home;
372
+    }
373
+
374
+    /**
375
+     * Get the name of the backend class the user is connected with
376
+     *
377
+     * @return string
378
+     */
379
+    public function getBackendClassName() {
380
+        if ($this->backend instanceof IUserBackend) {
381
+            return $this->backend->getBackendName();
382
+        }
383
+        return get_class($this->backend);
384
+    }
385
+
386
+    public function getBackend(): ?UserInterface {
387
+        return $this->backend;
388
+    }
389
+
390
+    /**
391
+     * Check if the backend allows the user to change his avatar on Personal page
392
+     *
393
+     * @return bool
394
+     */
395
+    public function canChangeAvatar() {
396
+        if ($this->backend instanceof IProvideAvatarBackend || $this->backend->implementsActions(Backend::PROVIDE_AVATAR)) {
397
+            /** @var IProvideAvatarBackend $backend */
398
+            $backend = $this->backend;
399
+            return $backend->canChangeAvatar($this->uid);
400
+        }
401
+        return true;
402
+    }
403
+
404
+    /**
405
+     * check if the backend supports changing passwords
406
+     *
407
+     * @return bool
408
+     */
409
+    public function canChangePassword() {
410
+        return $this->backend->implementsActions(Backend::SET_PASSWORD);
411
+    }
412
+
413
+    /**
414
+     * check if the backend supports changing display names
415
+     *
416
+     * @return bool
417
+     */
418
+    public function canChangeDisplayName() {
419
+        if ($this->config->getSystemValue('allow_user_to_change_display_name') === false) {
420
+            return false;
421
+        }
422
+        return $this->backend->implementsActions(Backend::SET_DISPLAYNAME);
423
+    }
424
+
425
+    /**
426
+     * check if the user is enabled
427
+     *
428
+     * @return bool
429
+     */
430
+    public function isEnabled() {
431
+        if ($this->enabled === null) {
432
+            $enabled = $this->config->getUserValue($this->uid, 'core', 'enabled', 'true');
433
+            $this->enabled = $enabled === 'true';
434
+        }
435
+        return (bool) $this->enabled;
436
+    }
437
+
438
+    /**
439
+     * set the enabled status for the user
440
+     *
441
+     * @param bool $enabled
442
+     */
443
+    public function setEnabled(bool $enabled = true) {
444
+        $oldStatus = $this->isEnabled();
445
+        $this->enabled = $enabled;
446
+        if ($oldStatus !== $this->enabled) {
447
+            // TODO: First change the value, then trigger the event as done for all other properties.
448
+            $this->triggerChange('enabled', $enabled, $oldStatus);
449
+            $this->config->setUserValue($this->uid, 'core', 'enabled', $enabled ? 'true' : 'false');
450
+        }
451
+    }
452
+
453
+    /**
454
+     * get the users email address
455
+     *
456
+     * @return string|null
457
+     * @since 9.0.0
458
+     */
459
+    public function getEMailAddress() {
460
+        return $this->getPrimaryEMailAddress() ?? $this->getSystemEMailAddress();
461
+    }
462
+
463
+    /**
464
+     * @inheritDoc
465
+     */
466
+    public function getSystemEMailAddress(): ?string {
467
+        return $this->config->getUserValue($this->uid, 'settings', 'email', null);
468
+    }
469
+
470
+    /**
471
+     * @inheritDoc
472
+     */
473
+    public function getPrimaryEMailAddress(): ?string {
474
+        return $this->config->getUserValue($this->uid, 'settings', 'primary_email', null);
475
+    }
476
+
477
+    /**
478
+     * get the users' quota
479
+     *
480
+     * @return string
481
+     * @since 9.0.0
482
+     */
483
+    public function getQuota() {
484
+        // allow apps to modify the user quota by hooking into the event
485
+        $event = new GetQuotaEvent($this);
486
+        $this->dispatcher->dispatchTyped($event);
487
+        $overwriteQuota = $event->getQuota();
488
+        if ($overwriteQuota) {
489
+            $quota = $overwriteQuota;
490
+        } else {
491
+            $quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
492
+        }
493
+        if ($quota === 'default') {
494
+            $quota = $this->config->getAppValue('files', 'default_quota', 'none');
495
+
496
+            // if unlimited quota is not allowed => avoid getting 'unlimited' as default_quota fallback value
497
+            // use the first preset instead
498
+            $allowUnlimitedQuota = $this->config->getAppValue('files', 'allow_unlimited_quota', '1') === '1';
499
+            if (!$allowUnlimitedQuota) {
500
+                $presets = $this->config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
501
+                $presets = array_filter(array_map('trim', explode(',', $presets)));
502
+                $quotaPreset = array_values(array_diff($presets, ['default', 'none']));
503
+                if (count($quotaPreset) > 0) {
504
+                    $quota = $this->config->getAppValue('files', 'default_quota', $quotaPreset[0]);
505
+                }
506
+            }
507
+        }
508
+        return $quota;
509
+    }
510
+
511
+    /**
512
+     * set the users' quota
513
+     *
514
+     * @param string $quota
515
+     * @return void
516
+     * @throws InvalidArgumentException
517
+     * @since 9.0.0
518
+     */
519
+    public function setQuota($quota) {
520
+        $oldQuota = $this->config->getUserValue($this->uid, 'files', 'quota', '');
521
+        if ($quota !== 'none' and $quota !== 'default') {
522
+            $bytesQuota = OC_Helper::computerFileSize($quota);
523
+            if ($bytesQuota === false) {
524
+                throw new InvalidArgumentException('Failed to set quota to invalid value '.$quota);
525
+            }
526
+            $quota = OC_Helper::humanFileSize($bytesQuota);
527
+        }
528
+        if ($quota !== $oldQuota) {
529
+            $this->config->setUserValue($this->uid, 'files', 'quota', $quota);
530
+            $this->triggerChange('quota', $quota, $oldQuota);
531
+        }
532
+        \OC_Helper::clearStorageInfo('/' . $this->uid . '/files');
533
+    }
534
+
535
+    /**
536
+     * get the avatar image if it exists
537
+     *
538
+     * @param int $size
539
+     * @return IImage|null
540
+     * @since 9.0.0
541
+     */
542
+    public function getAvatarImage($size) {
543
+        // delay the initialization
544
+        if (is_null($this->avatarManager)) {
545
+            $this->avatarManager = \OC::$server->getAvatarManager();
546
+        }
547
+
548
+        $avatar = $this->avatarManager->getAvatar($this->uid);
549
+        $image = $avatar->get(-1);
550
+        if ($image) {
551
+            return $image;
552
+        }
553
+
554
+        return null;
555
+    }
556
+
557
+    /**
558
+     * get the federation cloud id
559
+     *
560
+     * @return string
561
+     * @since 9.0.0
562
+     */
563
+    public function getCloudId() {
564
+        $uid = $this->getUID();
565
+        $server = rtrim($this->urlGenerator->getAbsoluteURL('/'), '/');
566
+        if (substr($server, -10) === '/index.php') {
567
+            $server = substr($server, 0, -10);
568
+        }
569
+        $server = $this->removeProtocolFromUrl($server);
570
+        return $uid . '@' . $server;
571
+    }
572
+
573
+    private function removeProtocolFromUrl(string $url): string {
574
+        if (strpos($url, 'https://') === 0) {
575
+            return substr($url, strlen('https://'));
576
+        }
577
+
578
+        return $url;
579
+    }
580
+
581
+    public function triggerChange($feature, $value = null, $oldValue = null) {
582
+        $this->legacyDispatcher->dispatch(IUser::class . '::changeUser', new GenericEvent($this, [
583
+            'feature' => $feature,
584
+            'value' => $value,
585
+            'oldValue' => $oldValue,
586
+        ]));
587
+        if ($this->emitter) {
588
+            $this->emitter->emit('\OC\User', 'changeUser', [$this, $feature, $value, $oldValue]);
589
+        }
590
+    }
591 591
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 		if ($now - $previousLogin > 60) {
255 255
 			$this->lastLogin = time();
256 256
 			$this->config->setUserValue(
257
-				$this->uid, 'login', 'lastLogin', (string)$this->lastLogin);
257
+				$this->uid, 'login', 'lastLogin', (string) $this->lastLogin);
258 258
 		}
259 259
 
260 260
 		return $firstTimeLogin;
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
 	 */
268 268
 	public function delete() {
269 269
 		/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
270
-		$this->legacyDispatcher->dispatch(IUser::class . '::preDelete', new GenericEvent($this));
270
+		$this->legacyDispatcher->dispatch(IUser::class.'::preDelete', new GenericEvent($this));
271 271
 		if ($this->emitter) {
272 272
 			/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
273 273
 			$this->emitter->emit('\OC\User', 'preDelete', [$this]);
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
 			$accountManager->deleteUser($this);
307 307
 
308 308
 			/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
309
-			$this->legacyDispatcher->dispatch(IUser::class . '::postDelete', new GenericEvent($this));
309
+			$this->legacyDispatcher->dispatch(IUser::class.'::postDelete', new GenericEvent($this));
310 310
 			if ($this->emitter) {
311 311
 				/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
312 312
 				$this->emitter->emit('\OC\User', 'postDelete', [$this]);
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
 	 * @return bool
325 325
 	 */
326 326
 	public function setPassword($password, $recoveryPassword = null) {
327
-		$this->legacyDispatcher->dispatch(IUser::class . '::preSetPassword', new GenericEvent($this, [
327
+		$this->legacyDispatcher->dispatch(IUser::class.'::preSetPassword', new GenericEvent($this, [
328 328
 			'password' => $password,
329 329
 			'recoveryPassword' => $recoveryPassword,
330 330
 		]));
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 			$result = $backend->setPassword($this->uid, $password);
338 338
 
339 339
 			if ($result !== false) {
340
-				$this->legacyDispatcher->dispatch(IUser::class . '::postSetPassword', new GenericEvent($this, [
340
+				$this->legacyDispatcher->dispatch(IUser::class.'::postSetPassword', new GenericEvent($this, [
341 341
 					'password' => $password,
342 342
 					'recoveryPassword' => $recoveryPassword,
343 343
 				]));
@@ -363,9 +363,9 @@  discard block
 block discarded – undo
363 363
 			if (($this->backend instanceof IGetHomeBackend || $this->backend->implementsActions(Backend::GET_HOME)) && $home = $this->backend->getHome($this->uid)) {
364 364
 				$this->home = $home;
365 365
 			} elseif ($this->config) {
366
-				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
366
+				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/'.$this->uid;
367 367
 			} else {
368
-				$this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
368
+				$this->home = \OC::$SERVERROOT.'/data/'.$this->uid;
369 369
 			}
370 370
 		}
371 371
 		return $this->home;
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
 			$this->config->setUserValue($this->uid, 'files', 'quota', $quota);
530 530
 			$this->triggerChange('quota', $quota, $oldQuota);
531 531
 		}
532
-		\OC_Helper::clearStorageInfo('/' . $this->uid . '/files');
532
+		\OC_Helper::clearStorageInfo('/'.$this->uid.'/files');
533 533
 	}
534 534
 
535 535
 	/**
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 			$server = substr($server, 0, -10);
568 568
 		}
569 569
 		$server = $this->removeProtocolFromUrl($server);
570
-		return $uid . '@' . $server;
570
+		return $uid.'@'.$server;
571 571
 	}
572 572
 
573 573
 	private function removeProtocolFromUrl(string $url): string {
@@ -579,7 +579,7 @@  discard block
 block discarded – undo
579 579
 	}
580 580
 
581 581
 	public function triggerChange($feature, $value = null, $oldValue = null) {
582
-		$this->legacyDispatcher->dispatch(IUser::class . '::changeUser', new GenericEvent($this, [
582
+		$this->legacyDispatcher->dispatch(IUser::class.'::changeUser', new GenericEvent($this, [
583 583
 			'feature' => $feature,
584 584
 			'value' => $value,
585 585
 			'oldValue' => $oldValue,
Please login to merge, or discard this patch.
lib/private/legacy/OC_Helper.php 2 patches
Indentation   +580 added lines, -580 removed lines patch added patch discarded remove patch
@@ -56,584 +56,584 @@
 block discarded – undo
56 56
  * Collection of useful functions
57 57
  */
58 58
 class OC_Helper {
59
-	private static $templateManager;
60
-
61
-	/**
62
-	 * Make a human file size
63
-	 * @param int|float $bytes file size in bytes
64
-	 * @return string a human readable file size
65
-	 *
66
-	 * Makes 2048 to 2 kB.
67
-	 */
68
-	public static function humanFileSize(int|float $bytes): string {
69
-		if ($bytes < 0) {
70
-			return "?";
71
-		}
72
-		if ($bytes < 1024) {
73
-			return "$bytes B";
74
-		}
75
-		$bytes = round($bytes / 1024, 0);
76
-		if ($bytes < 1024) {
77
-			return "$bytes KB";
78
-		}
79
-		$bytes = round($bytes / 1024, 1);
80
-		if ($bytes < 1024) {
81
-			return "$bytes MB";
82
-		}
83
-		$bytes = round($bytes / 1024, 1);
84
-		if ($bytes < 1024) {
85
-			return "$bytes GB";
86
-		}
87
-		$bytes = round($bytes / 1024, 1);
88
-		if ($bytes < 1024) {
89
-			return "$bytes TB";
90
-		}
91
-
92
-		$bytes = round($bytes / 1024, 1);
93
-		return "$bytes PB";
94
-	}
95
-
96
-	/**
97
-	 * Make a computer file size
98
-	 * @param string $str file size in human readable format
99
-	 * @return false|int|float a file size in bytes
100
-	 *
101
-	 * Makes 2kB to 2048.
102
-	 *
103
-	 * Inspired by: https://www.php.net/manual/en/function.filesize.php#92418
104
-	 */
105
-	public static function computerFileSize(string $str): false|int|float {
106
-		$str = strtolower($str);
107
-		if (is_numeric($str)) {
108
-			return Util::numericToNumber($str);
109
-		}
110
-
111
-		$bytes_array = [
112
-			'b' => 1,
113
-			'k' => 1024,
114
-			'kb' => 1024,
115
-			'mb' => 1024 * 1024,
116
-			'm' => 1024 * 1024,
117
-			'gb' => 1024 * 1024 * 1024,
118
-			'g' => 1024 * 1024 * 1024,
119
-			'tb' => 1024 * 1024 * 1024 * 1024,
120
-			't' => 1024 * 1024 * 1024 * 1024,
121
-			'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
122
-			'p' => 1024 * 1024 * 1024 * 1024 * 1024,
123
-		];
124
-
125
-		$bytes = (float)$str;
126
-
127
-		if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
128
-			$bytes *= $bytes_array[$matches[1]];
129
-		} else {
130
-			return false;
131
-		}
132
-
133
-		return Util::numericToNumber(round($bytes));
134
-	}
135
-
136
-	/**
137
-	 * Recursive copying of folders
138
-	 * @param string $src source folder
139
-	 * @param string $dest target folder
140
-	 * @return void
141
-	 */
142
-	public static function copyr($src, $dest) {
143
-		if (is_dir($src)) {
144
-			if (!is_dir($dest)) {
145
-				mkdir($dest);
146
-			}
147
-			$files = scandir($src);
148
-			foreach ($files as $file) {
149
-				if ($file != "." && $file != "..") {
150
-					self::copyr("$src/$file", "$dest/$file");
151
-				}
152
-			}
153
-		} elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
154
-			copy($src, $dest);
155
-		}
156
-	}
157
-
158
-	/**
159
-	 * Recursive deletion of folders
160
-	 * @param string $dir path to the folder
161
-	 * @param bool $deleteSelf if set to false only the content of the folder will be deleted
162
-	 * @return bool
163
-	 */
164
-	public static function rmdirr($dir, $deleteSelf = true) {
165
-		if (is_dir($dir)) {
166
-			$files = new RecursiveIteratorIterator(
167
-				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
168
-				RecursiveIteratorIterator::CHILD_FIRST
169
-			);
170
-
171
-			foreach ($files as $fileInfo) {
172
-				/** @var SplFileInfo $fileInfo */
173
-				if ($fileInfo->isLink()) {
174
-					unlink($fileInfo->getPathname());
175
-				} elseif ($fileInfo->isDir()) {
176
-					rmdir($fileInfo->getRealPath());
177
-				} else {
178
-					unlink($fileInfo->getRealPath());
179
-				}
180
-			}
181
-			if ($deleteSelf) {
182
-				rmdir($dir);
183
-			}
184
-		} elseif (file_exists($dir)) {
185
-			if ($deleteSelf) {
186
-				unlink($dir);
187
-			}
188
-		}
189
-		if (!$deleteSelf) {
190
-			return true;
191
-		}
192
-
193
-		return !file_exists($dir);
194
-	}
195
-
196
-	/**
197
-	 * @deprecated 18.0.0
198
-	 * @return \OC\Files\Type\TemplateManager
199
-	 */
200
-	public static function getFileTemplateManager() {
201
-		if (!self::$templateManager) {
202
-			self::$templateManager = new \OC\Files\Type\TemplateManager();
203
-		}
204
-		return self::$templateManager;
205
-	}
206
-
207
-	/**
208
-	 * detect if a given program is found in the search PATH
209
-	 *
210
-	 * @param string $name
211
-	 * @param bool $path
212
-	 * @internal param string $program name
213
-	 * @internal param string $optional search path, defaults to $PATH
214
-	 * @return bool    true if executable program found in path
215
-	 */
216
-	public static function canExecute($name, $path = false) {
217
-		// path defaults to PATH from environment if not set
218
-		if ($path === false) {
219
-			$path = getenv("PATH");
220
-		}
221
-		// we look for an executable file of that name
222
-		$exts = [""];
223
-		$check_fn = "is_executable";
224
-		// Default check will be done with $path directories :
225
-		$dirs = explode(PATH_SEPARATOR, $path);
226
-		// WARNING : We have to check if open_basedir is enabled :
227
-		$obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
228
-		if ($obd != "none") {
229
-			$obd_values = explode(PATH_SEPARATOR, $obd);
230
-			if (count($obd_values) > 0 and $obd_values[0]) {
231
-				// open_basedir is in effect !
232
-				// We need to check if the program is in one of these dirs :
233
-				$dirs = $obd_values;
234
-			}
235
-		}
236
-		foreach ($dirs as $dir) {
237
-			foreach ($exts as $ext) {
238
-				if ($check_fn("$dir/$name" . $ext)) {
239
-					return true;
240
-				}
241
-			}
242
-		}
243
-		return false;
244
-	}
245
-
246
-	/**
247
-	 * copy the contents of one stream to another
248
-	 *
249
-	 * @param resource $source
250
-	 * @param resource $target
251
-	 * @return array the number of bytes copied and result
252
-	 */
253
-	public static function streamCopy($source, $target) {
254
-		if (!$source or !$target) {
255
-			return [0, false];
256
-		}
257
-		$bufSize = 8192;
258
-		$result = true;
259
-		$count = 0;
260
-		while (!feof($source)) {
261
-			$buf = fread($source, $bufSize);
262
-			$bytesWritten = fwrite($target, $buf);
263
-			if ($bytesWritten !== false) {
264
-				$count += $bytesWritten;
265
-			}
266
-			// note: strlen is expensive so only use it when necessary,
267
-			// on the last block
268
-			if ($bytesWritten === false
269
-				|| ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
270
-			) {
271
-				// write error, could be disk full ?
272
-				$result = false;
273
-				break;
274
-			}
275
-		}
276
-		return [$count, $result];
277
-	}
278
-
279
-	/**
280
-	 * Adds a suffix to the name in case the file exists
281
-	 *
282
-	 * @param string $path
283
-	 * @param string $filename
284
-	 * @return string
285
-	 */
286
-	public static function buildNotExistingFileName($path, $filename) {
287
-		$view = \OC\Files\Filesystem::getView();
288
-		return self::buildNotExistingFileNameForView($path, $filename, $view);
289
-	}
290
-
291
-	/**
292
-	 * Adds a suffix to the name in case the file exists
293
-	 *
294
-	 * @param string $path
295
-	 * @param string $filename
296
-	 * @return string
297
-	 */
298
-	public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
299
-		if ($path === '/') {
300
-			$path = '';
301
-		}
302
-		if ($pos = strrpos($filename, '.')) {
303
-			$name = substr($filename, 0, $pos);
304
-			$ext = substr($filename, $pos);
305
-		} else {
306
-			$name = $filename;
307
-			$ext = '';
308
-		}
309
-
310
-		$newpath = $path . '/' . $filename;
311
-		if ($view->file_exists($newpath)) {
312
-			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
313
-				//Replace the last "(number)" with "(number+1)"
314
-				$last_match = count($matches[0]) - 1;
315
-				$counter = $matches[1][$last_match][0] + 1;
316
-				$offset = $matches[0][$last_match][1];
317
-				$match_length = strlen($matches[0][$last_match][0]);
318
-			} else {
319
-				$counter = 2;
320
-				$match_length = 0;
321
-				$offset = false;
322
-			}
323
-			do {
324
-				if ($offset) {
325
-					//Replace the last "(number)" with "(number+1)"
326
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
327
-				} else {
328
-					$newname = $name . ' (' . $counter . ')';
329
-				}
330
-				$newpath = $path . '/' . $newname . $ext;
331
-				$counter++;
332
-			} while ($view->file_exists($newpath));
333
-		}
334
-
335
-		return $newpath;
336
-	}
337
-
338
-	/**
339
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
340
-	 *
341
-	 * @param array $input The array to work on
342
-	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
343
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
344
-	 * @return array
345
-	 *
346
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
347
-	 * based on https://www.php.net/manual/en/function.array-change-key-case.php#107715
348
-	 *
349
-	 */
350
-	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
351
-		$case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
352
-		$ret = [];
353
-		foreach ($input as $k => $v) {
354
-			$ret[mb_convert_case($k, $case, $encoding)] = $v;
355
-		}
356
-		return $ret;
357
-	}
358
-
359
-	/**
360
-	 * performs a search in a nested array
361
-	 * @param array $haystack the array to be searched
362
-	 * @param string $needle the search string
363
-	 * @param mixed $index optional, only search this key name
364
-	 * @return mixed the key of the matching field, otherwise false
365
-	 *
366
-	 * performs a search in a nested array
367
-	 *
368
-	 * taken from https://www.php.net/manual/en/function.array-search.php#97645
369
-	 */
370
-	public static function recursiveArraySearch($haystack, $needle, $index = null) {
371
-		$aIt = new RecursiveArrayIterator($haystack);
372
-		$it = new RecursiveIteratorIterator($aIt);
373
-
374
-		while ($it->valid()) {
375
-			if (((isset($index) and ($it->key() == $index)) or !isset($index)) and ($it->current() == $needle)) {
376
-				return $aIt->key();
377
-			}
378
-
379
-			$it->next();
380
-		}
381
-
382
-		return false;
383
-	}
384
-
385
-	/**
386
-	 * calculates the maximum upload size respecting system settings, free space and user quota
387
-	 *
388
-	 * @param string $dir the current folder where the user currently operates
389
-	 * @param int|float $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
390
-	 * @return int|float number of bytes representing
391
-	 */
392
-	public static function maxUploadFilesize($dir, $freeSpace = null) {
393
-		if (is_null($freeSpace) || $freeSpace < 0) {
394
-			$freeSpace = self::freeSpace($dir);
395
-		}
396
-		return min($freeSpace, self::uploadLimit());
397
-	}
398
-
399
-	/**
400
-	 * Calculate free space left within user quota
401
-	 *
402
-	 * @param string $dir the current folder where the user currently operates
403
-	 * @return int|float number of bytes representing
404
-	 */
405
-	public static function freeSpace($dir) {
406
-		$freeSpace = \OC\Files\Filesystem::free_space($dir);
407
-		if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
408
-			$freeSpace = max($freeSpace, 0);
409
-			return $freeSpace;
410
-		} else {
411
-			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
412
-		}
413
-	}
414
-
415
-	/**
416
-	 * Calculate PHP upload limit
417
-	 *
418
-	 * @return int|float PHP upload file size limit
419
-	 */
420
-	public static function uploadLimit() {
421
-		$ini = \OC::$server->get(IniGetWrapper::class);
422
-		$upload_max_filesize = Util::computerFileSize($ini->get('upload_max_filesize')) ?: 0;
423
-		$post_max_size = Util::computerFileSize($ini->get('post_max_size')) ?: 0;
424
-		if ($upload_max_filesize === 0 && $post_max_size === 0) {
425
-			return INF;
426
-		} elseif ($upload_max_filesize === 0 || $post_max_size === 0) {
427
-			return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
428
-		} else {
429
-			return min($upload_max_filesize, $post_max_size);
430
-		}
431
-	}
432
-
433
-	/**
434
-	 * Checks if a function is available
435
-	 *
436
-	 * @deprecated Since 25.0.0 use \OCP\Util::isFunctionEnabled instead
437
-	 */
438
-	public static function is_function_enabled(string $function_name): bool {
439
-		return \OCP\Util::isFunctionEnabled($function_name);
440
-	}
441
-
442
-	/**
443
-	 * Try to find a program
444
-	 * @deprecated Since 25.0.0 Use \OC\BinaryFinder directly
445
-	 */
446
-	public static function findBinaryPath(string $program): ?string {
447
-		$result = \OCP\Server::get(IBinaryFinder::class)->findBinaryPath($program);
448
-		return $result !== false ? $result : null;
449
-	}
450
-
451
-	/**
452
-	 * Calculate the disc space for the given path
453
-	 *
454
-	 * BEWARE: this requires that Util::setupFS() was called
455
-	 * already !
456
-	 *
457
-	 * @param string $path
458
-	 * @param \OCP\Files\FileInfo $rootInfo (optional)
459
-	 * @param bool $includeMountPoints whether to include mount points in the size calculation
460
-	 * @param bool $useCache whether to use the cached quota values
461
-	 * @return array
462
-	 * @throws \OCP\Files\NotFoundException
463
-	 */
464
-	public static function getStorageInfo($path, $rootInfo = null, $includeMountPoints = true, $useCache = true) {
465
-		/** @var ICacheFactory $cacheFactory */
466
-		$cacheFactory = \OC::$server->get(ICacheFactory::class);
467
-		$memcache = $cacheFactory->createLocal('storage_info');
468
-
469
-		// return storage info without adding mount points
470
-		$includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
471
-
472
-		$view = Filesystem::getView();
473
-		if (!$view) {
474
-			throw new \OCP\Files\NotFoundException();
475
-		}
476
-		$fullPath = Filesystem::normalizePath($view->getAbsolutePath($path));
477
-
478
-		$cacheKey = $fullPath. '::' . ($includeMountPoints ? 'include' : 'exclude');
479
-		if ($useCache) {
480
-			$cached = $memcache->get($cacheKey);
481
-			if ($cached) {
482
-				return $cached;
483
-			}
484
-		}
485
-
486
-		if (!$rootInfo) {
487
-			$rootInfo = \OC\Files\Filesystem::getFileInfo($path, $includeExtStorage ? 'ext' : false);
488
-		}
489
-		if (!$rootInfo instanceof \OCP\Files\FileInfo) {
490
-			throw new \OCP\Files\NotFoundException();
491
-		}
492
-		$used = $rootInfo->getSize($includeMountPoints);
493
-		if ($used < 0) {
494
-			$used = 0;
495
-		}
496
-		$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
497
-		$mount = $rootInfo->getMountPoint();
498
-		$storage = $mount->getStorage();
499
-		$sourceStorage = $storage;
500
-		if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
501
-			$includeExtStorage = false;
502
-		}
503
-		if ($includeExtStorage) {
504
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
505
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
506
-			) {
507
-				/** @var \OC\Files\Storage\Home $storage */
508
-				$user = $storage->getUser();
509
-			} else {
510
-				$user = \OC::$server->getUserSession()->getUser();
511
-			}
512
-			$quota = OC_Util::getUserQuota($user);
513
-			if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
514
-				// always get free space / total space from root + mount points
515
-				return self::getGlobalStorageInfo($quota, $user, $mount);
516
-			}
517
-		}
518
-
519
-		// TODO: need a better way to get total space from storage
520
-		if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
521
-			/** @var \OC\Files\Storage\Wrapper\Quota $storage */
522
-			$quota = $sourceStorage->getQuota();
523
-		}
524
-		try {
525
-			$free = $sourceStorage->free_space($rootInfo->getInternalPath());
526
-		} catch (\Exception $e) {
527
-			if ($path === "") {
528
-				throw $e;
529
-			}
530
-			/** @var LoggerInterface $logger */
531
-			$logger = \OC::$server->get(LoggerInterface::class);
532
-			$logger->warning("Error while getting quota info, using root quota", ['exception' => $e]);
533
-			$rootInfo = self::getStorageInfo("");
534
-			$memcache->set($cacheKey, $rootInfo, 5 * 60);
535
-			return $rootInfo;
536
-		}
537
-		if ($free >= 0) {
538
-			$total = $free + $used;
539
-		} else {
540
-			$total = $free; //either unknown or unlimited
541
-		}
542
-		if ($total > 0) {
543
-			if ($quota > 0 && $total > $quota) {
544
-				$total = $quota;
545
-			}
546
-			// prevent division by zero or error codes (negative values)
547
-			$relative = round(($used / $total) * 10000) / 100;
548
-		} else {
549
-			$relative = 0;
550
-		}
551
-
552
-		$ownerId = $storage->getOwner($path);
553
-		$ownerDisplayName = '';
554
-		if ($ownerId) {
555
-			$ownerDisplayName = \OC::$server->getUserManager()->getDisplayName($ownerId) ?? '';
556
-		}
557
-
558
-		if (substr_count($mount->getMountPoint(), '/') < 3) {
559
-			$mountPoint = '';
560
-		} else {
561
-			[,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
562
-		}
563
-
564
-		$info = [
565
-			'free' => $free,
566
-			'used' => $used,
567
-			'quota' => $quota,
568
-			'total' => $total,
569
-			'relative' => $relative,
570
-			'owner' => $ownerId,
571
-			'ownerDisplayName' => $ownerDisplayName,
572
-			'mountType' => $mount->getMountType(),
573
-			'mountPoint' => trim($mountPoint, '/'),
574
-		];
575
-
576
-		$memcache->set($cacheKey, $info, 5 * 60);
577
-
578
-		return $info;
579
-	}
580
-
581
-	/**
582
-	 * Get storage info including all mount points and quota
583
-	 */
584
-	private static function getGlobalStorageInfo(int|float $quota, IUser $user, IMountPoint $mount): array {
585
-		$rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
586
-		$used = $rootInfo['size'];
587
-		if ($used < 0) {
588
-			$used = 0;
589
-		}
590
-
591
-		$total = $quota;
592
-		$free = $quota - $used;
593
-
594
-		if ($total > 0) {
595
-			if ($quota > 0 && $total > $quota) {
596
-				$total = $quota;
597
-			}
598
-			// prevent division by zero or error codes (negative values)
599
-			$relative = round(($used / $total) * 10000) / 100;
600
-		} else {
601
-			$relative = 0;
602
-		}
603
-
604
-		if (substr_count($mount->getMountPoint(), '/') < 3) {
605
-			$mountPoint = '';
606
-		} else {
607
-			[,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
608
-		}
609
-
610
-		return [
611
-			'free' => $free,
612
-			'used' => $used,
613
-			'total' => $total,
614
-			'relative' => $relative,
615
-			'quota' => $quota,
616
-			'owner' => $user->getUID(),
617
-			'ownerDisplayName' => $user->getDisplayName(),
618
-			'mountType' => $mount->getMountType(),
619
-			'mountPoint' => trim($mountPoint, '/'),
620
-		];
621
-	}
622
-
623
-	public static function clearStorageInfo(string $absolutePath): void {
624
-		/** @var ICacheFactory $cacheFactory */
625
-		$cacheFactory = \OC::$server->get(ICacheFactory::class);
626
-		$memcache = $cacheFactory->createLocal('storage_info');
627
-		$cacheKeyPrefix = Filesystem::normalizePath($absolutePath) . '::';
628
-		$memcache->remove($cacheKeyPrefix . 'include');
629
-		$memcache->remove($cacheKeyPrefix . 'exclude');
630
-	}
631
-
632
-	/**
633
-	 * Returns whether the config file is set manually to read-only
634
-	 * @return bool
635
-	 */
636
-	public static function isReadOnlyConfigEnabled() {
637
-		return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
638
-	}
59
+    private static $templateManager;
60
+
61
+    /**
62
+     * Make a human file size
63
+     * @param int|float $bytes file size in bytes
64
+     * @return string a human readable file size
65
+     *
66
+     * Makes 2048 to 2 kB.
67
+     */
68
+    public static function humanFileSize(int|float $bytes): string {
69
+        if ($bytes < 0) {
70
+            return "?";
71
+        }
72
+        if ($bytes < 1024) {
73
+            return "$bytes B";
74
+        }
75
+        $bytes = round($bytes / 1024, 0);
76
+        if ($bytes < 1024) {
77
+            return "$bytes KB";
78
+        }
79
+        $bytes = round($bytes / 1024, 1);
80
+        if ($bytes < 1024) {
81
+            return "$bytes MB";
82
+        }
83
+        $bytes = round($bytes / 1024, 1);
84
+        if ($bytes < 1024) {
85
+            return "$bytes GB";
86
+        }
87
+        $bytes = round($bytes / 1024, 1);
88
+        if ($bytes < 1024) {
89
+            return "$bytes TB";
90
+        }
91
+
92
+        $bytes = round($bytes / 1024, 1);
93
+        return "$bytes PB";
94
+    }
95
+
96
+    /**
97
+     * Make a computer file size
98
+     * @param string $str file size in human readable format
99
+     * @return false|int|float a file size in bytes
100
+     *
101
+     * Makes 2kB to 2048.
102
+     *
103
+     * Inspired by: https://www.php.net/manual/en/function.filesize.php#92418
104
+     */
105
+    public static function computerFileSize(string $str): false|int|float {
106
+        $str = strtolower($str);
107
+        if (is_numeric($str)) {
108
+            return Util::numericToNumber($str);
109
+        }
110
+
111
+        $bytes_array = [
112
+            'b' => 1,
113
+            'k' => 1024,
114
+            'kb' => 1024,
115
+            'mb' => 1024 * 1024,
116
+            'm' => 1024 * 1024,
117
+            'gb' => 1024 * 1024 * 1024,
118
+            'g' => 1024 * 1024 * 1024,
119
+            'tb' => 1024 * 1024 * 1024 * 1024,
120
+            't' => 1024 * 1024 * 1024 * 1024,
121
+            'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
122
+            'p' => 1024 * 1024 * 1024 * 1024 * 1024,
123
+        ];
124
+
125
+        $bytes = (float)$str;
126
+
127
+        if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
128
+            $bytes *= $bytes_array[$matches[1]];
129
+        } else {
130
+            return false;
131
+        }
132
+
133
+        return Util::numericToNumber(round($bytes));
134
+    }
135
+
136
+    /**
137
+     * Recursive copying of folders
138
+     * @param string $src source folder
139
+     * @param string $dest target folder
140
+     * @return void
141
+     */
142
+    public static function copyr($src, $dest) {
143
+        if (is_dir($src)) {
144
+            if (!is_dir($dest)) {
145
+                mkdir($dest);
146
+            }
147
+            $files = scandir($src);
148
+            foreach ($files as $file) {
149
+                if ($file != "." && $file != "..") {
150
+                    self::copyr("$src/$file", "$dest/$file");
151
+                }
152
+            }
153
+        } elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
154
+            copy($src, $dest);
155
+        }
156
+    }
157
+
158
+    /**
159
+     * Recursive deletion of folders
160
+     * @param string $dir path to the folder
161
+     * @param bool $deleteSelf if set to false only the content of the folder will be deleted
162
+     * @return bool
163
+     */
164
+    public static function rmdirr($dir, $deleteSelf = true) {
165
+        if (is_dir($dir)) {
166
+            $files = new RecursiveIteratorIterator(
167
+                new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
168
+                RecursiveIteratorIterator::CHILD_FIRST
169
+            );
170
+
171
+            foreach ($files as $fileInfo) {
172
+                /** @var SplFileInfo $fileInfo */
173
+                if ($fileInfo->isLink()) {
174
+                    unlink($fileInfo->getPathname());
175
+                } elseif ($fileInfo->isDir()) {
176
+                    rmdir($fileInfo->getRealPath());
177
+                } else {
178
+                    unlink($fileInfo->getRealPath());
179
+                }
180
+            }
181
+            if ($deleteSelf) {
182
+                rmdir($dir);
183
+            }
184
+        } elseif (file_exists($dir)) {
185
+            if ($deleteSelf) {
186
+                unlink($dir);
187
+            }
188
+        }
189
+        if (!$deleteSelf) {
190
+            return true;
191
+        }
192
+
193
+        return !file_exists($dir);
194
+    }
195
+
196
+    /**
197
+     * @deprecated 18.0.0
198
+     * @return \OC\Files\Type\TemplateManager
199
+     */
200
+    public static function getFileTemplateManager() {
201
+        if (!self::$templateManager) {
202
+            self::$templateManager = new \OC\Files\Type\TemplateManager();
203
+        }
204
+        return self::$templateManager;
205
+    }
206
+
207
+    /**
208
+     * detect if a given program is found in the search PATH
209
+     *
210
+     * @param string $name
211
+     * @param bool $path
212
+     * @internal param string $program name
213
+     * @internal param string $optional search path, defaults to $PATH
214
+     * @return bool    true if executable program found in path
215
+     */
216
+    public static function canExecute($name, $path = false) {
217
+        // path defaults to PATH from environment if not set
218
+        if ($path === false) {
219
+            $path = getenv("PATH");
220
+        }
221
+        // we look for an executable file of that name
222
+        $exts = [""];
223
+        $check_fn = "is_executable";
224
+        // Default check will be done with $path directories :
225
+        $dirs = explode(PATH_SEPARATOR, $path);
226
+        // WARNING : We have to check if open_basedir is enabled :
227
+        $obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
228
+        if ($obd != "none") {
229
+            $obd_values = explode(PATH_SEPARATOR, $obd);
230
+            if (count($obd_values) > 0 and $obd_values[0]) {
231
+                // open_basedir is in effect !
232
+                // We need to check if the program is in one of these dirs :
233
+                $dirs = $obd_values;
234
+            }
235
+        }
236
+        foreach ($dirs as $dir) {
237
+            foreach ($exts as $ext) {
238
+                if ($check_fn("$dir/$name" . $ext)) {
239
+                    return true;
240
+                }
241
+            }
242
+        }
243
+        return false;
244
+    }
245
+
246
+    /**
247
+     * copy the contents of one stream to another
248
+     *
249
+     * @param resource $source
250
+     * @param resource $target
251
+     * @return array the number of bytes copied and result
252
+     */
253
+    public static function streamCopy($source, $target) {
254
+        if (!$source or !$target) {
255
+            return [0, false];
256
+        }
257
+        $bufSize = 8192;
258
+        $result = true;
259
+        $count = 0;
260
+        while (!feof($source)) {
261
+            $buf = fread($source, $bufSize);
262
+            $bytesWritten = fwrite($target, $buf);
263
+            if ($bytesWritten !== false) {
264
+                $count += $bytesWritten;
265
+            }
266
+            // note: strlen is expensive so only use it when necessary,
267
+            // on the last block
268
+            if ($bytesWritten === false
269
+                || ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
270
+            ) {
271
+                // write error, could be disk full ?
272
+                $result = false;
273
+                break;
274
+            }
275
+        }
276
+        return [$count, $result];
277
+    }
278
+
279
+    /**
280
+     * Adds a suffix to the name in case the file exists
281
+     *
282
+     * @param string $path
283
+     * @param string $filename
284
+     * @return string
285
+     */
286
+    public static function buildNotExistingFileName($path, $filename) {
287
+        $view = \OC\Files\Filesystem::getView();
288
+        return self::buildNotExistingFileNameForView($path, $filename, $view);
289
+    }
290
+
291
+    /**
292
+     * Adds a suffix to the name in case the file exists
293
+     *
294
+     * @param string $path
295
+     * @param string $filename
296
+     * @return string
297
+     */
298
+    public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
299
+        if ($path === '/') {
300
+            $path = '';
301
+        }
302
+        if ($pos = strrpos($filename, '.')) {
303
+            $name = substr($filename, 0, $pos);
304
+            $ext = substr($filename, $pos);
305
+        } else {
306
+            $name = $filename;
307
+            $ext = '';
308
+        }
309
+
310
+        $newpath = $path . '/' . $filename;
311
+        if ($view->file_exists($newpath)) {
312
+            if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
313
+                //Replace the last "(number)" with "(number+1)"
314
+                $last_match = count($matches[0]) - 1;
315
+                $counter = $matches[1][$last_match][0] + 1;
316
+                $offset = $matches[0][$last_match][1];
317
+                $match_length = strlen($matches[0][$last_match][0]);
318
+            } else {
319
+                $counter = 2;
320
+                $match_length = 0;
321
+                $offset = false;
322
+            }
323
+            do {
324
+                if ($offset) {
325
+                    //Replace the last "(number)" with "(number+1)"
326
+                    $newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
327
+                } else {
328
+                    $newname = $name . ' (' . $counter . ')';
329
+                }
330
+                $newpath = $path . '/' . $newname . $ext;
331
+                $counter++;
332
+            } while ($view->file_exists($newpath));
333
+        }
334
+
335
+        return $newpath;
336
+    }
337
+
338
+    /**
339
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
340
+     *
341
+     * @param array $input The array to work on
342
+     * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
343
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
344
+     * @return array
345
+     *
346
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
347
+     * based on https://www.php.net/manual/en/function.array-change-key-case.php#107715
348
+     *
349
+     */
350
+    public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
351
+        $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
352
+        $ret = [];
353
+        foreach ($input as $k => $v) {
354
+            $ret[mb_convert_case($k, $case, $encoding)] = $v;
355
+        }
356
+        return $ret;
357
+    }
358
+
359
+    /**
360
+     * performs a search in a nested array
361
+     * @param array $haystack the array to be searched
362
+     * @param string $needle the search string
363
+     * @param mixed $index optional, only search this key name
364
+     * @return mixed the key of the matching field, otherwise false
365
+     *
366
+     * performs a search in a nested array
367
+     *
368
+     * taken from https://www.php.net/manual/en/function.array-search.php#97645
369
+     */
370
+    public static function recursiveArraySearch($haystack, $needle, $index = null) {
371
+        $aIt = new RecursiveArrayIterator($haystack);
372
+        $it = new RecursiveIteratorIterator($aIt);
373
+
374
+        while ($it->valid()) {
375
+            if (((isset($index) and ($it->key() == $index)) or !isset($index)) and ($it->current() == $needle)) {
376
+                return $aIt->key();
377
+            }
378
+
379
+            $it->next();
380
+        }
381
+
382
+        return false;
383
+    }
384
+
385
+    /**
386
+     * calculates the maximum upload size respecting system settings, free space and user quota
387
+     *
388
+     * @param string $dir the current folder where the user currently operates
389
+     * @param int|float $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
390
+     * @return int|float number of bytes representing
391
+     */
392
+    public static function maxUploadFilesize($dir, $freeSpace = null) {
393
+        if (is_null($freeSpace) || $freeSpace < 0) {
394
+            $freeSpace = self::freeSpace($dir);
395
+        }
396
+        return min($freeSpace, self::uploadLimit());
397
+    }
398
+
399
+    /**
400
+     * Calculate free space left within user quota
401
+     *
402
+     * @param string $dir the current folder where the user currently operates
403
+     * @return int|float number of bytes representing
404
+     */
405
+    public static function freeSpace($dir) {
406
+        $freeSpace = \OC\Files\Filesystem::free_space($dir);
407
+        if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
408
+            $freeSpace = max($freeSpace, 0);
409
+            return $freeSpace;
410
+        } else {
411
+            return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
412
+        }
413
+    }
414
+
415
+    /**
416
+     * Calculate PHP upload limit
417
+     *
418
+     * @return int|float PHP upload file size limit
419
+     */
420
+    public static function uploadLimit() {
421
+        $ini = \OC::$server->get(IniGetWrapper::class);
422
+        $upload_max_filesize = Util::computerFileSize($ini->get('upload_max_filesize')) ?: 0;
423
+        $post_max_size = Util::computerFileSize($ini->get('post_max_size')) ?: 0;
424
+        if ($upload_max_filesize === 0 && $post_max_size === 0) {
425
+            return INF;
426
+        } elseif ($upload_max_filesize === 0 || $post_max_size === 0) {
427
+            return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
428
+        } else {
429
+            return min($upload_max_filesize, $post_max_size);
430
+        }
431
+    }
432
+
433
+    /**
434
+     * Checks if a function is available
435
+     *
436
+     * @deprecated Since 25.0.0 use \OCP\Util::isFunctionEnabled instead
437
+     */
438
+    public static function is_function_enabled(string $function_name): bool {
439
+        return \OCP\Util::isFunctionEnabled($function_name);
440
+    }
441
+
442
+    /**
443
+     * Try to find a program
444
+     * @deprecated Since 25.0.0 Use \OC\BinaryFinder directly
445
+     */
446
+    public static function findBinaryPath(string $program): ?string {
447
+        $result = \OCP\Server::get(IBinaryFinder::class)->findBinaryPath($program);
448
+        return $result !== false ? $result : null;
449
+    }
450
+
451
+    /**
452
+     * Calculate the disc space for the given path
453
+     *
454
+     * BEWARE: this requires that Util::setupFS() was called
455
+     * already !
456
+     *
457
+     * @param string $path
458
+     * @param \OCP\Files\FileInfo $rootInfo (optional)
459
+     * @param bool $includeMountPoints whether to include mount points in the size calculation
460
+     * @param bool $useCache whether to use the cached quota values
461
+     * @return array
462
+     * @throws \OCP\Files\NotFoundException
463
+     */
464
+    public static function getStorageInfo($path, $rootInfo = null, $includeMountPoints = true, $useCache = true) {
465
+        /** @var ICacheFactory $cacheFactory */
466
+        $cacheFactory = \OC::$server->get(ICacheFactory::class);
467
+        $memcache = $cacheFactory->createLocal('storage_info');
468
+
469
+        // return storage info without adding mount points
470
+        $includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
471
+
472
+        $view = Filesystem::getView();
473
+        if (!$view) {
474
+            throw new \OCP\Files\NotFoundException();
475
+        }
476
+        $fullPath = Filesystem::normalizePath($view->getAbsolutePath($path));
477
+
478
+        $cacheKey = $fullPath. '::' . ($includeMountPoints ? 'include' : 'exclude');
479
+        if ($useCache) {
480
+            $cached = $memcache->get($cacheKey);
481
+            if ($cached) {
482
+                return $cached;
483
+            }
484
+        }
485
+
486
+        if (!$rootInfo) {
487
+            $rootInfo = \OC\Files\Filesystem::getFileInfo($path, $includeExtStorage ? 'ext' : false);
488
+        }
489
+        if (!$rootInfo instanceof \OCP\Files\FileInfo) {
490
+            throw new \OCP\Files\NotFoundException();
491
+        }
492
+        $used = $rootInfo->getSize($includeMountPoints);
493
+        if ($used < 0) {
494
+            $used = 0;
495
+        }
496
+        $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
497
+        $mount = $rootInfo->getMountPoint();
498
+        $storage = $mount->getStorage();
499
+        $sourceStorage = $storage;
500
+        if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
501
+            $includeExtStorage = false;
502
+        }
503
+        if ($includeExtStorage) {
504
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
505
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
506
+            ) {
507
+                /** @var \OC\Files\Storage\Home $storage */
508
+                $user = $storage->getUser();
509
+            } else {
510
+                $user = \OC::$server->getUserSession()->getUser();
511
+            }
512
+            $quota = OC_Util::getUserQuota($user);
513
+            if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
514
+                // always get free space / total space from root + mount points
515
+                return self::getGlobalStorageInfo($quota, $user, $mount);
516
+            }
517
+        }
518
+
519
+        // TODO: need a better way to get total space from storage
520
+        if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
521
+            /** @var \OC\Files\Storage\Wrapper\Quota $storage */
522
+            $quota = $sourceStorage->getQuota();
523
+        }
524
+        try {
525
+            $free = $sourceStorage->free_space($rootInfo->getInternalPath());
526
+        } catch (\Exception $e) {
527
+            if ($path === "") {
528
+                throw $e;
529
+            }
530
+            /** @var LoggerInterface $logger */
531
+            $logger = \OC::$server->get(LoggerInterface::class);
532
+            $logger->warning("Error while getting quota info, using root quota", ['exception' => $e]);
533
+            $rootInfo = self::getStorageInfo("");
534
+            $memcache->set($cacheKey, $rootInfo, 5 * 60);
535
+            return $rootInfo;
536
+        }
537
+        if ($free >= 0) {
538
+            $total = $free + $used;
539
+        } else {
540
+            $total = $free; //either unknown or unlimited
541
+        }
542
+        if ($total > 0) {
543
+            if ($quota > 0 && $total > $quota) {
544
+                $total = $quota;
545
+            }
546
+            // prevent division by zero or error codes (negative values)
547
+            $relative = round(($used / $total) * 10000) / 100;
548
+        } else {
549
+            $relative = 0;
550
+        }
551
+
552
+        $ownerId = $storage->getOwner($path);
553
+        $ownerDisplayName = '';
554
+        if ($ownerId) {
555
+            $ownerDisplayName = \OC::$server->getUserManager()->getDisplayName($ownerId) ?? '';
556
+        }
557
+
558
+        if (substr_count($mount->getMountPoint(), '/') < 3) {
559
+            $mountPoint = '';
560
+        } else {
561
+            [,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
562
+        }
563
+
564
+        $info = [
565
+            'free' => $free,
566
+            'used' => $used,
567
+            'quota' => $quota,
568
+            'total' => $total,
569
+            'relative' => $relative,
570
+            'owner' => $ownerId,
571
+            'ownerDisplayName' => $ownerDisplayName,
572
+            'mountType' => $mount->getMountType(),
573
+            'mountPoint' => trim($mountPoint, '/'),
574
+        ];
575
+
576
+        $memcache->set($cacheKey, $info, 5 * 60);
577
+
578
+        return $info;
579
+    }
580
+
581
+    /**
582
+     * Get storage info including all mount points and quota
583
+     */
584
+    private static function getGlobalStorageInfo(int|float $quota, IUser $user, IMountPoint $mount): array {
585
+        $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
586
+        $used = $rootInfo['size'];
587
+        if ($used < 0) {
588
+            $used = 0;
589
+        }
590
+
591
+        $total = $quota;
592
+        $free = $quota - $used;
593
+
594
+        if ($total > 0) {
595
+            if ($quota > 0 && $total > $quota) {
596
+                $total = $quota;
597
+            }
598
+            // prevent division by zero or error codes (negative values)
599
+            $relative = round(($used / $total) * 10000) / 100;
600
+        } else {
601
+            $relative = 0;
602
+        }
603
+
604
+        if (substr_count($mount->getMountPoint(), '/') < 3) {
605
+            $mountPoint = '';
606
+        } else {
607
+            [,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
608
+        }
609
+
610
+        return [
611
+            'free' => $free,
612
+            'used' => $used,
613
+            'total' => $total,
614
+            'relative' => $relative,
615
+            'quota' => $quota,
616
+            'owner' => $user->getUID(),
617
+            'ownerDisplayName' => $user->getDisplayName(),
618
+            'mountType' => $mount->getMountType(),
619
+            'mountPoint' => trim($mountPoint, '/'),
620
+        ];
621
+    }
622
+
623
+    public static function clearStorageInfo(string $absolutePath): void {
624
+        /** @var ICacheFactory $cacheFactory */
625
+        $cacheFactory = \OC::$server->get(ICacheFactory::class);
626
+        $memcache = $cacheFactory->createLocal('storage_info');
627
+        $cacheKeyPrefix = Filesystem::normalizePath($absolutePath) . '::';
628
+        $memcache->remove($cacheKeyPrefix . 'include');
629
+        $memcache->remove($cacheKeyPrefix . 'exclude');
630
+    }
631
+
632
+    /**
633
+     * Returns whether the config file is set manually to read-only
634
+     * @return bool
635
+     */
636
+    public static function isReadOnlyConfigEnabled() {
637
+        return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
638
+    }
639 639
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
 	 *
66 66
 	 * Makes 2048 to 2 kB.
67 67
 	 */
68
-	public static function humanFileSize(int|float $bytes): string {
68
+	public static function humanFileSize(int | float $bytes): string {
69 69
 		if ($bytes < 0) {
70 70
 			return "?";
71 71
 		}
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 	 *
103 103
 	 * Inspired by: https://www.php.net/manual/en/function.filesize.php#92418
104 104
 	 */
105
-	public static function computerFileSize(string $str): false|int|float {
105
+	public static function computerFileSize(string $str): false | int | float {
106 106
 		$str = strtolower($str);
107 107
 		if (is_numeric($str)) {
108 108
 			return Util::numericToNumber($str);
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
 			'p' => 1024 * 1024 * 1024 * 1024 * 1024,
123 123
 		];
124 124
 
125
-		$bytes = (float)$str;
125
+		$bytes = (float) $str;
126 126
 
127 127
 		if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
128 128
 			$bytes *= $bytes_array[$matches[1]];
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 		}
236 236
 		foreach ($dirs as $dir) {
237 237
 			foreach ($exts as $ext) {
238
-				if ($check_fn("$dir/$name" . $ext)) {
238
+				if ($check_fn("$dir/$name".$ext)) {
239 239
 					return true;
240 240
 				}
241 241
 			}
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
 			$ext = '';
308 308
 		}
309 309
 
310
-		$newpath = $path . '/' . $filename;
310
+		$newpath = $path.'/'.$filename;
311 311
 		if ($view->file_exists($newpath)) {
312 312
 			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
313 313
 				//Replace the last "(number)" with "(number+1)"
@@ -323,11 +323,11 @@  discard block
 block discarded – undo
323 323
 			do {
324 324
 				if ($offset) {
325 325
 					//Replace the last "(number)" with "(number+1)"
326
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
326
+					$newname = substr_replace($name, '('.$counter.')', $offset, $match_length);
327 327
 				} else {
328
-					$newname = $name . ' (' . $counter . ')';
328
+					$newname = $name.' ('.$counter.')';
329 329
 				}
330
-				$newpath = $path . '/' . $newname . $ext;
330
+				$newpath = $path.'/'.$newname.$ext;
331 331
 				$counter++;
332 332
 			} while ($view->file_exists($newpath));
333 333
 		}
@@ -408,7 +408,7 @@  discard block
 block discarded – undo
408 408
 			$freeSpace = max($freeSpace, 0);
409 409
 			return $freeSpace;
410 410
 		} else {
411
-			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
411
+			return (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
412 412
 		}
413 413
 	}
414 414
 
@@ -475,7 +475,7 @@  discard block
 block discarded – undo
475 475
 		}
476 476
 		$fullPath = Filesystem::normalizePath($view->getAbsolutePath($path));
477 477
 
478
-		$cacheKey = $fullPath. '::' . ($includeMountPoints ? 'include' : 'exclude');
478
+		$cacheKey = $fullPath.'::'.($includeMountPoints ? 'include' : 'exclude');
479 479
 		if ($useCache) {
480 480
 			$cached = $memcache->get($cacheKey);
481 481
 			if ($cached) {
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
 	/**
582 582
 	 * Get storage info including all mount points and quota
583 583
 	 */
584
-	private static function getGlobalStorageInfo(int|float $quota, IUser $user, IMountPoint $mount): array {
584
+	private static function getGlobalStorageInfo(int | float $quota, IUser $user, IMountPoint $mount): array {
585 585
 		$rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
586 586
 		$used = $rootInfo['size'];
587 587
 		if ($used < 0) {
@@ -624,9 +624,9 @@  discard block
 block discarded – undo
624 624
 		/** @var ICacheFactory $cacheFactory */
625 625
 		$cacheFactory = \OC::$server->get(ICacheFactory::class);
626 626
 		$memcache = $cacheFactory->createLocal('storage_info');
627
-		$cacheKeyPrefix = Filesystem::normalizePath($absolutePath) . '::';
628
-		$memcache->remove($cacheKeyPrefix . 'include');
629
-		$memcache->remove($cacheKeyPrefix . 'exclude');
627
+		$cacheKeyPrefix = Filesystem::normalizePath($absolutePath).'::';
628
+		$memcache->remove($cacheKeyPrefix.'include');
629
+		$memcache->remove($cacheKeyPrefix.'exclude');
630 630
 	}
631 631
 
632 632
 	/**
Please login to merge, or discard this patch.
lib/private/Files/View.php 1 patch
Indentation   +2128 added lines, -2128 removed lines patch added patch discarded remove patch
@@ -86,2132 +86,2132 @@
 block discarded – undo
86 86
  * \OC\Files\Storage\Storage object
87 87
  */
88 88
 class View {
89
-	/** @var string */
90
-	private $fakeRoot = '';
91
-
92
-	/**
93
-	 * @var \OCP\Lock\ILockingProvider
94
-	 */
95
-	protected $lockingProvider;
96
-
97
-	private $lockingEnabled;
98
-
99
-	private $updaterEnabled = true;
100
-
101
-	/** @var \OC\User\Manager */
102
-	private $userManager;
103
-
104
-	private LoggerInterface $logger;
105
-
106
-	/**
107
-	 * @param string $root
108
-	 * @throws \Exception If $root contains an invalid path
109
-	 */
110
-	public function __construct($root = '') {
111
-		if (is_null($root)) {
112
-			throw new \InvalidArgumentException('Root can\'t be null');
113
-		}
114
-		if (!Filesystem::isValidPath($root)) {
115
-			throw new \Exception();
116
-		}
117
-
118
-		$this->fakeRoot = $root;
119
-		$this->lockingProvider = \OC::$server->getLockingProvider();
120
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
121
-		$this->userManager = \OC::$server->getUserManager();
122
-		$this->logger = \OC::$server->get(LoggerInterface::class);
123
-	}
124
-
125
-	public function getAbsolutePath($path = '/') {
126
-		if ($path === null) {
127
-			return null;
128
-		}
129
-		$this->assertPathLength($path);
130
-		if ($path === '') {
131
-			$path = '/';
132
-		}
133
-		if ($path[0] !== '/') {
134
-			$path = '/' . $path;
135
-		}
136
-		return $this->fakeRoot . $path;
137
-	}
138
-
139
-	/**
140
-	 * change the root to a fake root
141
-	 *
142
-	 * @param string $fakeRoot
143
-	 * @return boolean|null
144
-	 */
145
-	public function chroot($fakeRoot) {
146
-		if (!$fakeRoot == '') {
147
-			if ($fakeRoot[0] !== '/') {
148
-				$fakeRoot = '/' . $fakeRoot;
149
-			}
150
-		}
151
-		$this->fakeRoot = $fakeRoot;
152
-	}
153
-
154
-	/**
155
-	 * get the fake root
156
-	 *
157
-	 * @return string
158
-	 */
159
-	public function getRoot() {
160
-		return $this->fakeRoot;
161
-	}
162
-
163
-	/**
164
-	 * get path relative to the root of the view
165
-	 *
166
-	 * @param string $path
167
-	 * @return ?string
168
-	 */
169
-	public function getRelativePath($path) {
170
-		$this->assertPathLength($path);
171
-		if ($this->fakeRoot == '') {
172
-			return $path;
173
-		}
174
-
175
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
176
-			return '/';
177
-		}
178
-
179
-		// missing slashes can cause wrong matches!
180
-		$root = rtrim($this->fakeRoot, '/') . '/';
181
-
182
-		if (strpos($path, $root) !== 0) {
183
-			return null;
184
-		} else {
185
-			$path = substr($path, strlen($this->fakeRoot));
186
-			if (strlen($path) === 0) {
187
-				return '/';
188
-			} else {
189
-				return $path;
190
-			}
191
-		}
192
-	}
193
-
194
-	/**
195
-	 * get the mountpoint of the storage object for a path
196
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
197
-	 * returned mountpoint is relative to the absolute root of the filesystem
198
-	 * and does not take the chroot into account )
199
-	 *
200
-	 * @param string $path
201
-	 * @return string
202
-	 */
203
-	public function getMountPoint($path) {
204
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
205
-	}
206
-
207
-	/**
208
-	 * get the mountpoint of the storage object for a path
209
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
210
-	 * returned mountpoint is relative to the absolute root of the filesystem
211
-	 * and does not take the chroot into account )
212
-	 *
213
-	 * @param string $path
214
-	 * @return \OCP\Files\Mount\IMountPoint
215
-	 */
216
-	public function getMount($path) {
217
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
218
-	}
219
-
220
-	/**
221
-	 * resolve a path to a storage and internal path
222
-	 *
223
-	 * @param string $path
224
-	 * @return array an array consisting of the storage and the internal path
225
-	 */
226
-	public function resolvePath($path) {
227
-		$a = $this->getAbsolutePath($path);
228
-		$p = Filesystem::normalizePath($a);
229
-		return Filesystem::resolvePath($p);
230
-	}
231
-
232
-	/**
233
-	 * return the path to a local version of the file
234
-	 * we need this because we can't know if a file is stored local or not from
235
-	 * outside the filestorage and for some purposes a local file is needed
236
-	 *
237
-	 * @param string $path
238
-	 * @return string
239
-	 */
240
-	public function getLocalFile($path) {
241
-		$parent = substr($path, 0, strrpos($path, '/'));
242
-		$path = $this->getAbsolutePath($path);
243
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
244
-		if (Filesystem::isValidPath($parent) and $storage) {
245
-			return $storage->getLocalFile($internalPath);
246
-		} else {
247
-			return null;
248
-		}
249
-	}
250
-
251
-	/**
252
-	 * @param string $path
253
-	 * @return string
254
-	 */
255
-	public function getLocalFolder($path) {
256
-		$parent = substr($path, 0, strrpos($path, '/'));
257
-		$path = $this->getAbsolutePath($path);
258
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
259
-		if (Filesystem::isValidPath($parent) and $storage) {
260
-			return $storage->getLocalFolder($internalPath);
261
-		} else {
262
-			return null;
263
-		}
264
-	}
265
-
266
-	/**
267
-	 * the following functions operate with arguments and return values identical
268
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
269
-	 * for \OC\Files\Storage\Storage via basicOperation().
270
-	 */
271
-	public function mkdir($path) {
272
-		return $this->basicOperation('mkdir', $path, ['create', 'write']);
273
-	}
274
-
275
-	/**
276
-	 * remove mount point
277
-	 *
278
-	 * @param IMountPoint $mount
279
-	 * @param string $path relative to data/
280
-	 * @return boolean
281
-	 */
282
-	protected function removeMount($mount, $path) {
283
-		if ($mount instanceof MoveableMount) {
284
-			// cut of /user/files to get the relative path to data/user/files
285
-			$pathParts = explode('/', $path, 4);
286
-			$relPath = '/' . $pathParts[3];
287
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
288
-			\OC_Hook::emit(
289
-				Filesystem::CLASSNAME, "umount",
290
-				[Filesystem::signal_param_path => $relPath]
291
-			);
292
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
293
-			$result = $mount->removeMount();
294
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
295
-			if ($result) {
296
-				\OC_Hook::emit(
297
-					Filesystem::CLASSNAME, "post_umount",
298
-					[Filesystem::signal_param_path => $relPath]
299
-				);
300
-			}
301
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
302
-			return $result;
303
-		} else {
304
-			// do not allow deleting the storage's root / the mount point
305
-			// because for some storages it might delete the whole contents
306
-			// but isn't supposed to work that way
307
-			return false;
308
-		}
309
-	}
310
-
311
-	public function disableCacheUpdate() {
312
-		$this->updaterEnabled = false;
313
-	}
314
-
315
-	public function enableCacheUpdate() {
316
-		$this->updaterEnabled = true;
317
-	}
318
-
319
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
320
-		if ($this->updaterEnabled) {
321
-			if (is_null($time)) {
322
-				$time = time();
323
-			}
324
-			$storage->getUpdater()->update($internalPath, $time);
325
-		}
326
-	}
327
-
328
-	protected function removeUpdate(Storage $storage, $internalPath) {
329
-		if ($this->updaterEnabled) {
330
-			$storage->getUpdater()->remove($internalPath);
331
-		}
332
-	}
333
-
334
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
335
-		if ($this->updaterEnabled) {
336
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
337
-		}
338
-	}
339
-
340
-	/**
341
-	 * @param string $path
342
-	 * @return bool|mixed
343
-	 */
344
-	public function rmdir($path) {
345
-		$absolutePath = $this->getAbsolutePath($path);
346
-		$mount = Filesystem::getMountManager()->find($absolutePath);
347
-		if ($mount->getInternalPath($absolutePath) === '') {
348
-			return $this->removeMount($mount, $absolutePath);
349
-		}
350
-		if ($this->is_dir($path)) {
351
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
352
-		} else {
353
-			$result = false;
354
-		}
355
-
356
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
357
-			$storage = $mount->getStorage();
358
-			$internalPath = $mount->getInternalPath($absolutePath);
359
-			$storage->getUpdater()->remove($internalPath);
360
-		}
361
-		return $result;
362
-	}
363
-
364
-	/**
365
-	 * @param string $path
366
-	 * @return resource
367
-	 */
368
-	public function opendir($path) {
369
-		return $this->basicOperation('opendir', $path, ['read']);
370
-	}
371
-
372
-	/**
373
-	 * @param string $path
374
-	 * @return bool|mixed
375
-	 */
376
-	public function is_dir($path) {
377
-		if ($path == '/') {
378
-			return true;
379
-		}
380
-		return $this->basicOperation('is_dir', $path);
381
-	}
382
-
383
-	/**
384
-	 * @param string $path
385
-	 * @return bool|mixed
386
-	 */
387
-	public function is_file($path) {
388
-		if ($path == '/') {
389
-			return false;
390
-		}
391
-		return $this->basicOperation('is_file', $path);
392
-	}
393
-
394
-	/**
395
-	 * @param string $path
396
-	 * @return mixed
397
-	 */
398
-	public function stat($path) {
399
-		return $this->basicOperation('stat', $path);
400
-	}
401
-
402
-	/**
403
-	 * @param string $path
404
-	 * @return mixed
405
-	 */
406
-	public function filetype($path) {
407
-		return $this->basicOperation('filetype', $path);
408
-	}
409
-
410
-	/**
411
-	 * @param string $path
412
-	 * @return mixed
413
-	 */
414
-	public function filesize(string $path) {
415
-		return $this->basicOperation('filesize', $path);
416
-	}
417
-
418
-	/**
419
-	 * @param string $path
420
-	 * @return bool|mixed
421
-	 * @throws \OCP\Files\InvalidPathException
422
-	 */
423
-	public function readfile($path) {
424
-		$this->assertPathLength($path);
425
-		if (ob_get_level()) {
426
-			ob_end_clean();
427
-		}
428
-		$handle = $this->fopen($path, 'rb');
429
-		if ($handle) {
430
-			$chunkSize = 524288; // 512 kB chunks
431
-			while (!feof($handle)) {
432
-				echo fread($handle, $chunkSize);
433
-				flush();
434
-			}
435
-			fclose($handle);
436
-			return $this->filesize($path);
437
-		}
438
-		return false;
439
-	}
440
-
441
-	/**
442
-	 * @param string $path
443
-	 * @param int $from
444
-	 * @param int $to
445
-	 * @return bool|mixed
446
-	 * @throws \OCP\Files\InvalidPathException
447
-	 * @throws \OCP\Files\UnseekableException
448
-	 */
449
-	public function readfilePart($path, $from, $to) {
450
-		$this->assertPathLength($path);
451
-		if (ob_get_level()) {
452
-			ob_end_clean();
453
-		}
454
-		$handle = $this->fopen($path, 'rb');
455
-		if ($handle) {
456
-			$chunkSize = 524288; // 512 kB chunks
457
-			$startReading = true;
458
-
459
-			if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
460
-				// forward file handle via chunked fread because fseek seem to have failed
461
-
462
-				$end = $from + 1;
463
-				while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
464
-					$len = $from - ftell($handle);
465
-					if ($len > $chunkSize) {
466
-						$len = $chunkSize;
467
-					}
468
-					$result = fread($handle, $len);
469
-
470
-					if ($result === false) {
471
-						$startReading = false;
472
-						break;
473
-					}
474
-				}
475
-			}
476
-
477
-			if ($startReading) {
478
-				$end = $to + 1;
479
-				while (!feof($handle) && ftell($handle) < $end) {
480
-					$len = $end - ftell($handle);
481
-					if ($len > $chunkSize) {
482
-						$len = $chunkSize;
483
-					}
484
-					echo fread($handle, $len);
485
-					flush();
486
-				}
487
-				return ftell($handle) - $from;
488
-			}
489
-
490
-			throw new \OCP\Files\UnseekableException('fseek error');
491
-		}
492
-		return false;
493
-	}
494
-
495
-	/**
496
-	 * @param string $path
497
-	 * @return mixed
498
-	 */
499
-	public function isCreatable($path) {
500
-		return $this->basicOperation('isCreatable', $path);
501
-	}
502
-
503
-	/**
504
-	 * @param string $path
505
-	 * @return mixed
506
-	 */
507
-	public function isReadable($path) {
508
-		return $this->basicOperation('isReadable', $path);
509
-	}
510
-
511
-	/**
512
-	 * @param string $path
513
-	 * @return mixed
514
-	 */
515
-	public function isUpdatable($path) {
516
-		return $this->basicOperation('isUpdatable', $path);
517
-	}
518
-
519
-	/**
520
-	 * @param string $path
521
-	 * @return bool|mixed
522
-	 */
523
-	public function isDeletable($path) {
524
-		$absolutePath = $this->getAbsolutePath($path);
525
-		$mount = Filesystem::getMountManager()->find($absolutePath);
526
-		if ($mount->getInternalPath($absolutePath) === '') {
527
-			return $mount instanceof MoveableMount;
528
-		}
529
-		return $this->basicOperation('isDeletable', $path);
530
-	}
531
-
532
-	/**
533
-	 * @param string $path
534
-	 * @return mixed
535
-	 */
536
-	public function isSharable($path) {
537
-		return $this->basicOperation('isSharable', $path);
538
-	}
539
-
540
-	/**
541
-	 * @param string $path
542
-	 * @return bool|mixed
543
-	 */
544
-	public function file_exists($path) {
545
-		if ($path == '/') {
546
-			return true;
547
-		}
548
-		return $this->basicOperation('file_exists', $path);
549
-	}
550
-
551
-	/**
552
-	 * @param string $path
553
-	 * @return mixed
554
-	 */
555
-	public function filemtime($path) {
556
-		return $this->basicOperation('filemtime', $path);
557
-	}
558
-
559
-	/**
560
-	 * @param string $path
561
-	 * @param int|string $mtime
562
-	 * @return bool
563
-	 */
564
-	public function touch($path, $mtime = null) {
565
-		if (!is_null($mtime) and !is_numeric($mtime)) {
566
-			$mtime = strtotime($mtime);
567
-		}
568
-
569
-		$hooks = ['touch'];
570
-
571
-		if (!$this->file_exists($path)) {
572
-			$hooks[] = 'create';
573
-			$hooks[] = 'write';
574
-		}
575
-		try {
576
-			$result = $this->basicOperation('touch', $path, $hooks, $mtime);
577
-		} catch (\Exception $e) {
578
-			$this->logger->info('Error while setting modified time', ['app' => 'core', 'exception' => $e]);
579
-			$result = false;
580
-		}
581
-		if (!$result) {
582
-			// If create file fails because of permissions on external storage like SMB folders,
583
-			// check file exists and return false if not.
584
-			if (!$this->file_exists($path)) {
585
-				return false;
586
-			}
587
-			if (is_null($mtime)) {
588
-				$mtime = time();
589
-			}
590
-			//if native touch fails, we emulate it by changing the mtime in the cache
591
-			$this->putFileInfo($path, ['mtime' => floor($mtime)]);
592
-		}
593
-		return true;
594
-	}
595
-
596
-	/**
597
-	 * @param string $path
598
-	 * @return mixed
599
-	 * @throws LockedException
600
-	 */
601
-	public function file_get_contents($path) {
602
-		return $this->basicOperation('file_get_contents', $path, ['read']);
603
-	}
604
-
605
-	/**
606
-	 * @param bool $exists
607
-	 * @param string $path
608
-	 * @param bool $run
609
-	 */
610
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
611
-		if (!$exists) {
612
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
613
-				Filesystem::signal_param_path => $this->getHookPath($path),
614
-				Filesystem::signal_param_run => &$run,
615
-			]);
616
-		} else {
617
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
618
-				Filesystem::signal_param_path => $this->getHookPath($path),
619
-				Filesystem::signal_param_run => &$run,
620
-			]);
621
-		}
622
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
623
-			Filesystem::signal_param_path => $this->getHookPath($path),
624
-			Filesystem::signal_param_run => &$run,
625
-		]);
626
-	}
627
-
628
-	/**
629
-	 * @param bool $exists
630
-	 * @param string $path
631
-	 */
632
-	protected function emit_file_hooks_post($exists, $path) {
633
-		if (!$exists) {
634
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
635
-				Filesystem::signal_param_path => $this->getHookPath($path),
636
-			]);
637
-		} else {
638
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
639
-				Filesystem::signal_param_path => $this->getHookPath($path),
640
-			]);
641
-		}
642
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
643
-			Filesystem::signal_param_path => $this->getHookPath($path),
644
-		]);
645
-	}
646
-
647
-	/**
648
-	 * @param string $path
649
-	 * @param string|resource $data
650
-	 * @return bool|mixed
651
-	 * @throws LockedException
652
-	 */
653
-	public function file_put_contents($path, $data) {
654
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
655
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
656
-			if (Filesystem::isValidPath($path)
657
-				and !Filesystem::isFileBlacklisted($path)
658
-			) {
659
-				$path = $this->getRelativePath($absolutePath);
660
-
661
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
662
-
663
-				$exists = $this->file_exists($path);
664
-				$run = true;
665
-				if ($this->shouldEmitHooks($path)) {
666
-					$this->emit_file_hooks_pre($exists, $path, $run);
667
-				}
668
-				if (!$run) {
669
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
670
-					return false;
671
-				}
672
-
673
-				try {
674
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
675
-				} catch (\Exception $e) {
676
-					// Release the shared lock before throwing.
677
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
678
-					throw $e;
679
-				}
680
-
681
-				/** @var \OC\Files\Storage\Storage $storage */
682
-				[$storage, $internalPath] = $this->resolvePath($path);
683
-				$target = $storage->fopen($internalPath, 'w');
684
-				if ($target) {
685
-					[, $result] = \OC_Helper::streamCopy($data, $target);
686
-					fclose($target);
687
-					fclose($data);
688
-
689
-					$this->writeUpdate($storage, $internalPath);
690
-
691
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
692
-
693
-					if ($this->shouldEmitHooks($path) && $result !== false) {
694
-						$this->emit_file_hooks_post($exists, $path);
695
-					}
696
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
697
-					return $result;
698
-				} else {
699
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
700
-					return false;
701
-				}
702
-			} else {
703
-				return false;
704
-			}
705
-		} else {
706
-			$hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
707
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
708
-		}
709
-	}
710
-
711
-	/**
712
-	 * @param string $path
713
-	 * @return bool|mixed
714
-	 */
715
-	public function unlink($path) {
716
-		if ($path === '' || $path === '/') {
717
-			// do not allow deleting the root
718
-			return false;
719
-		}
720
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
721
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
722
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
723
-		if ($mount->getInternalPath($absolutePath) === '') {
724
-			return $this->removeMount($mount, $absolutePath);
725
-		}
726
-		if ($this->is_dir($path)) {
727
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
728
-		} else {
729
-			$result = $this->basicOperation('unlink', $path, ['delete']);
730
-		}
731
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
732
-			$storage = $mount->getStorage();
733
-			$internalPath = $mount->getInternalPath($absolutePath);
734
-			$storage->getUpdater()->remove($internalPath);
735
-			return true;
736
-		} else {
737
-			return $result;
738
-		}
739
-	}
740
-
741
-	/**
742
-	 * @param string $directory
743
-	 * @return bool|mixed
744
-	 */
745
-	public function deleteAll($directory) {
746
-		return $this->rmdir($directory);
747
-	}
748
-
749
-	/**
750
-	 * Rename/move a file or folder from the source path to target path.
751
-	 *
752
-	 * @param string $source source path
753
-	 * @param string $target target path
754
-	 *
755
-	 * @return bool|mixed
756
-	 * @throws LockedException
757
-	 */
758
-	public function rename($source, $target) {
759
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
760
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
761
-		$result = false;
762
-		if (
763
-			Filesystem::isValidPath($target)
764
-			and Filesystem::isValidPath($source)
765
-			and !Filesystem::isFileBlacklisted($target)
766
-		) {
767
-			$source = $this->getRelativePath($absolutePath1);
768
-			$target = $this->getRelativePath($absolutePath2);
769
-			$exists = $this->file_exists($target);
770
-
771
-			if ($source == null or $target == null) {
772
-				return false;
773
-			}
774
-
775
-			$this->lockFile($source, ILockingProvider::LOCK_SHARED, true);
776
-			try {
777
-				$this->lockFile($target, ILockingProvider::LOCK_SHARED, true);
778
-
779
-				$run = true;
780
-				if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) {
781
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
782
-					$this->emit_file_hooks_pre($exists, $target, $run);
783
-				} elseif ($this->shouldEmitHooks($source)) {
784
-					\OC_Hook::emit(
785
-						Filesystem::CLASSNAME, Filesystem::signal_rename,
786
-						[
787
-							Filesystem::signal_param_oldpath => $this->getHookPath($source),
788
-							Filesystem::signal_param_newpath => $this->getHookPath($target),
789
-							Filesystem::signal_param_run => &$run
790
-						]
791
-					);
792
-				}
793
-				if ($run) {
794
-					$this->verifyPath(dirname($target), basename($target));
795
-
796
-					$manager = Filesystem::getMountManager();
797
-					$mount1 = $this->getMount($source);
798
-					$mount2 = $this->getMount($target);
799
-					$storage1 = $mount1->getStorage();
800
-					$storage2 = $mount2->getStorage();
801
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
802
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
803
-
804
-					$this->changeLock($source, ILockingProvider::LOCK_EXCLUSIVE, true);
805
-					try {
806
-						$this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE, true);
807
-
808
-						if ($internalPath1 === '') {
809
-							if ($mount1 instanceof MoveableMount) {
810
-								$sourceParentMount = $this->getMount(dirname($source));
811
-								if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
812
-									/**
813
-									 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
814
-									 */
815
-									$sourceMountPoint = $mount1->getMountPoint();
816
-									$result = $mount1->moveMount($absolutePath2);
817
-									$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
818
-								} else {
819
-									$result = false;
820
-								}
821
-							} else {
822
-								$result = false;
823
-							}
824
-						// moving a file/folder within the same mount point
825
-						} elseif ($storage1 === $storage2) {
826
-							if ($storage1) {
827
-								$result = $storage1->rename($internalPath1, $internalPath2);
828
-							} else {
829
-								$result = false;
830
-							}
831
-						// moving a file/folder between storages (from $storage1 to $storage2)
832
-						} else {
833
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
834
-						}
835
-
836
-						if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
837
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
838
-							$this->writeUpdate($storage2, $internalPath2);
839
-						} elseif ($result) {
840
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
841
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
842
-							}
843
-						}
844
-					} catch (\Exception $e) {
845
-						throw $e;
846
-					} finally {
847
-						$this->changeLock($source, ILockingProvider::LOCK_SHARED, true);
848
-						$this->changeLock($target, ILockingProvider::LOCK_SHARED, true);
849
-					}
850
-
851
-					if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
852
-						if ($this->shouldEmitHooks()) {
853
-							$this->emit_file_hooks_post($exists, $target);
854
-						}
855
-					} elseif ($result) {
856
-						if ($this->shouldEmitHooks($source) and $this->shouldEmitHooks($target)) {
857
-							\OC_Hook::emit(
858
-								Filesystem::CLASSNAME,
859
-								Filesystem::signal_post_rename,
860
-								[
861
-									Filesystem::signal_param_oldpath => $this->getHookPath($source),
862
-									Filesystem::signal_param_newpath => $this->getHookPath($target)
863
-								]
864
-							);
865
-						}
866
-					}
867
-				}
868
-			} catch (\Exception $e) {
869
-				throw $e;
870
-			} finally {
871
-				$this->unlockFile($source, ILockingProvider::LOCK_SHARED, true);
872
-				$this->unlockFile($target, ILockingProvider::LOCK_SHARED, true);
873
-			}
874
-		}
875
-		return $result;
876
-	}
877
-
878
-	/**
879
-	 * Copy a file/folder from the source path to target path
880
-	 *
881
-	 * @param string $source source path
882
-	 * @param string $target target path
883
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
884
-	 *
885
-	 * @return bool|mixed
886
-	 */
887
-	public function copy($source, $target, $preserveMtime = false) {
888
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
889
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
890
-		$result = false;
891
-		if (
892
-			Filesystem::isValidPath($target)
893
-			and Filesystem::isValidPath($source)
894
-			and !Filesystem::isFileBlacklisted($target)
895
-		) {
896
-			$source = $this->getRelativePath($absolutePath1);
897
-			$target = $this->getRelativePath($absolutePath2);
898
-
899
-			if ($source == null or $target == null) {
900
-				return false;
901
-			}
902
-			$run = true;
903
-
904
-			$this->lockFile($target, ILockingProvider::LOCK_SHARED);
905
-			$this->lockFile($source, ILockingProvider::LOCK_SHARED);
906
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
907
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
908
-
909
-			try {
910
-				$exists = $this->file_exists($target);
911
-				if ($this->shouldEmitHooks()) {
912
-					\OC_Hook::emit(
913
-						Filesystem::CLASSNAME,
914
-						Filesystem::signal_copy,
915
-						[
916
-							Filesystem::signal_param_oldpath => $this->getHookPath($source),
917
-							Filesystem::signal_param_newpath => $this->getHookPath($target),
918
-							Filesystem::signal_param_run => &$run
919
-						]
920
-					);
921
-					$this->emit_file_hooks_pre($exists, $target, $run);
922
-				}
923
-				if ($run) {
924
-					$mount1 = $this->getMount($source);
925
-					$mount2 = $this->getMount($target);
926
-					$storage1 = $mount1->getStorage();
927
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
928
-					$storage2 = $mount2->getStorage();
929
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
930
-
931
-					$this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE);
932
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
933
-
934
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
935
-						if ($storage1) {
936
-							$result = $storage1->copy($internalPath1, $internalPath2);
937
-						} else {
938
-							$result = false;
939
-						}
940
-					} else {
941
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
942
-					}
943
-
944
-					$this->writeUpdate($storage2, $internalPath2);
945
-
946
-					$this->changeLock($target, ILockingProvider::LOCK_SHARED);
947
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
948
-
949
-					if ($this->shouldEmitHooks() && $result !== false) {
950
-						\OC_Hook::emit(
951
-							Filesystem::CLASSNAME,
952
-							Filesystem::signal_post_copy,
953
-							[
954
-								Filesystem::signal_param_oldpath => $this->getHookPath($source),
955
-								Filesystem::signal_param_newpath => $this->getHookPath($target)
956
-							]
957
-						);
958
-						$this->emit_file_hooks_post($exists, $target);
959
-					}
960
-				}
961
-			} catch (\Exception $e) {
962
-				$this->unlockFile($target, $lockTypePath2);
963
-				$this->unlockFile($source, $lockTypePath1);
964
-				throw $e;
965
-			}
966
-
967
-			$this->unlockFile($target, $lockTypePath2);
968
-			$this->unlockFile($source, $lockTypePath1);
969
-		}
970
-		return $result;
971
-	}
972
-
973
-	/**
974
-	 * @param string $path
975
-	 * @param string $mode 'r' or 'w'
976
-	 * @return resource
977
-	 * @throws LockedException
978
-	 */
979
-	public function fopen($path, $mode) {
980
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
981
-		$hooks = [];
982
-		switch ($mode) {
983
-			case 'r':
984
-				$hooks[] = 'read';
985
-				break;
986
-			case 'r+':
987
-			case 'w+':
988
-			case 'x+':
989
-			case 'a+':
990
-				$hooks[] = 'read';
991
-				$hooks[] = 'write';
992
-				break;
993
-			case 'w':
994
-			case 'x':
995
-			case 'a':
996
-				$hooks[] = 'write';
997
-				break;
998
-			default:
999
-				$this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
1000
-		}
1001
-
1002
-		if ($mode !== 'r' && $mode !== 'w') {
1003
-			$this->logger->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends', ['app' => 'core']);
1004
-		}
1005
-
1006
-		$handle = $this->basicOperation('fopen', $path, $hooks, $mode);
1007
-		if (!is_resource($handle) && $mode === 'r') {
1008
-			// trying to read a file that isn't on disk, check if the cache is out of sync and rescan if needed
1009
-			$mount = $this->getMount($path);
1010
-			$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1011
-			$storage = $mount->getStorage();
1012
-			if ($storage->getCache()->inCache($internalPath) && !$storage->file_exists($path)) {
1013
-				$this->writeUpdate($storage, $internalPath);
1014
-			}
1015
-		}
1016
-		return $handle;
1017
-	}
1018
-
1019
-	/**
1020
-	 * @param string $path
1021
-	 * @return bool|string
1022
-	 * @throws \OCP\Files\InvalidPathException
1023
-	 */
1024
-	public function toTmpFile($path) {
1025
-		$this->assertPathLength($path);
1026
-		if (Filesystem::isValidPath($path)) {
1027
-			$source = $this->fopen($path, 'r');
1028
-			if ($source) {
1029
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
1030
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1031
-				file_put_contents($tmpFile, $source);
1032
-				return $tmpFile;
1033
-			} else {
1034
-				return false;
1035
-			}
1036
-		} else {
1037
-			return false;
1038
-		}
1039
-	}
1040
-
1041
-	/**
1042
-	 * @param string $tmpFile
1043
-	 * @param string $path
1044
-	 * @return bool|mixed
1045
-	 * @throws \OCP\Files\InvalidPathException
1046
-	 */
1047
-	public function fromTmpFile($tmpFile, $path) {
1048
-		$this->assertPathLength($path);
1049
-		if (Filesystem::isValidPath($path)) {
1050
-			// Get directory that the file is going into
1051
-			$filePath = dirname($path);
1052
-
1053
-			// Create the directories if any
1054
-			if (!$this->file_exists($filePath)) {
1055
-				$result = $this->createParentDirectories($filePath);
1056
-				if ($result === false) {
1057
-					return false;
1058
-				}
1059
-			}
1060
-
1061
-			$source = fopen($tmpFile, 'r');
1062
-			if ($source) {
1063
-				$result = $this->file_put_contents($path, $source);
1064
-				// $this->file_put_contents() might have already closed
1065
-				// the resource, so we check it, before trying to close it
1066
-				// to avoid messages in the error log.
1067
-				if (is_resource($source)) {
1068
-					fclose($source);
1069
-				}
1070
-				unlink($tmpFile);
1071
-				return $result;
1072
-			} else {
1073
-				return false;
1074
-			}
1075
-		} else {
1076
-			return false;
1077
-		}
1078
-	}
1079
-
1080
-
1081
-	/**
1082
-	 * @param string $path
1083
-	 * @return mixed
1084
-	 * @throws \OCP\Files\InvalidPathException
1085
-	 */
1086
-	public function getMimeType($path) {
1087
-		$this->assertPathLength($path);
1088
-		return $this->basicOperation('getMimeType', $path);
1089
-	}
1090
-
1091
-	/**
1092
-	 * @param string $type
1093
-	 * @param string $path
1094
-	 * @param bool $raw
1095
-	 * @return bool|string
1096
-	 */
1097
-	public function hash($type, $path, $raw = false) {
1098
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1099
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1100
-		if (Filesystem::isValidPath($path)) {
1101
-			$path = $this->getRelativePath($absolutePath);
1102
-			if ($path == null) {
1103
-				return false;
1104
-			}
1105
-			if ($this->shouldEmitHooks($path)) {
1106
-				\OC_Hook::emit(
1107
-					Filesystem::CLASSNAME,
1108
-					Filesystem::signal_read,
1109
-					[Filesystem::signal_param_path => $this->getHookPath($path)]
1110
-				);
1111
-			}
1112
-			/** @var Storage|null $storage */
1113
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1114
-			if ($storage) {
1115
-				return $storage->hash($type, $internalPath, $raw);
1116
-			}
1117
-		}
1118
-		return false;
1119
-	}
1120
-
1121
-	/**
1122
-	 * @param string $path
1123
-	 * @return mixed
1124
-	 * @throws \OCP\Files\InvalidPathException
1125
-	 */
1126
-	public function free_space($path = '/') {
1127
-		$this->assertPathLength($path);
1128
-		$result = $this->basicOperation('free_space', $path);
1129
-		if ($result === null) {
1130
-			throw new InvalidPathException();
1131
-		}
1132
-		return $result;
1133
-	}
1134
-
1135
-	/**
1136
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1137
-	 *
1138
-	 * @param string $operation
1139
-	 * @param string $path
1140
-	 * @param array $hooks (optional)
1141
-	 * @param mixed $extraParam (optional)
1142
-	 * @return mixed
1143
-	 * @throws LockedException
1144
-	 *
1145
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1146
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1147
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1148
-	 */
1149
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1150
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1151
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1152
-		if (Filesystem::isValidPath($path)
1153
-			and !Filesystem::isFileBlacklisted($path)
1154
-		) {
1155
-			$path = $this->getRelativePath($absolutePath);
1156
-			if ($path == null) {
1157
-				return false;
1158
-			}
1159
-
1160
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1161
-				// always a shared lock during pre-hooks so the hook can read the file
1162
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1163
-			}
1164
-
1165
-			$run = $this->runHooks($hooks, $path);
1166
-			/** @var \OC\Files\Storage\Storage $storage */
1167
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1168
-			if ($run and $storage) {
1169
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1170
-					try {
1171
-						$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1172
-					} catch (LockedException $e) {
1173
-						// release the shared lock we acquired before quitting
1174
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1175
-						throw $e;
1176
-					}
1177
-				}
1178
-				try {
1179
-					if (!is_null($extraParam)) {
1180
-						$result = $storage->$operation($internalPath, $extraParam);
1181
-					} else {
1182
-						$result = $storage->$operation($internalPath);
1183
-					}
1184
-				} catch (\Exception $e) {
1185
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1186
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1187
-					} elseif (in_array('read', $hooks)) {
1188
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1189
-					}
1190
-					throw $e;
1191
-				}
1192
-
1193
-				if ($result !== false && in_array('delete', $hooks)) {
1194
-					$this->removeUpdate($storage, $internalPath);
1195
-				}
1196
-				if ($result !== false && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
1197
-					$this->writeUpdate($storage, $internalPath);
1198
-				}
1199
-				if ($result !== false && in_array('touch', $hooks)) {
1200
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1201
-				}
1202
-
1203
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1204
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1205
-				}
1206
-
1207
-				$unlockLater = false;
1208
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1209
-					$unlockLater = true;
1210
-					// make sure our unlocking callback will still be called if connection is aborted
1211
-					ignore_user_abort(true);
1212
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1213
-						if (in_array('write', $hooks)) {
1214
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1215
-						} elseif (in_array('read', $hooks)) {
1216
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1217
-						}
1218
-					});
1219
-				}
1220
-
1221
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1222
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1223
-						$this->runHooks($hooks, $path, true);
1224
-					}
1225
-				}
1226
-
1227
-				if (!$unlockLater
1228
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1229
-				) {
1230
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1231
-				}
1232
-				return $result;
1233
-			} else {
1234
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1235
-			}
1236
-		}
1237
-		return null;
1238
-	}
1239
-
1240
-	/**
1241
-	 * get the path relative to the default root for hook usage
1242
-	 *
1243
-	 * @param string $path
1244
-	 * @return ?string
1245
-	 */
1246
-	private function getHookPath($path) {
1247
-		if (!Filesystem::getView()) {
1248
-			return $path;
1249
-		}
1250
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1251
-	}
1252
-
1253
-	private function shouldEmitHooks($path = '') {
1254
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1255
-			return false;
1256
-		}
1257
-		if (!Filesystem::$loaded) {
1258
-			return false;
1259
-		}
1260
-		$defaultRoot = Filesystem::getRoot();
1261
-		if ($defaultRoot === null) {
1262
-			return false;
1263
-		}
1264
-		if ($this->fakeRoot === $defaultRoot) {
1265
-			return true;
1266
-		}
1267
-		$fullPath = $this->getAbsolutePath($path);
1268
-
1269
-		if ($fullPath === $defaultRoot) {
1270
-			return true;
1271
-		}
1272
-
1273
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1274
-	}
1275
-
1276
-	/**
1277
-	 * @param string[] $hooks
1278
-	 * @param string $path
1279
-	 * @param bool $post
1280
-	 * @return bool
1281
-	 */
1282
-	private function runHooks($hooks, $path, $post = false) {
1283
-		$relativePath = $path;
1284
-		$path = $this->getHookPath($path);
1285
-		$prefix = $post ? 'post_' : '';
1286
-		$run = true;
1287
-		if ($this->shouldEmitHooks($relativePath)) {
1288
-			foreach ($hooks as $hook) {
1289
-				if ($hook != 'read') {
1290
-					\OC_Hook::emit(
1291
-						Filesystem::CLASSNAME,
1292
-						$prefix . $hook,
1293
-						[
1294
-							Filesystem::signal_param_run => &$run,
1295
-							Filesystem::signal_param_path => $path
1296
-						]
1297
-					);
1298
-				} elseif (!$post) {
1299
-					\OC_Hook::emit(
1300
-						Filesystem::CLASSNAME,
1301
-						$prefix . $hook,
1302
-						[
1303
-							Filesystem::signal_param_path => $path
1304
-						]
1305
-					);
1306
-				}
1307
-			}
1308
-		}
1309
-		return $run;
1310
-	}
1311
-
1312
-	/**
1313
-	 * check if a file or folder has been updated since $time
1314
-	 *
1315
-	 * @param string $path
1316
-	 * @param int $time
1317
-	 * @return bool
1318
-	 */
1319
-	public function hasUpdated($path, $time) {
1320
-		return $this->basicOperation('hasUpdated', $path, [], $time);
1321
-	}
1322
-
1323
-	/**
1324
-	 * @param string $ownerId
1325
-	 * @return IUser
1326
-	 */
1327
-	private function getUserObjectForOwner(string $ownerId) {
1328
-		return new LazyUser($ownerId, $this->userManager);
1329
-	}
1330
-
1331
-	/**
1332
-	 * Get file info from cache
1333
-	 *
1334
-	 * If the file is not in cached it will be scanned
1335
-	 * If the file has changed on storage the cache will be updated
1336
-	 *
1337
-	 * @param \OC\Files\Storage\Storage $storage
1338
-	 * @param string $internalPath
1339
-	 * @param string $relativePath
1340
-	 * @return ICacheEntry|bool
1341
-	 */
1342
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1343
-		$cache = $storage->getCache($internalPath);
1344
-		$data = $cache->get($internalPath);
1345
-		$watcher = $storage->getWatcher($internalPath);
1346
-
1347
-		try {
1348
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1349
-			if (!$data || (isset($data['size']) && $data['size'] === -1)) {
1350
-				if (!$storage->file_exists($internalPath)) {
1351
-					return false;
1352
-				}
1353
-				// don't need to get a lock here since the scanner does it's own locking
1354
-				$scanner = $storage->getScanner($internalPath);
1355
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1356
-				$data = $cache->get($internalPath);
1357
-			} elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1358
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1359
-				$watcher->update($internalPath, $data);
1360
-				$storage->getPropagator()->propagateChange($internalPath, time());
1361
-				$data = $cache->get($internalPath);
1362
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1363
-			}
1364
-		} catch (LockedException $e) {
1365
-			// if the file is locked we just use the old cache info
1366
-		}
1367
-
1368
-		return $data;
1369
-	}
1370
-
1371
-	/**
1372
-	 * get the filesystem info
1373
-	 *
1374
-	 * @param string $path
1375
-	 * @param bool|string $includeMountPoints true to add mountpoint sizes,
1376
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1377
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1378
-	 */
1379
-	public function getFileInfo($path, $includeMountPoints = true) {
1380
-		$this->assertPathLength($path);
1381
-		if (!Filesystem::isValidPath($path)) {
1382
-			return false;
1383
-		}
1384
-		if (Cache\Scanner::isPartialFile($path)) {
1385
-			return $this->getPartFileInfo($path);
1386
-		}
1387
-		$relativePath = $path;
1388
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1389
-
1390
-		$mount = Filesystem::getMountManager()->find($path);
1391
-		$storage = $mount->getStorage();
1392
-		$internalPath = $mount->getInternalPath($path);
1393
-		if ($storage) {
1394
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1395
-
1396
-			if (!$data instanceof ICacheEntry) {
1397
-				return false;
1398
-			}
1399
-
1400
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1401
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1402
-			}
1403
-			$ownerId = $storage->getOwner($internalPath);
1404
-			$owner = null;
1405
-			if ($ownerId !== null && $ownerId !== false) {
1406
-				// ownerId might be null if files are accessed with an access token without file system access
1407
-				$owner = $this->getUserObjectForOwner($ownerId);
1408
-			}
1409
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1410
-
1411
-			if (isset($data['fileid'])) {
1412
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1413
-					//add the sizes of other mount points to the folder
1414
-					$extOnly = ($includeMountPoints === 'ext');
1415
-					$this->addSubMounts($info, $extOnly);
1416
-				}
1417
-			}
1418
-
1419
-			return $info;
1420
-		} else {
1421
-			$this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
1422
-		}
1423
-
1424
-		return false;
1425
-	}
1426
-
1427
-	/**
1428
-	 * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
1429
-	 */
1430
-	public function addSubMounts(FileInfo $info, $extOnly = false): void {
1431
-		$mounts = Filesystem::getMountManager()->findIn($info->getPath());
1432
-		$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1433
-			$subStorage = $mount->getStorage();
1434
-			return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1435
-		}));
1436
-	}
1437
-
1438
-	/**
1439
-	 * get the content of a directory
1440
-	 *
1441
-	 * @param string $directory path under datadirectory
1442
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1443
-	 * @return FileInfo[]
1444
-	 */
1445
-	public function getDirectoryContent($directory, $mimetype_filter = '', \OCP\Files\FileInfo $directoryInfo = null) {
1446
-		$this->assertPathLength($directory);
1447
-		if (!Filesystem::isValidPath($directory)) {
1448
-			return [];
1449
-		}
1450
-
1451
-		$path = $this->getAbsolutePath($directory);
1452
-		$path = Filesystem::normalizePath($path);
1453
-		$mount = $this->getMount($directory);
1454
-		$storage = $mount->getStorage();
1455
-		$internalPath = $mount->getInternalPath($path);
1456
-		if (!$storage) {
1457
-			return [];
1458
-		}
1459
-
1460
-		$cache = $storage->getCache($internalPath);
1461
-		$user = \OC_User::getUser();
1462
-
1463
-		if (!$directoryInfo) {
1464
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1465
-			if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
1466
-				return [];
1467
-			}
1468
-		} else {
1469
-			$data = $directoryInfo;
1470
-		}
1471
-
1472
-		if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
1473
-			return [];
1474
-		}
1475
-
1476
-		$folderId = $data->getId();
1477
-		$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1478
-
1479
-		$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1480
-
1481
-		$fileNames = array_map(function (ICacheEntry $content) {
1482
-			return $content->getName();
1483
-		}, $contents);
1484
-		/**
1485
-		 * @var \OC\Files\FileInfo[] $fileInfos
1486
-		 */
1487
-		$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1488
-			if ($sharingDisabled) {
1489
-				$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1490
-			}
1491
-			$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1492
-			return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1493
-		}, $contents);
1494
-		$files = array_combine($fileNames, $fileInfos);
1495
-
1496
-		//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1497
-		$mounts = Filesystem::getMountManager()->findIn($path);
1498
-		$dirLength = strlen($path);
1499
-		foreach ($mounts as $mount) {
1500
-			$mountPoint = $mount->getMountPoint();
1501
-			$subStorage = $mount->getStorage();
1502
-			if ($subStorage) {
1503
-				$subCache = $subStorage->getCache('');
1504
-
1505
-				$rootEntry = $subCache->get('');
1506
-				if (!$rootEntry) {
1507
-					$subScanner = $subStorage->getScanner();
1508
-					try {
1509
-						$subScanner->scanFile('');
1510
-					} catch (\OCP\Files\StorageNotAvailableException $e) {
1511
-						continue;
1512
-					} catch (\OCP\Files\StorageInvalidException $e) {
1513
-						continue;
1514
-					} catch (\Exception $e) {
1515
-						// sometimes when the storage is not available it can be any exception
1516
-						$this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
1517
-							'exception' => $e,
1518
-							'app' => 'core',
1519
-						]);
1520
-						continue;
1521
-					}
1522
-					$rootEntry = $subCache->get('');
1523
-				}
1524
-
1525
-				if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
1526
-					$relativePath = trim(substr($mountPoint, $dirLength), '/');
1527
-					if ($pos = strpos($relativePath, '/')) {
1528
-						//mountpoint inside subfolder add size to the correct folder
1529
-						$entryName = substr($relativePath, 0, $pos);
1530
-						if (isset($files[$entryName])) {
1531
-							$files[$entryName]->addSubEntry($rootEntry, $mountPoint);
1532
-						}
1533
-					} else { //mountpoint in this folder, add an entry for it
1534
-						$rootEntry['name'] = $relativePath;
1535
-						$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1536
-						$permissions = $rootEntry['permissions'];
1537
-						// do not allow renaming/deleting the mount point if they are not shared files/folders
1538
-						// for shared files/folders we use the permissions given by the owner
1539
-						if ($mount instanceof MoveableMount) {
1540
-							$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1541
-						} else {
1542
-							$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1543
-						}
1544
-
1545
-						$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1546
-
1547
-						// if sharing was disabled for the user we remove the share permissions
1548
-						if (\OCP\Util::isSharingDisabledForUser()) {
1549
-							$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1550
-						}
1551
-
1552
-						$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1553
-						$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1554
-					}
1555
-				}
1556
-			}
1557
-		}
1558
-
1559
-		if ($mimetype_filter) {
1560
-			$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1561
-				if (strpos($mimetype_filter, '/')) {
1562
-					return $file->getMimetype() === $mimetype_filter;
1563
-				} else {
1564
-					return $file->getMimePart() === $mimetype_filter;
1565
-				}
1566
-			});
1567
-		}
1568
-
1569
-		return array_values($files);
1570
-	}
1571
-
1572
-	/**
1573
-	 * change file metadata
1574
-	 *
1575
-	 * @param string $path
1576
-	 * @param array|\OCP\Files\FileInfo $data
1577
-	 * @return int
1578
-	 *
1579
-	 * returns the fileid of the updated file
1580
-	 */
1581
-	public function putFileInfo($path, $data) {
1582
-		$this->assertPathLength($path);
1583
-		if ($data instanceof FileInfo) {
1584
-			$data = $data->getData();
1585
-		}
1586
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1587
-		/**
1588
-		 * @var \OC\Files\Storage\Storage $storage
1589
-		 * @var string $internalPath
1590
-		 */
1591
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
1592
-		if ($storage) {
1593
-			$cache = $storage->getCache($path);
1594
-
1595
-			if (!$cache->inCache($internalPath)) {
1596
-				$scanner = $storage->getScanner($internalPath);
1597
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1598
-			}
1599
-
1600
-			return $cache->put($internalPath, $data);
1601
-		} else {
1602
-			return -1;
1603
-		}
1604
-	}
1605
-
1606
-	/**
1607
-	 * search for files with the name matching $query
1608
-	 *
1609
-	 * @param string $query
1610
-	 * @return FileInfo[]
1611
-	 */
1612
-	public function search($query) {
1613
-		return $this->searchCommon('search', ['%' . $query . '%']);
1614
-	}
1615
-
1616
-	/**
1617
-	 * search for files with the name matching $query
1618
-	 *
1619
-	 * @param string $query
1620
-	 * @return FileInfo[]
1621
-	 */
1622
-	public function searchRaw($query) {
1623
-		return $this->searchCommon('search', [$query]);
1624
-	}
1625
-
1626
-	/**
1627
-	 * search for files by mimetype
1628
-	 *
1629
-	 * @param string $mimetype
1630
-	 * @return FileInfo[]
1631
-	 */
1632
-	public function searchByMime($mimetype) {
1633
-		return $this->searchCommon('searchByMime', [$mimetype]);
1634
-	}
1635
-
1636
-	/**
1637
-	 * search for files by tag
1638
-	 *
1639
-	 * @param string|int $tag name or tag id
1640
-	 * @param string $userId owner of the tags
1641
-	 * @return FileInfo[]
1642
-	 */
1643
-	public function searchByTag($tag, $userId) {
1644
-		return $this->searchCommon('searchByTag', [$tag, $userId]);
1645
-	}
1646
-
1647
-	/**
1648
-	 * @param string $method cache method
1649
-	 * @param array $args
1650
-	 * @return FileInfo[]
1651
-	 */
1652
-	private function searchCommon($method, $args) {
1653
-		$files = [];
1654
-		$rootLength = strlen($this->fakeRoot);
1655
-
1656
-		$mount = $this->getMount('');
1657
-		$mountPoint = $mount->getMountPoint();
1658
-		$storage = $mount->getStorage();
1659
-		$userManager = \OC::$server->getUserManager();
1660
-		if ($storage) {
1661
-			$cache = $storage->getCache('');
1662
-
1663
-			$results = call_user_func_array([$cache, $method], $args);
1664
-			foreach ($results as $result) {
1665
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1666
-					$internalPath = $result['path'];
1667
-					$path = $mountPoint . $result['path'];
1668
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1669
-					$owner = $userManager->get($storage->getOwner($internalPath));
1670
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1671
-				}
1672
-			}
1673
-
1674
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1675
-			foreach ($mounts as $mount) {
1676
-				$mountPoint = $mount->getMountPoint();
1677
-				$storage = $mount->getStorage();
1678
-				if ($storage) {
1679
-					$cache = $storage->getCache('');
1680
-
1681
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1682
-					$results = call_user_func_array([$cache, $method], $args);
1683
-					if ($results) {
1684
-						foreach ($results as $result) {
1685
-							$internalPath = $result['path'];
1686
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1687
-							$path = rtrim($mountPoint . $internalPath, '/');
1688
-							$owner = $userManager->get($storage->getOwner($internalPath));
1689
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1690
-						}
1691
-					}
1692
-				}
1693
-			}
1694
-		}
1695
-		return $files;
1696
-	}
1697
-
1698
-	/**
1699
-	 * Get the owner for a file or folder
1700
-	 *
1701
-	 * @param string $path
1702
-	 * @return string the user id of the owner
1703
-	 * @throws NotFoundException
1704
-	 */
1705
-	public function getOwner($path) {
1706
-		$info = $this->getFileInfo($path);
1707
-		if (!$info) {
1708
-			throw new NotFoundException($path . ' not found while trying to get owner');
1709
-		}
1710
-
1711
-		if ($info->getOwner() === null) {
1712
-			throw new NotFoundException($path . ' has no owner');
1713
-		}
1714
-
1715
-		return $info->getOwner()->getUID();
1716
-	}
1717
-
1718
-	/**
1719
-	 * get the ETag for a file or folder
1720
-	 *
1721
-	 * @param string $path
1722
-	 * @return string
1723
-	 */
1724
-	public function getETag($path) {
1725
-		/**
1726
-		 * @var Storage\Storage $storage
1727
-		 * @var string $internalPath
1728
-		 */
1729
-		[$storage, $internalPath] = $this->resolvePath($path);
1730
-		if ($storage) {
1731
-			return $storage->getETag($internalPath);
1732
-		} else {
1733
-			return null;
1734
-		}
1735
-	}
1736
-
1737
-	/**
1738
-	 * Get the path of a file by id, relative to the view
1739
-	 *
1740
-	 * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
1741
-	 *
1742
-	 * @param int $id
1743
-	 * @param int|null $storageId
1744
-	 * @return string
1745
-	 * @throws NotFoundException
1746
-	 */
1747
-	public function getPath($id, int $storageId = null) {
1748
-		$id = (int)$id;
1749
-		$manager = Filesystem::getMountManager();
1750
-		$mounts = $manager->findIn($this->fakeRoot);
1751
-		$mounts[] = $manager->find($this->fakeRoot);
1752
-		$mounts = array_filter($mounts);
1753
-		// reverse the array, so we start with the storage this view is in
1754
-		// which is the most likely to contain the file we're looking for
1755
-		$mounts = array_reverse($mounts);
1756
-
1757
-		// put non-shared mounts in front of the shared mount
1758
-		// this prevents unneeded recursion into shares
1759
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1760
-			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1761
-		});
1762
-
1763
-		if (!is_null($storageId)) {
1764
-			$mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1765
-				return $mount->getNumericStorageId() === $storageId;
1766
-			});
1767
-		}
1768
-
1769
-		foreach ($mounts as $mount) {
1770
-			/**
1771
-			 * @var \OC\Files\Mount\MountPoint $mount
1772
-			 */
1773
-			if ($mount->getStorage()) {
1774
-				$cache = $mount->getStorage()->getCache();
1775
-				$internalPath = $cache->getPathById($id);
1776
-				if (is_string($internalPath)) {
1777
-					$fullPath = $mount->getMountPoint() . $internalPath;
1778
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1779
-						return $path;
1780
-					}
1781
-				}
1782
-			}
1783
-		}
1784
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1785
-	}
1786
-
1787
-	/**
1788
-	 * @param string $path
1789
-	 * @throws InvalidPathException
1790
-	 */
1791
-	private function assertPathLength($path) {
1792
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1793
-		// Check for the string length - performed using isset() instead of strlen()
1794
-		// because isset() is about 5x-40x faster.
1795
-		if (isset($path[$maxLen])) {
1796
-			$pathLen = strlen($path);
1797
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1798
-		}
1799
-	}
1800
-
1801
-	/**
1802
-	 * check if it is allowed to move a mount point to a given target.
1803
-	 * It is not allowed to move a mount point into a different mount point or
1804
-	 * into an already shared folder
1805
-	 *
1806
-	 * @param IStorage $targetStorage
1807
-	 * @param string $targetInternalPath
1808
-	 * @return boolean
1809
-	 */
1810
-	private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1811
-		// note: cannot use the view because the target is already locked
1812
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1813
-		if ($fileId === -1) {
1814
-			// target might not exist, need to check parent instead
1815
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1816
-		}
1817
-
1818
-		// check if any of the parents were shared by the current owner (include collections)
1819
-		$shares = Share::getItemShared(
1820
-			'folder',
1821
-			$fileId,
1822
-			\OC\Share\Constants::FORMAT_NONE,
1823
-			null,
1824
-			true
1825
-		);
1826
-
1827
-		if (count($shares) > 0) {
1828
-			$this->logger->debug(
1829
-				'It is not allowed to move one mount point into a shared folder',
1830
-				['app' => 'files']);
1831
-			return false;
1832
-		}
1833
-
1834
-		return true;
1835
-	}
1836
-
1837
-	/**
1838
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1839
-	 *
1840
-	 * @param string $path
1841
-	 * @return \OCP\Files\FileInfo
1842
-	 */
1843
-	private function getPartFileInfo($path) {
1844
-		$mount = $this->getMount($path);
1845
-		$storage = $mount->getStorage();
1846
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1847
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1848
-		return new FileInfo(
1849
-			$this->getAbsolutePath($path),
1850
-			$storage,
1851
-			$internalPath,
1852
-			[
1853
-				'fileid' => null,
1854
-				'mimetype' => $storage->getMimeType($internalPath),
1855
-				'name' => basename($path),
1856
-				'etag' => null,
1857
-				'size' => $storage->filesize($internalPath),
1858
-				'mtime' => $storage->filemtime($internalPath),
1859
-				'encrypted' => false,
1860
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1861
-			],
1862
-			$mount,
1863
-			$owner
1864
-		);
1865
-	}
1866
-
1867
-	/**
1868
-	 * @param string $path
1869
-	 * @param string $fileName
1870
-	 * @throws InvalidPathException
1871
-	 */
1872
-	public function verifyPath($path, $fileName) {
1873
-		try {
1874
-			/** @type \OCP\Files\Storage $storage */
1875
-			[$storage, $internalPath] = $this->resolvePath($path);
1876
-			$storage->verifyPath($internalPath, $fileName);
1877
-		} catch (ReservedWordException $ex) {
1878
-			$l = \OC::$server->getL10N('lib');
1879
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1880
-		} catch (InvalidCharacterInPathException $ex) {
1881
-			$l = \OC::$server->getL10N('lib');
1882
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1883
-		} catch (FileNameTooLongException $ex) {
1884
-			$l = \OC::$server->getL10N('lib');
1885
-			throw new InvalidPathException($l->t('File name is too long'));
1886
-		} catch (InvalidDirectoryException $ex) {
1887
-			$l = \OC::$server->getL10N('lib');
1888
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1889
-		} catch (EmptyFileNameException $ex) {
1890
-			$l = \OC::$server->getL10N('lib');
1891
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1892
-		}
1893
-	}
1894
-
1895
-	/**
1896
-	 * get all parent folders of $path
1897
-	 *
1898
-	 * @param string $path
1899
-	 * @return string[]
1900
-	 */
1901
-	private function getParents($path) {
1902
-		$path = trim($path, '/');
1903
-		if (!$path) {
1904
-			return [];
1905
-		}
1906
-
1907
-		$parts = explode('/', $path);
1908
-
1909
-		// remove the single file
1910
-		array_pop($parts);
1911
-		$result = ['/'];
1912
-		$resultPath = '';
1913
-		foreach ($parts as $part) {
1914
-			if ($part) {
1915
-				$resultPath .= '/' . $part;
1916
-				$result[] = $resultPath;
1917
-			}
1918
-		}
1919
-		return $result;
1920
-	}
1921
-
1922
-	/**
1923
-	 * Returns the mount point for which to lock
1924
-	 *
1925
-	 * @param string $absolutePath absolute path
1926
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1927
-	 * is mounted directly on the given path, false otherwise
1928
-	 * @return IMountPoint mount point for which to apply locks
1929
-	 */
1930
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1931
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1932
-
1933
-		if ($useParentMount) {
1934
-			// find out if something is mounted directly on the path
1935
-			$internalPath = $mount->getInternalPath($absolutePath);
1936
-			if ($internalPath === '') {
1937
-				// resolve the parent mount instead
1938
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1939
-			}
1940
-		}
1941
-
1942
-		return $mount;
1943
-	}
1944
-
1945
-	/**
1946
-	 * Lock the given path
1947
-	 *
1948
-	 * @param string $path the path of the file to lock, relative to the view
1949
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1950
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1951
-	 *
1952
-	 * @return bool False if the path is excluded from locking, true otherwise
1953
-	 * @throws LockedException if the path is already locked
1954
-	 */
1955
-	private function lockPath($path, $type, $lockMountPoint = false) {
1956
-		$absolutePath = $this->getAbsolutePath($path);
1957
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1958
-		if (!$this->shouldLockFile($absolutePath)) {
1959
-			return false;
1960
-		}
1961
-
1962
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1963
-		if ($mount) {
1964
-			try {
1965
-				$storage = $mount->getStorage();
1966
-				if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1967
-					$storage->acquireLock(
1968
-						$mount->getInternalPath($absolutePath),
1969
-						$type,
1970
-						$this->lockingProvider
1971
-					);
1972
-				}
1973
-			} catch (LockedException $e) {
1974
-				// rethrow with the a human-readable path
1975
-				throw new LockedException(
1976
-					$this->getPathRelativeToFiles($absolutePath),
1977
-					$e,
1978
-					$e->getExistingLock()
1979
-				);
1980
-			}
1981
-		}
1982
-
1983
-		return true;
1984
-	}
1985
-
1986
-	/**
1987
-	 * Change the lock type
1988
-	 *
1989
-	 * @param string $path the path of the file to lock, relative to the view
1990
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1991
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1992
-	 *
1993
-	 * @return bool False if the path is excluded from locking, true otherwise
1994
-	 * @throws LockedException if the path is already locked
1995
-	 */
1996
-	public function changeLock($path, $type, $lockMountPoint = false) {
1997
-		$path = Filesystem::normalizePath($path);
1998
-		$absolutePath = $this->getAbsolutePath($path);
1999
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2000
-		if (!$this->shouldLockFile($absolutePath)) {
2001
-			return false;
2002
-		}
2003
-
2004
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2005
-		if ($mount) {
2006
-			try {
2007
-				$storage = $mount->getStorage();
2008
-				if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2009
-					$storage->changeLock(
2010
-						$mount->getInternalPath($absolutePath),
2011
-						$type,
2012
-						$this->lockingProvider
2013
-					);
2014
-				}
2015
-			} catch (LockedException $e) {
2016
-				try {
2017
-					// rethrow with the a human-readable path
2018
-					throw new LockedException(
2019
-						$this->getPathRelativeToFiles($absolutePath),
2020
-						$e,
2021
-						$e->getExistingLock()
2022
-					);
2023
-				} catch (\InvalidArgumentException $ex) {
2024
-					throw new LockedException(
2025
-						$absolutePath,
2026
-						$ex,
2027
-						$e->getExistingLock()
2028
-					);
2029
-				}
2030
-			}
2031
-		}
2032
-
2033
-		return true;
2034
-	}
2035
-
2036
-	/**
2037
-	 * Unlock the given path
2038
-	 *
2039
-	 * @param string $path the path of the file to unlock, relative to the view
2040
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2041
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2042
-	 *
2043
-	 * @return bool False if the path is excluded from locking, true otherwise
2044
-	 * @throws LockedException
2045
-	 */
2046
-	private function unlockPath($path, $type, $lockMountPoint = false) {
2047
-		$absolutePath = $this->getAbsolutePath($path);
2048
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2049
-		if (!$this->shouldLockFile($absolutePath)) {
2050
-			return false;
2051
-		}
2052
-
2053
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2054
-		if ($mount) {
2055
-			$storage = $mount->getStorage();
2056
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2057
-				$storage->releaseLock(
2058
-					$mount->getInternalPath($absolutePath),
2059
-					$type,
2060
-					$this->lockingProvider
2061
-				);
2062
-			}
2063
-		}
2064
-
2065
-		return true;
2066
-	}
2067
-
2068
-	/**
2069
-	 * Lock a path and all its parents up to the root of the view
2070
-	 *
2071
-	 * @param string $path the path of the file to lock relative to the view
2072
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2073
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2074
-	 *
2075
-	 * @return bool False if the path is excluded from locking, true otherwise
2076
-	 * @throws LockedException
2077
-	 */
2078
-	public function lockFile($path, $type, $lockMountPoint = false) {
2079
-		$absolutePath = $this->getAbsolutePath($path);
2080
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2081
-		if (!$this->shouldLockFile($absolutePath)) {
2082
-			return false;
2083
-		}
2084
-
2085
-		$this->lockPath($path, $type, $lockMountPoint);
2086
-
2087
-		$parents = $this->getParents($path);
2088
-		foreach ($parents as $parent) {
2089
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2090
-		}
2091
-
2092
-		return true;
2093
-	}
2094
-
2095
-	/**
2096
-	 * Unlock a path and all its parents up to the root of the view
2097
-	 *
2098
-	 * @param string $path the path of the file to lock relative to the view
2099
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2100
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2101
-	 *
2102
-	 * @return bool False if the path is excluded from locking, true otherwise
2103
-	 * @throws LockedException
2104
-	 */
2105
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2106
-		$absolutePath = $this->getAbsolutePath($path);
2107
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2108
-		if (!$this->shouldLockFile($absolutePath)) {
2109
-			return false;
2110
-		}
2111
-
2112
-		$this->unlockPath($path, $type, $lockMountPoint);
2113
-
2114
-		$parents = $this->getParents($path);
2115
-		foreach ($parents as $parent) {
2116
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2117
-		}
2118
-
2119
-		return true;
2120
-	}
2121
-
2122
-	/**
2123
-	 * Only lock files in data/user/files/
2124
-	 *
2125
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2126
-	 * @return bool
2127
-	 */
2128
-	protected function shouldLockFile($path) {
2129
-		$path = Filesystem::normalizePath($path);
2130
-
2131
-		$pathSegments = explode('/', $path);
2132
-		if (isset($pathSegments[2])) {
2133
-			// E.g.: /username/files/path-to-file
2134
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2135
-		}
2136
-
2137
-		return strpos($path, '/appdata_') !== 0;
2138
-	}
2139
-
2140
-	/**
2141
-	 * Shortens the given absolute path to be relative to
2142
-	 * "$user/files".
2143
-	 *
2144
-	 * @param string $absolutePath absolute path which is under "files"
2145
-	 *
2146
-	 * @return string path relative to "files" with trimmed slashes or null
2147
-	 * if the path was NOT relative to files
2148
-	 *
2149
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2150
-	 * @since 8.1.0
2151
-	 */
2152
-	public function getPathRelativeToFiles($absolutePath) {
2153
-		$path = Filesystem::normalizePath($absolutePath);
2154
-		$parts = explode('/', trim($path, '/'), 3);
2155
-		// "$user", "files", "path/to/dir"
2156
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2157
-			$this->logger->error(
2158
-				'$absolutePath must be relative to "files", value is "{absolutePath}"',
2159
-				[
2160
-					'absolutePath' => $absolutePath,
2161
-				]
2162
-			);
2163
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2164
-		}
2165
-		if (isset($parts[2])) {
2166
-			return $parts[2];
2167
-		}
2168
-		return '';
2169
-	}
2170
-
2171
-	/**
2172
-	 * @param string $filename
2173
-	 * @return array
2174
-	 * @throws \OC\User\NoUserException
2175
-	 * @throws NotFoundException
2176
-	 */
2177
-	public function getUidAndFilename($filename) {
2178
-		$info = $this->getFileInfo($filename);
2179
-		if (!$info instanceof \OCP\Files\FileInfo) {
2180
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2181
-		}
2182
-		$uid = $info->getOwner()->getUID();
2183
-		if ($uid != \OC_User::getUser()) {
2184
-			Filesystem::initMountPoints($uid);
2185
-			$ownerView = new View('/' . $uid . '/files');
2186
-			try {
2187
-				$filename = $ownerView->getPath($info['fileid']);
2188
-			} catch (NotFoundException $e) {
2189
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2190
-			}
2191
-		}
2192
-		return [$uid, $filename];
2193
-	}
2194
-
2195
-	/**
2196
-	 * Creates parent non-existing folders
2197
-	 *
2198
-	 * @param string $filePath
2199
-	 * @return bool
2200
-	 */
2201
-	private function createParentDirectories($filePath) {
2202
-		$directoryParts = explode('/', $filePath);
2203
-		$directoryParts = array_filter($directoryParts);
2204
-		foreach ($directoryParts as $key => $part) {
2205
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2206
-			$currentPath = '/' . implode('/', $currentPathElements);
2207
-			if ($this->is_file($currentPath)) {
2208
-				return false;
2209
-			}
2210
-			if (!$this->file_exists($currentPath)) {
2211
-				$this->mkdir($currentPath);
2212
-			}
2213
-		}
2214
-
2215
-		return true;
2216
-	}
89
+    /** @var string */
90
+    private $fakeRoot = '';
91
+
92
+    /**
93
+     * @var \OCP\Lock\ILockingProvider
94
+     */
95
+    protected $lockingProvider;
96
+
97
+    private $lockingEnabled;
98
+
99
+    private $updaterEnabled = true;
100
+
101
+    /** @var \OC\User\Manager */
102
+    private $userManager;
103
+
104
+    private LoggerInterface $logger;
105
+
106
+    /**
107
+     * @param string $root
108
+     * @throws \Exception If $root contains an invalid path
109
+     */
110
+    public function __construct($root = '') {
111
+        if (is_null($root)) {
112
+            throw new \InvalidArgumentException('Root can\'t be null');
113
+        }
114
+        if (!Filesystem::isValidPath($root)) {
115
+            throw new \Exception();
116
+        }
117
+
118
+        $this->fakeRoot = $root;
119
+        $this->lockingProvider = \OC::$server->getLockingProvider();
120
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
121
+        $this->userManager = \OC::$server->getUserManager();
122
+        $this->logger = \OC::$server->get(LoggerInterface::class);
123
+    }
124
+
125
+    public function getAbsolutePath($path = '/') {
126
+        if ($path === null) {
127
+            return null;
128
+        }
129
+        $this->assertPathLength($path);
130
+        if ($path === '') {
131
+            $path = '/';
132
+        }
133
+        if ($path[0] !== '/') {
134
+            $path = '/' . $path;
135
+        }
136
+        return $this->fakeRoot . $path;
137
+    }
138
+
139
+    /**
140
+     * change the root to a fake root
141
+     *
142
+     * @param string $fakeRoot
143
+     * @return boolean|null
144
+     */
145
+    public function chroot($fakeRoot) {
146
+        if (!$fakeRoot == '') {
147
+            if ($fakeRoot[0] !== '/') {
148
+                $fakeRoot = '/' . $fakeRoot;
149
+            }
150
+        }
151
+        $this->fakeRoot = $fakeRoot;
152
+    }
153
+
154
+    /**
155
+     * get the fake root
156
+     *
157
+     * @return string
158
+     */
159
+    public function getRoot() {
160
+        return $this->fakeRoot;
161
+    }
162
+
163
+    /**
164
+     * get path relative to the root of the view
165
+     *
166
+     * @param string $path
167
+     * @return ?string
168
+     */
169
+    public function getRelativePath($path) {
170
+        $this->assertPathLength($path);
171
+        if ($this->fakeRoot == '') {
172
+            return $path;
173
+        }
174
+
175
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
176
+            return '/';
177
+        }
178
+
179
+        // missing slashes can cause wrong matches!
180
+        $root = rtrim($this->fakeRoot, '/') . '/';
181
+
182
+        if (strpos($path, $root) !== 0) {
183
+            return null;
184
+        } else {
185
+            $path = substr($path, strlen($this->fakeRoot));
186
+            if (strlen($path) === 0) {
187
+                return '/';
188
+            } else {
189
+                return $path;
190
+            }
191
+        }
192
+    }
193
+
194
+    /**
195
+     * get the mountpoint of the storage object for a path
196
+     * ( note: because a storage is not always mounted inside the fakeroot, the
197
+     * returned mountpoint is relative to the absolute root of the filesystem
198
+     * and does not take the chroot into account )
199
+     *
200
+     * @param string $path
201
+     * @return string
202
+     */
203
+    public function getMountPoint($path) {
204
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
205
+    }
206
+
207
+    /**
208
+     * get the mountpoint of the storage object for a path
209
+     * ( note: because a storage is not always mounted inside the fakeroot, the
210
+     * returned mountpoint is relative to the absolute root of the filesystem
211
+     * and does not take the chroot into account )
212
+     *
213
+     * @param string $path
214
+     * @return \OCP\Files\Mount\IMountPoint
215
+     */
216
+    public function getMount($path) {
217
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
218
+    }
219
+
220
+    /**
221
+     * resolve a path to a storage and internal path
222
+     *
223
+     * @param string $path
224
+     * @return array an array consisting of the storage and the internal path
225
+     */
226
+    public function resolvePath($path) {
227
+        $a = $this->getAbsolutePath($path);
228
+        $p = Filesystem::normalizePath($a);
229
+        return Filesystem::resolvePath($p);
230
+    }
231
+
232
+    /**
233
+     * return the path to a local version of the file
234
+     * we need this because we can't know if a file is stored local or not from
235
+     * outside the filestorage and for some purposes a local file is needed
236
+     *
237
+     * @param string $path
238
+     * @return string
239
+     */
240
+    public function getLocalFile($path) {
241
+        $parent = substr($path, 0, strrpos($path, '/'));
242
+        $path = $this->getAbsolutePath($path);
243
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
244
+        if (Filesystem::isValidPath($parent) and $storage) {
245
+            return $storage->getLocalFile($internalPath);
246
+        } else {
247
+            return null;
248
+        }
249
+    }
250
+
251
+    /**
252
+     * @param string $path
253
+     * @return string
254
+     */
255
+    public function getLocalFolder($path) {
256
+        $parent = substr($path, 0, strrpos($path, '/'));
257
+        $path = $this->getAbsolutePath($path);
258
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
259
+        if (Filesystem::isValidPath($parent) and $storage) {
260
+            return $storage->getLocalFolder($internalPath);
261
+        } else {
262
+            return null;
263
+        }
264
+    }
265
+
266
+    /**
267
+     * the following functions operate with arguments and return values identical
268
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
269
+     * for \OC\Files\Storage\Storage via basicOperation().
270
+     */
271
+    public function mkdir($path) {
272
+        return $this->basicOperation('mkdir', $path, ['create', 'write']);
273
+    }
274
+
275
+    /**
276
+     * remove mount point
277
+     *
278
+     * @param IMountPoint $mount
279
+     * @param string $path relative to data/
280
+     * @return boolean
281
+     */
282
+    protected function removeMount($mount, $path) {
283
+        if ($mount instanceof MoveableMount) {
284
+            // cut of /user/files to get the relative path to data/user/files
285
+            $pathParts = explode('/', $path, 4);
286
+            $relPath = '/' . $pathParts[3];
287
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
288
+            \OC_Hook::emit(
289
+                Filesystem::CLASSNAME, "umount",
290
+                [Filesystem::signal_param_path => $relPath]
291
+            );
292
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
293
+            $result = $mount->removeMount();
294
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
295
+            if ($result) {
296
+                \OC_Hook::emit(
297
+                    Filesystem::CLASSNAME, "post_umount",
298
+                    [Filesystem::signal_param_path => $relPath]
299
+                );
300
+            }
301
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
302
+            return $result;
303
+        } else {
304
+            // do not allow deleting the storage's root / the mount point
305
+            // because for some storages it might delete the whole contents
306
+            // but isn't supposed to work that way
307
+            return false;
308
+        }
309
+    }
310
+
311
+    public function disableCacheUpdate() {
312
+        $this->updaterEnabled = false;
313
+    }
314
+
315
+    public function enableCacheUpdate() {
316
+        $this->updaterEnabled = true;
317
+    }
318
+
319
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
320
+        if ($this->updaterEnabled) {
321
+            if (is_null($time)) {
322
+                $time = time();
323
+            }
324
+            $storage->getUpdater()->update($internalPath, $time);
325
+        }
326
+    }
327
+
328
+    protected function removeUpdate(Storage $storage, $internalPath) {
329
+        if ($this->updaterEnabled) {
330
+            $storage->getUpdater()->remove($internalPath);
331
+        }
332
+    }
333
+
334
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
335
+        if ($this->updaterEnabled) {
336
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
337
+        }
338
+    }
339
+
340
+    /**
341
+     * @param string $path
342
+     * @return bool|mixed
343
+     */
344
+    public function rmdir($path) {
345
+        $absolutePath = $this->getAbsolutePath($path);
346
+        $mount = Filesystem::getMountManager()->find($absolutePath);
347
+        if ($mount->getInternalPath($absolutePath) === '') {
348
+            return $this->removeMount($mount, $absolutePath);
349
+        }
350
+        if ($this->is_dir($path)) {
351
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
352
+        } else {
353
+            $result = false;
354
+        }
355
+
356
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
357
+            $storage = $mount->getStorage();
358
+            $internalPath = $mount->getInternalPath($absolutePath);
359
+            $storage->getUpdater()->remove($internalPath);
360
+        }
361
+        return $result;
362
+    }
363
+
364
+    /**
365
+     * @param string $path
366
+     * @return resource
367
+     */
368
+    public function opendir($path) {
369
+        return $this->basicOperation('opendir', $path, ['read']);
370
+    }
371
+
372
+    /**
373
+     * @param string $path
374
+     * @return bool|mixed
375
+     */
376
+    public function is_dir($path) {
377
+        if ($path == '/') {
378
+            return true;
379
+        }
380
+        return $this->basicOperation('is_dir', $path);
381
+    }
382
+
383
+    /**
384
+     * @param string $path
385
+     * @return bool|mixed
386
+     */
387
+    public function is_file($path) {
388
+        if ($path == '/') {
389
+            return false;
390
+        }
391
+        return $this->basicOperation('is_file', $path);
392
+    }
393
+
394
+    /**
395
+     * @param string $path
396
+     * @return mixed
397
+     */
398
+    public function stat($path) {
399
+        return $this->basicOperation('stat', $path);
400
+    }
401
+
402
+    /**
403
+     * @param string $path
404
+     * @return mixed
405
+     */
406
+    public function filetype($path) {
407
+        return $this->basicOperation('filetype', $path);
408
+    }
409
+
410
+    /**
411
+     * @param string $path
412
+     * @return mixed
413
+     */
414
+    public function filesize(string $path) {
415
+        return $this->basicOperation('filesize', $path);
416
+    }
417
+
418
+    /**
419
+     * @param string $path
420
+     * @return bool|mixed
421
+     * @throws \OCP\Files\InvalidPathException
422
+     */
423
+    public function readfile($path) {
424
+        $this->assertPathLength($path);
425
+        if (ob_get_level()) {
426
+            ob_end_clean();
427
+        }
428
+        $handle = $this->fopen($path, 'rb');
429
+        if ($handle) {
430
+            $chunkSize = 524288; // 512 kB chunks
431
+            while (!feof($handle)) {
432
+                echo fread($handle, $chunkSize);
433
+                flush();
434
+            }
435
+            fclose($handle);
436
+            return $this->filesize($path);
437
+        }
438
+        return false;
439
+    }
440
+
441
+    /**
442
+     * @param string $path
443
+     * @param int $from
444
+     * @param int $to
445
+     * @return bool|mixed
446
+     * @throws \OCP\Files\InvalidPathException
447
+     * @throws \OCP\Files\UnseekableException
448
+     */
449
+    public function readfilePart($path, $from, $to) {
450
+        $this->assertPathLength($path);
451
+        if (ob_get_level()) {
452
+            ob_end_clean();
453
+        }
454
+        $handle = $this->fopen($path, 'rb');
455
+        if ($handle) {
456
+            $chunkSize = 524288; // 512 kB chunks
457
+            $startReading = true;
458
+
459
+            if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
460
+                // forward file handle via chunked fread because fseek seem to have failed
461
+
462
+                $end = $from + 1;
463
+                while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
464
+                    $len = $from - ftell($handle);
465
+                    if ($len > $chunkSize) {
466
+                        $len = $chunkSize;
467
+                    }
468
+                    $result = fread($handle, $len);
469
+
470
+                    if ($result === false) {
471
+                        $startReading = false;
472
+                        break;
473
+                    }
474
+                }
475
+            }
476
+
477
+            if ($startReading) {
478
+                $end = $to + 1;
479
+                while (!feof($handle) && ftell($handle) < $end) {
480
+                    $len = $end - ftell($handle);
481
+                    if ($len > $chunkSize) {
482
+                        $len = $chunkSize;
483
+                    }
484
+                    echo fread($handle, $len);
485
+                    flush();
486
+                }
487
+                return ftell($handle) - $from;
488
+            }
489
+
490
+            throw new \OCP\Files\UnseekableException('fseek error');
491
+        }
492
+        return false;
493
+    }
494
+
495
+    /**
496
+     * @param string $path
497
+     * @return mixed
498
+     */
499
+    public function isCreatable($path) {
500
+        return $this->basicOperation('isCreatable', $path);
501
+    }
502
+
503
+    /**
504
+     * @param string $path
505
+     * @return mixed
506
+     */
507
+    public function isReadable($path) {
508
+        return $this->basicOperation('isReadable', $path);
509
+    }
510
+
511
+    /**
512
+     * @param string $path
513
+     * @return mixed
514
+     */
515
+    public function isUpdatable($path) {
516
+        return $this->basicOperation('isUpdatable', $path);
517
+    }
518
+
519
+    /**
520
+     * @param string $path
521
+     * @return bool|mixed
522
+     */
523
+    public function isDeletable($path) {
524
+        $absolutePath = $this->getAbsolutePath($path);
525
+        $mount = Filesystem::getMountManager()->find($absolutePath);
526
+        if ($mount->getInternalPath($absolutePath) === '') {
527
+            return $mount instanceof MoveableMount;
528
+        }
529
+        return $this->basicOperation('isDeletable', $path);
530
+    }
531
+
532
+    /**
533
+     * @param string $path
534
+     * @return mixed
535
+     */
536
+    public function isSharable($path) {
537
+        return $this->basicOperation('isSharable', $path);
538
+    }
539
+
540
+    /**
541
+     * @param string $path
542
+     * @return bool|mixed
543
+     */
544
+    public function file_exists($path) {
545
+        if ($path == '/') {
546
+            return true;
547
+        }
548
+        return $this->basicOperation('file_exists', $path);
549
+    }
550
+
551
+    /**
552
+     * @param string $path
553
+     * @return mixed
554
+     */
555
+    public function filemtime($path) {
556
+        return $this->basicOperation('filemtime', $path);
557
+    }
558
+
559
+    /**
560
+     * @param string $path
561
+     * @param int|string $mtime
562
+     * @return bool
563
+     */
564
+    public function touch($path, $mtime = null) {
565
+        if (!is_null($mtime) and !is_numeric($mtime)) {
566
+            $mtime = strtotime($mtime);
567
+        }
568
+
569
+        $hooks = ['touch'];
570
+
571
+        if (!$this->file_exists($path)) {
572
+            $hooks[] = 'create';
573
+            $hooks[] = 'write';
574
+        }
575
+        try {
576
+            $result = $this->basicOperation('touch', $path, $hooks, $mtime);
577
+        } catch (\Exception $e) {
578
+            $this->logger->info('Error while setting modified time', ['app' => 'core', 'exception' => $e]);
579
+            $result = false;
580
+        }
581
+        if (!$result) {
582
+            // If create file fails because of permissions on external storage like SMB folders,
583
+            // check file exists and return false if not.
584
+            if (!$this->file_exists($path)) {
585
+                return false;
586
+            }
587
+            if (is_null($mtime)) {
588
+                $mtime = time();
589
+            }
590
+            //if native touch fails, we emulate it by changing the mtime in the cache
591
+            $this->putFileInfo($path, ['mtime' => floor($mtime)]);
592
+        }
593
+        return true;
594
+    }
595
+
596
+    /**
597
+     * @param string $path
598
+     * @return mixed
599
+     * @throws LockedException
600
+     */
601
+    public function file_get_contents($path) {
602
+        return $this->basicOperation('file_get_contents', $path, ['read']);
603
+    }
604
+
605
+    /**
606
+     * @param bool $exists
607
+     * @param string $path
608
+     * @param bool $run
609
+     */
610
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
611
+        if (!$exists) {
612
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
613
+                Filesystem::signal_param_path => $this->getHookPath($path),
614
+                Filesystem::signal_param_run => &$run,
615
+            ]);
616
+        } else {
617
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
618
+                Filesystem::signal_param_path => $this->getHookPath($path),
619
+                Filesystem::signal_param_run => &$run,
620
+            ]);
621
+        }
622
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
623
+            Filesystem::signal_param_path => $this->getHookPath($path),
624
+            Filesystem::signal_param_run => &$run,
625
+        ]);
626
+    }
627
+
628
+    /**
629
+     * @param bool $exists
630
+     * @param string $path
631
+     */
632
+    protected function emit_file_hooks_post($exists, $path) {
633
+        if (!$exists) {
634
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
635
+                Filesystem::signal_param_path => $this->getHookPath($path),
636
+            ]);
637
+        } else {
638
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
639
+                Filesystem::signal_param_path => $this->getHookPath($path),
640
+            ]);
641
+        }
642
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
643
+            Filesystem::signal_param_path => $this->getHookPath($path),
644
+        ]);
645
+    }
646
+
647
+    /**
648
+     * @param string $path
649
+     * @param string|resource $data
650
+     * @return bool|mixed
651
+     * @throws LockedException
652
+     */
653
+    public function file_put_contents($path, $data) {
654
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
655
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
656
+            if (Filesystem::isValidPath($path)
657
+                and !Filesystem::isFileBlacklisted($path)
658
+            ) {
659
+                $path = $this->getRelativePath($absolutePath);
660
+
661
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
662
+
663
+                $exists = $this->file_exists($path);
664
+                $run = true;
665
+                if ($this->shouldEmitHooks($path)) {
666
+                    $this->emit_file_hooks_pre($exists, $path, $run);
667
+                }
668
+                if (!$run) {
669
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
670
+                    return false;
671
+                }
672
+
673
+                try {
674
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
675
+                } catch (\Exception $e) {
676
+                    // Release the shared lock before throwing.
677
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
678
+                    throw $e;
679
+                }
680
+
681
+                /** @var \OC\Files\Storage\Storage $storage */
682
+                [$storage, $internalPath] = $this->resolvePath($path);
683
+                $target = $storage->fopen($internalPath, 'w');
684
+                if ($target) {
685
+                    [, $result] = \OC_Helper::streamCopy($data, $target);
686
+                    fclose($target);
687
+                    fclose($data);
688
+
689
+                    $this->writeUpdate($storage, $internalPath);
690
+
691
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
692
+
693
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
694
+                        $this->emit_file_hooks_post($exists, $path);
695
+                    }
696
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
697
+                    return $result;
698
+                } else {
699
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
700
+                    return false;
701
+                }
702
+            } else {
703
+                return false;
704
+            }
705
+        } else {
706
+            $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
707
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
708
+        }
709
+    }
710
+
711
+    /**
712
+     * @param string $path
713
+     * @return bool|mixed
714
+     */
715
+    public function unlink($path) {
716
+        if ($path === '' || $path === '/') {
717
+            // do not allow deleting the root
718
+            return false;
719
+        }
720
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
721
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
722
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
723
+        if ($mount->getInternalPath($absolutePath) === '') {
724
+            return $this->removeMount($mount, $absolutePath);
725
+        }
726
+        if ($this->is_dir($path)) {
727
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
728
+        } else {
729
+            $result = $this->basicOperation('unlink', $path, ['delete']);
730
+        }
731
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
732
+            $storage = $mount->getStorage();
733
+            $internalPath = $mount->getInternalPath($absolutePath);
734
+            $storage->getUpdater()->remove($internalPath);
735
+            return true;
736
+        } else {
737
+            return $result;
738
+        }
739
+    }
740
+
741
+    /**
742
+     * @param string $directory
743
+     * @return bool|mixed
744
+     */
745
+    public function deleteAll($directory) {
746
+        return $this->rmdir($directory);
747
+    }
748
+
749
+    /**
750
+     * Rename/move a file or folder from the source path to target path.
751
+     *
752
+     * @param string $source source path
753
+     * @param string $target target path
754
+     *
755
+     * @return bool|mixed
756
+     * @throws LockedException
757
+     */
758
+    public function rename($source, $target) {
759
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
760
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
761
+        $result = false;
762
+        if (
763
+            Filesystem::isValidPath($target)
764
+            and Filesystem::isValidPath($source)
765
+            and !Filesystem::isFileBlacklisted($target)
766
+        ) {
767
+            $source = $this->getRelativePath($absolutePath1);
768
+            $target = $this->getRelativePath($absolutePath2);
769
+            $exists = $this->file_exists($target);
770
+
771
+            if ($source == null or $target == null) {
772
+                return false;
773
+            }
774
+
775
+            $this->lockFile($source, ILockingProvider::LOCK_SHARED, true);
776
+            try {
777
+                $this->lockFile($target, ILockingProvider::LOCK_SHARED, true);
778
+
779
+                $run = true;
780
+                if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) {
781
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
782
+                    $this->emit_file_hooks_pre($exists, $target, $run);
783
+                } elseif ($this->shouldEmitHooks($source)) {
784
+                    \OC_Hook::emit(
785
+                        Filesystem::CLASSNAME, Filesystem::signal_rename,
786
+                        [
787
+                            Filesystem::signal_param_oldpath => $this->getHookPath($source),
788
+                            Filesystem::signal_param_newpath => $this->getHookPath($target),
789
+                            Filesystem::signal_param_run => &$run
790
+                        ]
791
+                    );
792
+                }
793
+                if ($run) {
794
+                    $this->verifyPath(dirname($target), basename($target));
795
+
796
+                    $manager = Filesystem::getMountManager();
797
+                    $mount1 = $this->getMount($source);
798
+                    $mount2 = $this->getMount($target);
799
+                    $storage1 = $mount1->getStorage();
800
+                    $storage2 = $mount2->getStorage();
801
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
802
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
803
+
804
+                    $this->changeLock($source, ILockingProvider::LOCK_EXCLUSIVE, true);
805
+                    try {
806
+                        $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE, true);
807
+
808
+                        if ($internalPath1 === '') {
809
+                            if ($mount1 instanceof MoveableMount) {
810
+                                $sourceParentMount = $this->getMount(dirname($source));
811
+                                if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
812
+                                    /**
813
+                                     * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
814
+                                     */
815
+                                    $sourceMountPoint = $mount1->getMountPoint();
816
+                                    $result = $mount1->moveMount($absolutePath2);
817
+                                    $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
818
+                                } else {
819
+                                    $result = false;
820
+                                }
821
+                            } else {
822
+                                $result = false;
823
+                            }
824
+                        // moving a file/folder within the same mount point
825
+                        } elseif ($storage1 === $storage2) {
826
+                            if ($storage1) {
827
+                                $result = $storage1->rename($internalPath1, $internalPath2);
828
+                            } else {
829
+                                $result = false;
830
+                            }
831
+                        // moving a file/folder between storages (from $storage1 to $storage2)
832
+                        } else {
833
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
834
+                        }
835
+
836
+                        if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
837
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
838
+                            $this->writeUpdate($storage2, $internalPath2);
839
+                        } elseif ($result) {
840
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
841
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
842
+                            }
843
+                        }
844
+                    } catch (\Exception $e) {
845
+                        throw $e;
846
+                    } finally {
847
+                        $this->changeLock($source, ILockingProvider::LOCK_SHARED, true);
848
+                        $this->changeLock($target, ILockingProvider::LOCK_SHARED, true);
849
+                    }
850
+
851
+                    if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
852
+                        if ($this->shouldEmitHooks()) {
853
+                            $this->emit_file_hooks_post($exists, $target);
854
+                        }
855
+                    } elseif ($result) {
856
+                        if ($this->shouldEmitHooks($source) and $this->shouldEmitHooks($target)) {
857
+                            \OC_Hook::emit(
858
+                                Filesystem::CLASSNAME,
859
+                                Filesystem::signal_post_rename,
860
+                                [
861
+                                    Filesystem::signal_param_oldpath => $this->getHookPath($source),
862
+                                    Filesystem::signal_param_newpath => $this->getHookPath($target)
863
+                                ]
864
+                            );
865
+                        }
866
+                    }
867
+                }
868
+            } catch (\Exception $e) {
869
+                throw $e;
870
+            } finally {
871
+                $this->unlockFile($source, ILockingProvider::LOCK_SHARED, true);
872
+                $this->unlockFile($target, ILockingProvider::LOCK_SHARED, true);
873
+            }
874
+        }
875
+        return $result;
876
+    }
877
+
878
+    /**
879
+     * Copy a file/folder from the source path to target path
880
+     *
881
+     * @param string $source source path
882
+     * @param string $target target path
883
+     * @param bool $preserveMtime whether to preserve mtime on the copy
884
+     *
885
+     * @return bool|mixed
886
+     */
887
+    public function copy($source, $target, $preserveMtime = false) {
888
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
889
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
890
+        $result = false;
891
+        if (
892
+            Filesystem::isValidPath($target)
893
+            and Filesystem::isValidPath($source)
894
+            and !Filesystem::isFileBlacklisted($target)
895
+        ) {
896
+            $source = $this->getRelativePath($absolutePath1);
897
+            $target = $this->getRelativePath($absolutePath2);
898
+
899
+            if ($source == null or $target == null) {
900
+                return false;
901
+            }
902
+            $run = true;
903
+
904
+            $this->lockFile($target, ILockingProvider::LOCK_SHARED);
905
+            $this->lockFile($source, ILockingProvider::LOCK_SHARED);
906
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
907
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
908
+
909
+            try {
910
+                $exists = $this->file_exists($target);
911
+                if ($this->shouldEmitHooks()) {
912
+                    \OC_Hook::emit(
913
+                        Filesystem::CLASSNAME,
914
+                        Filesystem::signal_copy,
915
+                        [
916
+                            Filesystem::signal_param_oldpath => $this->getHookPath($source),
917
+                            Filesystem::signal_param_newpath => $this->getHookPath($target),
918
+                            Filesystem::signal_param_run => &$run
919
+                        ]
920
+                    );
921
+                    $this->emit_file_hooks_pre($exists, $target, $run);
922
+                }
923
+                if ($run) {
924
+                    $mount1 = $this->getMount($source);
925
+                    $mount2 = $this->getMount($target);
926
+                    $storage1 = $mount1->getStorage();
927
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
928
+                    $storage2 = $mount2->getStorage();
929
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
930
+
931
+                    $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE);
932
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
933
+
934
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
935
+                        if ($storage1) {
936
+                            $result = $storage1->copy($internalPath1, $internalPath2);
937
+                        } else {
938
+                            $result = false;
939
+                        }
940
+                    } else {
941
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
942
+                    }
943
+
944
+                    $this->writeUpdate($storage2, $internalPath2);
945
+
946
+                    $this->changeLock($target, ILockingProvider::LOCK_SHARED);
947
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
948
+
949
+                    if ($this->shouldEmitHooks() && $result !== false) {
950
+                        \OC_Hook::emit(
951
+                            Filesystem::CLASSNAME,
952
+                            Filesystem::signal_post_copy,
953
+                            [
954
+                                Filesystem::signal_param_oldpath => $this->getHookPath($source),
955
+                                Filesystem::signal_param_newpath => $this->getHookPath($target)
956
+                            ]
957
+                        );
958
+                        $this->emit_file_hooks_post($exists, $target);
959
+                    }
960
+                }
961
+            } catch (\Exception $e) {
962
+                $this->unlockFile($target, $lockTypePath2);
963
+                $this->unlockFile($source, $lockTypePath1);
964
+                throw $e;
965
+            }
966
+
967
+            $this->unlockFile($target, $lockTypePath2);
968
+            $this->unlockFile($source, $lockTypePath1);
969
+        }
970
+        return $result;
971
+    }
972
+
973
+    /**
974
+     * @param string $path
975
+     * @param string $mode 'r' or 'w'
976
+     * @return resource
977
+     * @throws LockedException
978
+     */
979
+    public function fopen($path, $mode) {
980
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
981
+        $hooks = [];
982
+        switch ($mode) {
983
+            case 'r':
984
+                $hooks[] = 'read';
985
+                break;
986
+            case 'r+':
987
+            case 'w+':
988
+            case 'x+':
989
+            case 'a+':
990
+                $hooks[] = 'read';
991
+                $hooks[] = 'write';
992
+                break;
993
+            case 'w':
994
+            case 'x':
995
+            case 'a':
996
+                $hooks[] = 'write';
997
+                break;
998
+            default:
999
+                $this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
1000
+        }
1001
+
1002
+        if ($mode !== 'r' && $mode !== 'w') {
1003
+            $this->logger->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends', ['app' => 'core']);
1004
+        }
1005
+
1006
+        $handle = $this->basicOperation('fopen', $path, $hooks, $mode);
1007
+        if (!is_resource($handle) && $mode === 'r') {
1008
+            // trying to read a file that isn't on disk, check if the cache is out of sync and rescan if needed
1009
+            $mount = $this->getMount($path);
1010
+            $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1011
+            $storage = $mount->getStorage();
1012
+            if ($storage->getCache()->inCache($internalPath) && !$storage->file_exists($path)) {
1013
+                $this->writeUpdate($storage, $internalPath);
1014
+            }
1015
+        }
1016
+        return $handle;
1017
+    }
1018
+
1019
+    /**
1020
+     * @param string $path
1021
+     * @return bool|string
1022
+     * @throws \OCP\Files\InvalidPathException
1023
+     */
1024
+    public function toTmpFile($path) {
1025
+        $this->assertPathLength($path);
1026
+        if (Filesystem::isValidPath($path)) {
1027
+            $source = $this->fopen($path, 'r');
1028
+            if ($source) {
1029
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
1030
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1031
+                file_put_contents($tmpFile, $source);
1032
+                return $tmpFile;
1033
+            } else {
1034
+                return false;
1035
+            }
1036
+        } else {
1037
+            return false;
1038
+        }
1039
+    }
1040
+
1041
+    /**
1042
+     * @param string $tmpFile
1043
+     * @param string $path
1044
+     * @return bool|mixed
1045
+     * @throws \OCP\Files\InvalidPathException
1046
+     */
1047
+    public function fromTmpFile($tmpFile, $path) {
1048
+        $this->assertPathLength($path);
1049
+        if (Filesystem::isValidPath($path)) {
1050
+            // Get directory that the file is going into
1051
+            $filePath = dirname($path);
1052
+
1053
+            // Create the directories if any
1054
+            if (!$this->file_exists($filePath)) {
1055
+                $result = $this->createParentDirectories($filePath);
1056
+                if ($result === false) {
1057
+                    return false;
1058
+                }
1059
+            }
1060
+
1061
+            $source = fopen($tmpFile, 'r');
1062
+            if ($source) {
1063
+                $result = $this->file_put_contents($path, $source);
1064
+                // $this->file_put_contents() might have already closed
1065
+                // the resource, so we check it, before trying to close it
1066
+                // to avoid messages in the error log.
1067
+                if (is_resource($source)) {
1068
+                    fclose($source);
1069
+                }
1070
+                unlink($tmpFile);
1071
+                return $result;
1072
+            } else {
1073
+                return false;
1074
+            }
1075
+        } else {
1076
+            return false;
1077
+        }
1078
+    }
1079
+
1080
+
1081
+    /**
1082
+     * @param string $path
1083
+     * @return mixed
1084
+     * @throws \OCP\Files\InvalidPathException
1085
+     */
1086
+    public function getMimeType($path) {
1087
+        $this->assertPathLength($path);
1088
+        return $this->basicOperation('getMimeType', $path);
1089
+    }
1090
+
1091
+    /**
1092
+     * @param string $type
1093
+     * @param string $path
1094
+     * @param bool $raw
1095
+     * @return bool|string
1096
+     */
1097
+    public function hash($type, $path, $raw = false) {
1098
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1099
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1100
+        if (Filesystem::isValidPath($path)) {
1101
+            $path = $this->getRelativePath($absolutePath);
1102
+            if ($path == null) {
1103
+                return false;
1104
+            }
1105
+            if ($this->shouldEmitHooks($path)) {
1106
+                \OC_Hook::emit(
1107
+                    Filesystem::CLASSNAME,
1108
+                    Filesystem::signal_read,
1109
+                    [Filesystem::signal_param_path => $this->getHookPath($path)]
1110
+                );
1111
+            }
1112
+            /** @var Storage|null $storage */
1113
+            [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1114
+            if ($storage) {
1115
+                return $storage->hash($type, $internalPath, $raw);
1116
+            }
1117
+        }
1118
+        return false;
1119
+    }
1120
+
1121
+    /**
1122
+     * @param string $path
1123
+     * @return mixed
1124
+     * @throws \OCP\Files\InvalidPathException
1125
+     */
1126
+    public function free_space($path = '/') {
1127
+        $this->assertPathLength($path);
1128
+        $result = $this->basicOperation('free_space', $path);
1129
+        if ($result === null) {
1130
+            throw new InvalidPathException();
1131
+        }
1132
+        return $result;
1133
+    }
1134
+
1135
+    /**
1136
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1137
+     *
1138
+     * @param string $operation
1139
+     * @param string $path
1140
+     * @param array $hooks (optional)
1141
+     * @param mixed $extraParam (optional)
1142
+     * @return mixed
1143
+     * @throws LockedException
1144
+     *
1145
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1146
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1147
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1148
+     */
1149
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1150
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1151
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1152
+        if (Filesystem::isValidPath($path)
1153
+            and !Filesystem::isFileBlacklisted($path)
1154
+        ) {
1155
+            $path = $this->getRelativePath($absolutePath);
1156
+            if ($path == null) {
1157
+                return false;
1158
+            }
1159
+
1160
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1161
+                // always a shared lock during pre-hooks so the hook can read the file
1162
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1163
+            }
1164
+
1165
+            $run = $this->runHooks($hooks, $path);
1166
+            /** @var \OC\Files\Storage\Storage $storage */
1167
+            [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1168
+            if ($run and $storage) {
1169
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1170
+                    try {
1171
+                        $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1172
+                    } catch (LockedException $e) {
1173
+                        // release the shared lock we acquired before quitting
1174
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1175
+                        throw $e;
1176
+                    }
1177
+                }
1178
+                try {
1179
+                    if (!is_null($extraParam)) {
1180
+                        $result = $storage->$operation($internalPath, $extraParam);
1181
+                    } else {
1182
+                        $result = $storage->$operation($internalPath);
1183
+                    }
1184
+                } catch (\Exception $e) {
1185
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1186
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1187
+                    } elseif (in_array('read', $hooks)) {
1188
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1189
+                    }
1190
+                    throw $e;
1191
+                }
1192
+
1193
+                if ($result !== false && in_array('delete', $hooks)) {
1194
+                    $this->removeUpdate($storage, $internalPath);
1195
+                }
1196
+                if ($result !== false && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
1197
+                    $this->writeUpdate($storage, $internalPath);
1198
+                }
1199
+                if ($result !== false && in_array('touch', $hooks)) {
1200
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1201
+                }
1202
+
1203
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1204
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1205
+                }
1206
+
1207
+                $unlockLater = false;
1208
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1209
+                    $unlockLater = true;
1210
+                    // make sure our unlocking callback will still be called if connection is aborted
1211
+                    ignore_user_abort(true);
1212
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1213
+                        if (in_array('write', $hooks)) {
1214
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1215
+                        } elseif (in_array('read', $hooks)) {
1216
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1217
+                        }
1218
+                    });
1219
+                }
1220
+
1221
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1222
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1223
+                        $this->runHooks($hooks, $path, true);
1224
+                    }
1225
+                }
1226
+
1227
+                if (!$unlockLater
1228
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1229
+                ) {
1230
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1231
+                }
1232
+                return $result;
1233
+            } else {
1234
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1235
+            }
1236
+        }
1237
+        return null;
1238
+    }
1239
+
1240
+    /**
1241
+     * get the path relative to the default root for hook usage
1242
+     *
1243
+     * @param string $path
1244
+     * @return ?string
1245
+     */
1246
+    private function getHookPath($path) {
1247
+        if (!Filesystem::getView()) {
1248
+            return $path;
1249
+        }
1250
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1251
+    }
1252
+
1253
+    private function shouldEmitHooks($path = '') {
1254
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1255
+            return false;
1256
+        }
1257
+        if (!Filesystem::$loaded) {
1258
+            return false;
1259
+        }
1260
+        $defaultRoot = Filesystem::getRoot();
1261
+        if ($defaultRoot === null) {
1262
+            return false;
1263
+        }
1264
+        if ($this->fakeRoot === $defaultRoot) {
1265
+            return true;
1266
+        }
1267
+        $fullPath = $this->getAbsolutePath($path);
1268
+
1269
+        if ($fullPath === $defaultRoot) {
1270
+            return true;
1271
+        }
1272
+
1273
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1274
+    }
1275
+
1276
+    /**
1277
+     * @param string[] $hooks
1278
+     * @param string $path
1279
+     * @param bool $post
1280
+     * @return bool
1281
+     */
1282
+    private function runHooks($hooks, $path, $post = false) {
1283
+        $relativePath = $path;
1284
+        $path = $this->getHookPath($path);
1285
+        $prefix = $post ? 'post_' : '';
1286
+        $run = true;
1287
+        if ($this->shouldEmitHooks($relativePath)) {
1288
+            foreach ($hooks as $hook) {
1289
+                if ($hook != 'read') {
1290
+                    \OC_Hook::emit(
1291
+                        Filesystem::CLASSNAME,
1292
+                        $prefix . $hook,
1293
+                        [
1294
+                            Filesystem::signal_param_run => &$run,
1295
+                            Filesystem::signal_param_path => $path
1296
+                        ]
1297
+                    );
1298
+                } elseif (!$post) {
1299
+                    \OC_Hook::emit(
1300
+                        Filesystem::CLASSNAME,
1301
+                        $prefix . $hook,
1302
+                        [
1303
+                            Filesystem::signal_param_path => $path
1304
+                        ]
1305
+                    );
1306
+                }
1307
+            }
1308
+        }
1309
+        return $run;
1310
+    }
1311
+
1312
+    /**
1313
+     * check if a file or folder has been updated since $time
1314
+     *
1315
+     * @param string $path
1316
+     * @param int $time
1317
+     * @return bool
1318
+     */
1319
+    public function hasUpdated($path, $time) {
1320
+        return $this->basicOperation('hasUpdated', $path, [], $time);
1321
+    }
1322
+
1323
+    /**
1324
+     * @param string $ownerId
1325
+     * @return IUser
1326
+     */
1327
+    private function getUserObjectForOwner(string $ownerId) {
1328
+        return new LazyUser($ownerId, $this->userManager);
1329
+    }
1330
+
1331
+    /**
1332
+     * Get file info from cache
1333
+     *
1334
+     * If the file is not in cached it will be scanned
1335
+     * If the file has changed on storage the cache will be updated
1336
+     *
1337
+     * @param \OC\Files\Storage\Storage $storage
1338
+     * @param string $internalPath
1339
+     * @param string $relativePath
1340
+     * @return ICacheEntry|bool
1341
+     */
1342
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1343
+        $cache = $storage->getCache($internalPath);
1344
+        $data = $cache->get($internalPath);
1345
+        $watcher = $storage->getWatcher($internalPath);
1346
+
1347
+        try {
1348
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1349
+            if (!$data || (isset($data['size']) && $data['size'] === -1)) {
1350
+                if (!$storage->file_exists($internalPath)) {
1351
+                    return false;
1352
+                }
1353
+                // don't need to get a lock here since the scanner does it's own locking
1354
+                $scanner = $storage->getScanner($internalPath);
1355
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1356
+                $data = $cache->get($internalPath);
1357
+            } elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1358
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1359
+                $watcher->update($internalPath, $data);
1360
+                $storage->getPropagator()->propagateChange($internalPath, time());
1361
+                $data = $cache->get($internalPath);
1362
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1363
+            }
1364
+        } catch (LockedException $e) {
1365
+            // if the file is locked we just use the old cache info
1366
+        }
1367
+
1368
+        return $data;
1369
+    }
1370
+
1371
+    /**
1372
+     * get the filesystem info
1373
+     *
1374
+     * @param string $path
1375
+     * @param bool|string $includeMountPoints true to add mountpoint sizes,
1376
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1377
+     * @return \OC\Files\FileInfo|false False if file does not exist
1378
+     */
1379
+    public function getFileInfo($path, $includeMountPoints = true) {
1380
+        $this->assertPathLength($path);
1381
+        if (!Filesystem::isValidPath($path)) {
1382
+            return false;
1383
+        }
1384
+        if (Cache\Scanner::isPartialFile($path)) {
1385
+            return $this->getPartFileInfo($path);
1386
+        }
1387
+        $relativePath = $path;
1388
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1389
+
1390
+        $mount = Filesystem::getMountManager()->find($path);
1391
+        $storage = $mount->getStorage();
1392
+        $internalPath = $mount->getInternalPath($path);
1393
+        if ($storage) {
1394
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1395
+
1396
+            if (!$data instanceof ICacheEntry) {
1397
+                return false;
1398
+            }
1399
+
1400
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1401
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1402
+            }
1403
+            $ownerId = $storage->getOwner($internalPath);
1404
+            $owner = null;
1405
+            if ($ownerId !== null && $ownerId !== false) {
1406
+                // ownerId might be null if files are accessed with an access token without file system access
1407
+                $owner = $this->getUserObjectForOwner($ownerId);
1408
+            }
1409
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1410
+
1411
+            if (isset($data['fileid'])) {
1412
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1413
+                    //add the sizes of other mount points to the folder
1414
+                    $extOnly = ($includeMountPoints === 'ext');
1415
+                    $this->addSubMounts($info, $extOnly);
1416
+                }
1417
+            }
1418
+
1419
+            return $info;
1420
+        } else {
1421
+            $this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
1422
+        }
1423
+
1424
+        return false;
1425
+    }
1426
+
1427
+    /**
1428
+     * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
1429
+     */
1430
+    public function addSubMounts(FileInfo $info, $extOnly = false): void {
1431
+        $mounts = Filesystem::getMountManager()->findIn($info->getPath());
1432
+        $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1433
+            $subStorage = $mount->getStorage();
1434
+            return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1435
+        }));
1436
+    }
1437
+
1438
+    /**
1439
+     * get the content of a directory
1440
+     *
1441
+     * @param string $directory path under datadirectory
1442
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1443
+     * @return FileInfo[]
1444
+     */
1445
+    public function getDirectoryContent($directory, $mimetype_filter = '', \OCP\Files\FileInfo $directoryInfo = null) {
1446
+        $this->assertPathLength($directory);
1447
+        if (!Filesystem::isValidPath($directory)) {
1448
+            return [];
1449
+        }
1450
+
1451
+        $path = $this->getAbsolutePath($directory);
1452
+        $path = Filesystem::normalizePath($path);
1453
+        $mount = $this->getMount($directory);
1454
+        $storage = $mount->getStorage();
1455
+        $internalPath = $mount->getInternalPath($path);
1456
+        if (!$storage) {
1457
+            return [];
1458
+        }
1459
+
1460
+        $cache = $storage->getCache($internalPath);
1461
+        $user = \OC_User::getUser();
1462
+
1463
+        if (!$directoryInfo) {
1464
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1465
+            if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
1466
+                return [];
1467
+            }
1468
+        } else {
1469
+            $data = $directoryInfo;
1470
+        }
1471
+
1472
+        if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
1473
+            return [];
1474
+        }
1475
+
1476
+        $folderId = $data->getId();
1477
+        $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1478
+
1479
+        $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1480
+
1481
+        $fileNames = array_map(function (ICacheEntry $content) {
1482
+            return $content->getName();
1483
+        }, $contents);
1484
+        /**
1485
+         * @var \OC\Files\FileInfo[] $fileInfos
1486
+         */
1487
+        $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1488
+            if ($sharingDisabled) {
1489
+                $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1490
+            }
1491
+            $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1492
+            return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1493
+        }, $contents);
1494
+        $files = array_combine($fileNames, $fileInfos);
1495
+
1496
+        //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1497
+        $mounts = Filesystem::getMountManager()->findIn($path);
1498
+        $dirLength = strlen($path);
1499
+        foreach ($mounts as $mount) {
1500
+            $mountPoint = $mount->getMountPoint();
1501
+            $subStorage = $mount->getStorage();
1502
+            if ($subStorage) {
1503
+                $subCache = $subStorage->getCache('');
1504
+
1505
+                $rootEntry = $subCache->get('');
1506
+                if (!$rootEntry) {
1507
+                    $subScanner = $subStorage->getScanner();
1508
+                    try {
1509
+                        $subScanner->scanFile('');
1510
+                    } catch (\OCP\Files\StorageNotAvailableException $e) {
1511
+                        continue;
1512
+                    } catch (\OCP\Files\StorageInvalidException $e) {
1513
+                        continue;
1514
+                    } catch (\Exception $e) {
1515
+                        // sometimes when the storage is not available it can be any exception
1516
+                        $this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
1517
+                            'exception' => $e,
1518
+                            'app' => 'core',
1519
+                        ]);
1520
+                        continue;
1521
+                    }
1522
+                    $rootEntry = $subCache->get('');
1523
+                }
1524
+
1525
+                if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
1526
+                    $relativePath = trim(substr($mountPoint, $dirLength), '/');
1527
+                    if ($pos = strpos($relativePath, '/')) {
1528
+                        //mountpoint inside subfolder add size to the correct folder
1529
+                        $entryName = substr($relativePath, 0, $pos);
1530
+                        if (isset($files[$entryName])) {
1531
+                            $files[$entryName]->addSubEntry($rootEntry, $mountPoint);
1532
+                        }
1533
+                    } else { //mountpoint in this folder, add an entry for it
1534
+                        $rootEntry['name'] = $relativePath;
1535
+                        $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1536
+                        $permissions = $rootEntry['permissions'];
1537
+                        // do not allow renaming/deleting the mount point if they are not shared files/folders
1538
+                        // for shared files/folders we use the permissions given by the owner
1539
+                        if ($mount instanceof MoveableMount) {
1540
+                            $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1541
+                        } else {
1542
+                            $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1543
+                        }
1544
+
1545
+                        $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1546
+
1547
+                        // if sharing was disabled for the user we remove the share permissions
1548
+                        if (\OCP\Util::isSharingDisabledForUser()) {
1549
+                            $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1550
+                        }
1551
+
1552
+                        $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1553
+                        $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1554
+                    }
1555
+                }
1556
+            }
1557
+        }
1558
+
1559
+        if ($mimetype_filter) {
1560
+            $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1561
+                if (strpos($mimetype_filter, '/')) {
1562
+                    return $file->getMimetype() === $mimetype_filter;
1563
+                } else {
1564
+                    return $file->getMimePart() === $mimetype_filter;
1565
+                }
1566
+            });
1567
+        }
1568
+
1569
+        return array_values($files);
1570
+    }
1571
+
1572
+    /**
1573
+     * change file metadata
1574
+     *
1575
+     * @param string $path
1576
+     * @param array|\OCP\Files\FileInfo $data
1577
+     * @return int
1578
+     *
1579
+     * returns the fileid of the updated file
1580
+     */
1581
+    public function putFileInfo($path, $data) {
1582
+        $this->assertPathLength($path);
1583
+        if ($data instanceof FileInfo) {
1584
+            $data = $data->getData();
1585
+        }
1586
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1587
+        /**
1588
+         * @var \OC\Files\Storage\Storage $storage
1589
+         * @var string $internalPath
1590
+         */
1591
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
1592
+        if ($storage) {
1593
+            $cache = $storage->getCache($path);
1594
+
1595
+            if (!$cache->inCache($internalPath)) {
1596
+                $scanner = $storage->getScanner($internalPath);
1597
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1598
+            }
1599
+
1600
+            return $cache->put($internalPath, $data);
1601
+        } else {
1602
+            return -1;
1603
+        }
1604
+    }
1605
+
1606
+    /**
1607
+     * search for files with the name matching $query
1608
+     *
1609
+     * @param string $query
1610
+     * @return FileInfo[]
1611
+     */
1612
+    public function search($query) {
1613
+        return $this->searchCommon('search', ['%' . $query . '%']);
1614
+    }
1615
+
1616
+    /**
1617
+     * search for files with the name matching $query
1618
+     *
1619
+     * @param string $query
1620
+     * @return FileInfo[]
1621
+     */
1622
+    public function searchRaw($query) {
1623
+        return $this->searchCommon('search', [$query]);
1624
+    }
1625
+
1626
+    /**
1627
+     * search for files by mimetype
1628
+     *
1629
+     * @param string $mimetype
1630
+     * @return FileInfo[]
1631
+     */
1632
+    public function searchByMime($mimetype) {
1633
+        return $this->searchCommon('searchByMime', [$mimetype]);
1634
+    }
1635
+
1636
+    /**
1637
+     * search for files by tag
1638
+     *
1639
+     * @param string|int $tag name or tag id
1640
+     * @param string $userId owner of the tags
1641
+     * @return FileInfo[]
1642
+     */
1643
+    public function searchByTag($tag, $userId) {
1644
+        return $this->searchCommon('searchByTag', [$tag, $userId]);
1645
+    }
1646
+
1647
+    /**
1648
+     * @param string $method cache method
1649
+     * @param array $args
1650
+     * @return FileInfo[]
1651
+     */
1652
+    private function searchCommon($method, $args) {
1653
+        $files = [];
1654
+        $rootLength = strlen($this->fakeRoot);
1655
+
1656
+        $mount = $this->getMount('');
1657
+        $mountPoint = $mount->getMountPoint();
1658
+        $storage = $mount->getStorage();
1659
+        $userManager = \OC::$server->getUserManager();
1660
+        if ($storage) {
1661
+            $cache = $storage->getCache('');
1662
+
1663
+            $results = call_user_func_array([$cache, $method], $args);
1664
+            foreach ($results as $result) {
1665
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1666
+                    $internalPath = $result['path'];
1667
+                    $path = $mountPoint . $result['path'];
1668
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1669
+                    $owner = $userManager->get($storage->getOwner($internalPath));
1670
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1671
+                }
1672
+            }
1673
+
1674
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1675
+            foreach ($mounts as $mount) {
1676
+                $mountPoint = $mount->getMountPoint();
1677
+                $storage = $mount->getStorage();
1678
+                if ($storage) {
1679
+                    $cache = $storage->getCache('');
1680
+
1681
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1682
+                    $results = call_user_func_array([$cache, $method], $args);
1683
+                    if ($results) {
1684
+                        foreach ($results as $result) {
1685
+                            $internalPath = $result['path'];
1686
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1687
+                            $path = rtrim($mountPoint . $internalPath, '/');
1688
+                            $owner = $userManager->get($storage->getOwner($internalPath));
1689
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1690
+                        }
1691
+                    }
1692
+                }
1693
+            }
1694
+        }
1695
+        return $files;
1696
+    }
1697
+
1698
+    /**
1699
+     * Get the owner for a file or folder
1700
+     *
1701
+     * @param string $path
1702
+     * @return string the user id of the owner
1703
+     * @throws NotFoundException
1704
+     */
1705
+    public function getOwner($path) {
1706
+        $info = $this->getFileInfo($path);
1707
+        if (!$info) {
1708
+            throw new NotFoundException($path . ' not found while trying to get owner');
1709
+        }
1710
+
1711
+        if ($info->getOwner() === null) {
1712
+            throw new NotFoundException($path . ' has no owner');
1713
+        }
1714
+
1715
+        return $info->getOwner()->getUID();
1716
+    }
1717
+
1718
+    /**
1719
+     * get the ETag for a file or folder
1720
+     *
1721
+     * @param string $path
1722
+     * @return string
1723
+     */
1724
+    public function getETag($path) {
1725
+        /**
1726
+         * @var Storage\Storage $storage
1727
+         * @var string $internalPath
1728
+         */
1729
+        [$storage, $internalPath] = $this->resolvePath($path);
1730
+        if ($storage) {
1731
+            return $storage->getETag($internalPath);
1732
+        } else {
1733
+            return null;
1734
+        }
1735
+    }
1736
+
1737
+    /**
1738
+     * Get the path of a file by id, relative to the view
1739
+     *
1740
+     * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
1741
+     *
1742
+     * @param int $id
1743
+     * @param int|null $storageId
1744
+     * @return string
1745
+     * @throws NotFoundException
1746
+     */
1747
+    public function getPath($id, int $storageId = null) {
1748
+        $id = (int)$id;
1749
+        $manager = Filesystem::getMountManager();
1750
+        $mounts = $manager->findIn($this->fakeRoot);
1751
+        $mounts[] = $manager->find($this->fakeRoot);
1752
+        $mounts = array_filter($mounts);
1753
+        // reverse the array, so we start with the storage this view is in
1754
+        // which is the most likely to contain the file we're looking for
1755
+        $mounts = array_reverse($mounts);
1756
+
1757
+        // put non-shared mounts in front of the shared mount
1758
+        // this prevents unneeded recursion into shares
1759
+        usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1760
+            return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1761
+        });
1762
+
1763
+        if (!is_null($storageId)) {
1764
+            $mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1765
+                return $mount->getNumericStorageId() === $storageId;
1766
+            });
1767
+        }
1768
+
1769
+        foreach ($mounts as $mount) {
1770
+            /**
1771
+             * @var \OC\Files\Mount\MountPoint $mount
1772
+             */
1773
+            if ($mount->getStorage()) {
1774
+                $cache = $mount->getStorage()->getCache();
1775
+                $internalPath = $cache->getPathById($id);
1776
+                if (is_string($internalPath)) {
1777
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1778
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1779
+                        return $path;
1780
+                    }
1781
+                }
1782
+            }
1783
+        }
1784
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1785
+    }
1786
+
1787
+    /**
1788
+     * @param string $path
1789
+     * @throws InvalidPathException
1790
+     */
1791
+    private function assertPathLength($path) {
1792
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1793
+        // Check for the string length - performed using isset() instead of strlen()
1794
+        // because isset() is about 5x-40x faster.
1795
+        if (isset($path[$maxLen])) {
1796
+            $pathLen = strlen($path);
1797
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1798
+        }
1799
+    }
1800
+
1801
+    /**
1802
+     * check if it is allowed to move a mount point to a given target.
1803
+     * It is not allowed to move a mount point into a different mount point or
1804
+     * into an already shared folder
1805
+     *
1806
+     * @param IStorage $targetStorage
1807
+     * @param string $targetInternalPath
1808
+     * @return boolean
1809
+     */
1810
+    private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1811
+        // note: cannot use the view because the target is already locked
1812
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1813
+        if ($fileId === -1) {
1814
+            // target might not exist, need to check parent instead
1815
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1816
+        }
1817
+
1818
+        // check if any of the parents were shared by the current owner (include collections)
1819
+        $shares = Share::getItemShared(
1820
+            'folder',
1821
+            $fileId,
1822
+            \OC\Share\Constants::FORMAT_NONE,
1823
+            null,
1824
+            true
1825
+        );
1826
+
1827
+        if (count($shares) > 0) {
1828
+            $this->logger->debug(
1829
+                'It is not allowed to move one mount point into a shared folder',
1830
+                ['app' => 'files']);
1831
+            return false;
1832
+        }
1833
+
1834
+        return true;
1835
+    }
1836
+
1837
+    /**
1838
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1839
+     *
1840
+     * @param string $path
1841
+     * @return \OCP\Files\FileInfo
1842
+     */
1843
+    private function getPartFileInfo($path) {
1844
+        $mount = $this->getMount($path);
1845
+        $storage = $mount->getStorage();
1846
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1847
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1848
+        return new FileInfo(
1849
+            $this->getAbsolutePath($path),
1850
+            $storage,
1851
+            $internalPath,
1852
+            [
1853
+                'fileid' => null,
1854
+                'mimetype' => $storage->getMimeType($internalPath),
1855
+                'name' => basename($path),
1856
+                'etag' => null,
1857
+                'size' => $storage->filesize($internalPath),
1858
+                'mtime' => $storage->filemtime($internalPath),
1859
+                'encrypted' => false,
1860
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1861
+            ],
1862
+            $mount,
1863
+            $owner
1864
+        );
1865
+    }
1866
+
1867
+    /**
1868
+     * @param string $path
1869
+     * @param string $fileName
1870
+     * @throws InvalidPathException
1871
+     */
1872
+    public function verifyPath($path, $fileName) {
1873
+        try {
1874
+            /** @type \OCP\Files\Storage $storage */
1875
+            [$storage, $internalPath] = $this->resolvePath($path);
1876
+            $storage->verifyPath($internalPath, $fileName);
1877
+        } catch (ReservedWordException $ex) {
1878
+            $l = \OC::$server->getL10N('lib');
1879
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1880
+        } catch (InvalidCharacterInPathException $ex) {
1881
+            $l = \OC::$server->getL10N('lib');
1882
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1883
+        } catch (FileNameTooLongException $ex) {
1884
+            $l = \OC::$server->getL10N('lib');
1885
+            throw new InvalidPathException($l->t('File name is too long'));
1886
+        } catch (InvalidDirectoryException $ex) {
1887
+            $l = \OC::$server->getL10N('lib');
1888
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1889
+        } catch (EmptyFileNameException $ex) {
1890
+            $l = \OC::$server->getL10N('lib');
1891
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1892
+        }
1893
+    }
1894
+
1895
+    /**
1896
+     * get all parent folders of $path
1897
+     *
1898
+     * @param string $path
1899
+     * @return string[]
1900
+     */
1901
+    private function getParents($path) {
1902
+        $path = trim($path, '/');
1903
+        if (!$path) {
1904
+            return [];
1905
+        }
1906
+
1907
+        $parts = explode('/', $path);
1908
+
1909
+        // remove the single file
1910
+        array_pop($parts);
1911
+        $result = ['/'];
1912
+        $resultPath = '';
1913
+        foreach ($parts as $part) {
1914
+            if ($part) {
1915
+                $resultPath .= '/' . $part;
1916
+                $result[] = $resultPath;
1917
+            }
1918
+        }
1919
+        return $result;
1920
+    }
1921
+
1922
+    /**
1923
+     * Returns the mount point for which to lock
1924
+     *
1925
+     * @param string $absolutePath absolute path
1926
+     * @param bool $useParentMount true to return parent mount instead of whatever
1927
+     * is mounted directly on the given path, false otherwise
1928
+     * @return IMountPoint mount point for which to apply locks
1929
+     */
1930
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1931
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1932
+
1933
+        if ($useParentMount) {
1934
+            // find out if something is mounted directly on the path
1935
+            $internalPath = $mount->getInternalPath($absolutePath);
1936
+            if ($internalPath === '') {
1937
+                // resolve the parent mount instead
1938
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1939
+            }
1940
+        }
1941
+
1942
+        return $mount;
1943
+    }
1944
+
1945
+    /**
1946
+     * Lock the given path
1947
+     *
1948
+     * @param string $path the path of the file to lock, relative to the view
1949
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1950
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1951
+     *
1952
+     * @return bool False if the path is excluded from locking, true otherwise
1953
+     * @throws LockedException if the path is already locked
1954
+     */
1955
+    private function lockPath($path, $type, $lockMountPoint = false) {
1956
+        $absolutePath = $this->getAbsolutePath($path);
1957
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1958
+        if (!$this->shouldLockFile($absolutePath)) {
1959
+            return false;
1960
+        }
1961
+
1962
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1963
+        if ($mount) {
1964
+            try {
1965
+                $storage = $mount->getStorage();
1966
+                if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1967
+                    $storage->acquireLock(
1968
+                        $mount->getInternalPath($absolutePath),
1969
+                        $type,
1970
+                        $this->lockingProvider
1971
+                    );
1972
+                }
1973
+            } catch (LockedException $e) {
1974
+                // rethrow with the a human-readable path
1975
+                throw new LockedException(
1976
+                    $this->getPathRelativeToFiles($absolutePath),
1977
+                    $e,
1978
+                    $e->getExistingLock()
1979
+                );
1980
+            }
1981
+        }
1982
+
1983
+        return true;
1984
+    }
1985
+
1986
+    /**
1987
+     * Change the lock type
1988
+     *
1989
+     * @param string $path the path of the file to lock, relative to the view
1990
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1991
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1992
+     *
1993
+     * @return bool False if the path is excluded from locking, true otherwise
1994
+     * @throws LockedException if the path is already locked
1995
+     */
1996
+    public function changeLock($path, $type, $lockMountPoint = false) {
1997
+        $path = Filesystem::normalizePath($path);
1998
+        $absolutePath = $this->getAbsolutePath($path);
1999
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2000
+        if (!$this->shouldLockFile($absolutePath)) {
2001
+            return false;
2002
+        }
2003
+
2004
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2005
+        if ($mount) {
2006
+            try {
2007
+                $storage = $mount->getStorage();
2008
+                if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2009
+                    $storage->changeLock(
2010
+                        $mount->getInternalPath($absolutePath),
2011
+                        $type,
2012
+                        $this->lockingProvider
2013
+                    );
2014
+                }
2015
+            } catch (LockedException $e) {
2016
+                try {
2017
+                    // rethrow with the a human-readable path
2018
+                    throw new LockedException(
2019
+                        $this->getPathRelativeToFiles($absolutePath),
2020
+                        $e,
2021
+                        $e->getExistingLock()
2022
+                    );
2023
+                } catch (\InvalidArgumentException $ex) {
2024
+                    throw new LockedException(
2025
+                        $absolutePath,
2026
+                        $ex,
2027
+                        $e->getExistingLock()
2028
+                    );
2029
+                }
2030
+            }
2031
+        }
2032
+
2033
+        return true;
2034
+    }
2035
+
2036
+    /**
2037
+     * Unlock the given path
2038
+     *
2039
+     * @param string $path the path of the file to unlock, relative to the view
2040
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2041
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2042
+     *
2043
+     * @return bool False if the path is excluded from locking, true otherwise
2044
+     * @throws LockedException
2045
+     */
2046
+    private function unlockPath($path, $type, $lockMountPoint = false) {
2047
+        $absolutePath = $this->getAbsolutePath($path);
2048
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2049
+        if (!$this->shouldLockFile($absolutePath)) {
2050
+            return false;
2051
+        }
2052
+
2053
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2054
+        if ($mount) {
2055
+            $storage = $mount->getStorage();
2056
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2057
+                $storage->releaseLock(
2058
+                    $mount->getInternalPath($absolutePath),
2059
+                    $type,
2060
+                    $this->lockingProvider
2061
+                );
2062
+            }
2063
+        }
2064
+
2065
+        return true;
2066
+    }
2067
+
2068
+    /**
2069
+     * Lock a path and all its parents up to the root of the view
2070
+     *
2071
+     * @param string $path the path of the file to lock relative to the view
2072
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2073
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2074
+     *
2075
+     * @return bool False if the path is excluded from locking, true otherwise
2076
+     * @throws LockedException
2077
+     */
2078
+    public function lockFile($path, $type, $lockMountPoint = false) {
2079
+        $absolutePath = $this->getAbsolutePath($path);
2080
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2081
+        if (!$this->shouldLockFile($absolutePath)) {
2082
+            return false;
2083
+        }
2084
+
2085
+        $this->lockPath($path, $type, $lockMountPoint);
2086
+
2087
+        $parents = $this->getParents($path);
2088
+        foreach ($parents as $parent) {
2089
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2090
+        }
2091
+
2092
+        return true;
2093
+    }
2094
+
2095
+    /**
2096
+     * Unlock a path and all its parents up to the root of the view
2097
+     *
2098
+     * @param string $path the path of the file to lock relative to the view
2099
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2100
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2101
+     *
2102
+     * @return bool False if the path is excluded from locking, true otherwise
2103
+     * @throws LockedException
2104
+     */
2105
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2106
+        $absolutePath = $this->getAbsolutePath($path);
2107
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2108
+        if (!$this->shouldLockFile($absolutePath)) {
2109
+            return false;
2110
+        }
2111
+
2112
+        $this->unlockPath($path, $type, $lockMountPoint);
2113
+
2114
+        $parents = $this->getParents($path);
2115
+        foreach ($parents as $parent) {
2116
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2117
+        }
2118
+
2119
+        return true;
2120
+    }
2121
+
2122
+    /**
2123
+     * Only lock files in data/user/files/
2124
+     *
2125
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2126
+     * @return bool
2127
+     */
2128
+    protected function shouldLockFile($path) {
2129
+        $path = Filesystem::normalizePath($path);
2130
+
2131
+        $pathSegments = explode('/', $path);
2132
+        if (isset($pathSegments[2])) {
2133
+            // E.g.: /username/files/path-to-file
2134
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2135
+        }
2136
+
2137
+        return strpos($path, '/appdata_') !== 0;
2138
+    }
2139
+
2140
+    /**
2141
+     * Shortens the given absolute path to be relative to
2142
+     * "$user/files".
2143
+     *
2144
+     * @param string $absolutePath absolute path which is under "files"
2145
+     *
2146
+     * @return string path relative to "files" with trimmed slashes or null
2147
+     * if the path was NOT relative to files
2148
+     *
2149
+     * @throws \InvalidArgumentException if the given path was not under "files"
2150
+     * @since 8.1.0
2151
+     */
2152
+    public function getPathRelativeToFiles($absolutePath) {
2153
+        $path = Filesystem::normalizePath($absolutePath);
2154
+        $parts = explode('/', trim($path, '/'), 3);
2155
+        // "$user", "files", "path/to/dir"
2156
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2157
+            $this->logger->error(
2158
+                '$absolutePath must be relative to "files", value is "{absolutePath}"',
2159
+                [
2160
+                    'absolutePath' => $absolutePath,
2161
+                ]
2162
+            );
2163
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2164
+        }
2165
+        if (isset($parts[2])) {
2166
+            return $parts[2];
2167
+        }
2168
+        return '';
2169
+    }
2170
+
2171
+    /**
2172
+     * @param string $filename
2173
+     * @return array
2174
+     * @throws \OC\User\NoUserException
2175
+     * @throws NotFoundException
2176
+     */
2177
+    public function getUidAndFilename($filename) {
2178
+        $info = $this->getFileInfo($filename);
2179
+        if (!$info instanceof \OCP\Files\FileInfo) {
2180
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2181
+        }
2182
+        $uid = $info->getOwner()->getUID();
2183
+        if ($uid != \OC_User::getUser()) {
2184
+            Filesystem::initMountPoints($uid);
2185
+            $ownerView = new View('/' . $uid . '/files');
2186
+            try {
2187
+                $filename = $ownerView->getPath($info['fileid']);
2188
+            } catch (NotFoundException $e) {
2189
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2190
+            }
2191
+        }
2192
+        return [$uid, $filename];
2193
+    }
2194
+
2195
+    /**
2196
+     * Creates parent non-existing folders
2197
+     *
2198
+     * @param string $filePath
2199
+     * @return bool
2200
+     */
2201
+    private function createParentDirectories($filePath) {
2202
+        $directoryParts = explode('/', $filePath);
2203
+        $directoryParts = array_filter($directoryParts);
2204
+        foreach ($directoryParts as $key => $part) {
2205
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2206
+            $currentPath = '/' . implode('/', $currentPathElements);
2207
+            if ($this->is_file($currentPath)) {
2208
+                return false;
2209
+            }
2210
+            if (!$this->file_exists($currentPath)) {
2211
+                $this->mkdir($currentPath);
2212
+            }
2213
+        }
2214
+
2215
+        return true;
2216
+    }
2217 2217
 }
Please login to merge, or discard this patch.