Passed
Push — master ( a2c262...a3d30b )
by Blizzz
11:21 queued 12s
created
apps/files_trashbin/lib/AppInfo/Application.php 2 patches
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -41,61 +41,61 @@
 block discarded – undo
41 41
 use OCP\IServerContainer;
42 42
 
43 43
 class Application extends App implements IBootstrap {
44
-	public function __construct(array $urlParams = []) {
45
-		parent::__construct('files_trashbin', $urlParams);
46
-	}
44
+    public function __construct(array $urlParams = []) {
45
+        parent::__construct('files_trashbin', $urlParams);
46
+    }
47 47
 
48
-	public function register(IRegistrationContext $context): void {
49
-		$context->registerCapability(Capabilities::class);
48
+    public function register(IRegistrationContext $context): void {
49
+        $context->registerCapability(Capabilities::class);
50 50
 
51
-		$context->registerServiceAlias('Expiration', Expiration::class);
52
-		$context->registerServiceAlias(ITrashManager::class, TrashManager::class);
53
-		/** Register $principalBackend for the DAV collection */
54
-		$context->registerServiceAlias('principalBackend', Principal::class);
55
-	}
51
+        $context->registerServiceAlias('Expiration', Expiration::class);
52
+        $context->registerServiceAlias(ITrashManager::class, TrashManager::class);
53
+        /** Register $principalBackend for the DAV collection */
54
+        $context->registerServiceAlias('principalBackend', Principal::class);
55
+    }
56 56
 
57
-	public function boot(IBootContext $context): void {
58
-		$context->injectFn([$this, 'registerTrashBackends']);
57
+    public function boot(IBootContext $context): void {
58
+        $context->injectFn([$this, 'registerTrashBackends']);
59 59
 
60
-		// create storage wrapper on setup
61
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage');
62
-		//Listen to delete user signal
63
-		\OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook');
64
-		//Listen to post write hook
65
-		\OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook');
66
-		// pre and post-rename, disable trash logic for the copy+unlink case
67
-		\OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook');
60
+        // create storage wrapper on setup
61
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage');
62
+        //Listen to delete user signal
63
+        \OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook');
64
+        //Listen to post write hook
65
+        \OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook');
66
+        // pre and post-rename, disable trash logic for the copy+unlink case
67
+        \OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook');
68 68
 
69
-		\OCA\Files\App::getNavigationManager()->add(function () {
70
-			$l = \OC::$server->getL10N('files_trashbin');
71
-			return [
72
-				'id' => 'trashbin',
73
-				'appname' => 'files_trashbin',
74
-				'script' => 'list.php',
75
-				'order' => 50,
76
-				'name' => $l->t('Deleted files'),
77
-				'classes' => 'pinned',
78
-			];
79
-		});
80
-	}
69
+        \OCA\Files\App::getNavigationManager()->add(function () {
70
+            $l = \OC::$server->getL10N('files_trashbin');
71
+            return [
72
+                'id' => 'trashbin',
73
+                'appname' => 'files_trashbin',
74
+                'script' => 'list.php',
75
+                'order' => 50,
76
+                'name' => $l->t('Deleted files'),
77
+                'classes' => 'pinned',
78
+            ];
79
+        });
80
+    }
81 81
 
82
-	public function registerTrashBackends(IServerContainer $serverContainer, ILogger $logger, IAppManager $appManager, ITrashManager $trashManager) {
83
-		foreach ($appManager->getInstalledApps() as $app) {
84
-			$appInfo = $appManager->getAppInfo($app);
85
-			if (isset($appInfo['trash'])) {
86
-				$backends = $appInfo['trash'];
87
-				foreach ($backends as $backend) {
88
-					$class = $backend['@value'];
89
-					$for = $backend['@attributes']['for'];
82
+    public function registerTrashBackends(IServerContainer $serverContainer, ILogger $logger, IAppManager $appManager, ITrashManager $trashManager) {
83
+        foreach ($appManager->getInstalledApps() as $app) {
84
+            $appInfo = $appManager->getAppInfo($app);
85
+            if (isset($appInfo['trash'])) {
86
+                $backends = $appInfo['trash'];
87
+                foreach ($backends as $backend) {
88
+                    $class = $backend['@value'];
89
+                    $for = $backend['@attributes']['for'];
90 90
 
91
-					try {
92
-						$backendObject = $serverContainer->query($class);
93
-						$trashManager->registerBackend($for, $backendObject);
94
-					} catch (\Exception $e) {
95
-						$logger->logException($e);
96
-					}
97
-				}
98
-			}
99
-		}
100
-	}
91
+                    try {
92
+                        $backendObject = $serverContainer->query($class);
93
+                        $trashManager->registerBackend($for, $backendObject);
94
+                    } catch (\Exception $e) {
95
+                        $logger->logException($e);
96
+                    }
97
+                }
98
+            }
99
+        }
100
+    }
101 101
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -66,7 +66,7 @@
 block discarded – undo
66 66
 		// pre and post-rename, disable trash logic for the copy+unlink case
67 67
 		\OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook');
68 68
 
69
-		\OCA\Files\App::getNavigationManager()->add(function () {
69
+		\OCA\Files\App::getNavigationManager()->add(function() {
70 70
 			$l = \OC::$server->getL10N('files_trashbin');
71 71
 			return [
72 72
 				'id' => 'trashbin',
Please login to merge, or discard this patch.
apps/files_trashbin/lib/Trashbin.php 1 patch
Indentation   +986 added lines, -986 removed lines patch added patch discarded remove patch
@@ -59,990 +59,990 @@
 block discarded – undo
59 59
 
60 60
 class Trashbin {
61 61
 
62
-	// unit: percentage; 50% of available disk space/quota
63
-	public const DEFAULTMAXSIZE = 50;
64
-
65
-	/**
66
-	 * Whether versions have already be rescanned during this PHP request
67
-	 *
68
-	 * @var bool
69
-	 */
70
-	private static $scannedVersions = false;
71
-
72
-	/**
73
-	 * Ensure we don't need to scan the file during the move to trash
74
-	 * by triggering the scan in the pre-hook
75
-	 *
76
-	 * @param array $params
77
-	 */
78
-	public static function ensureFileScannedHook($params) {
79
-		try {
80
-			self::getUidAndFilename($params['path']);
81
-		} catch (NotFoundException $e) {
82
-			// nothing to scan for non existing files
83
-		}
84
-	}
85
-
86
-	/**
87
-	 * get the UID of the owner of the file and the path to the file relative to
88
-	 * owners files folder
89
-	 *
90
-	 * @param string $filename
91
-	 * @return array
92
-	 * @throws \OC\User\NoUserException
93
-	 */
94
-	public static function getUidAndFilename($filename) {
95
-		$uid = Filesystem::getOwner($filename);
96
-		$userManager = \OC::$server->getUserManager();
97
-		// if the user with the UID doesn't exists, e.g. because the UID points
98
-		// to a remote user with a federated cloud ID we use the current logged-in
99
-		// user. We need a valid local user to move the file to the right trash bin
100
-		if (!$userManager->userExists($uid)) {
101
-			$uid = User::getUser();
102
-		}
103
-		if (!$uid) {
104
-			// no owner, usually because of share link from ext storage
105
-			return [null, null];
106
-		}
107
-		Filesystem::initMountPoints($uid);
108
-		if ($uid !== User::getUser()) {
109
-			$info = Filesystem::getFileInfo($filename);
110
-			$ownerView = new View('/' . $uid . '/files');
111
-			try {
112
-				$filename = $ownerView->getPath($info['fileid']);
113
-			} catch (NotFoundException $e) {
114
-				$filename = null;
115
-			}
116
-		}
117
-		return [$uid, $filename];
118
-	}
119
-
120
-	/**
121
-	 * get original location of files for user
122
-	 *
123
-	 * @param string $user
124
-	 * @return array (filename => array (timestamp => original location))
125
-	 */
126
-	public static function getLocations($user) {
127
-		$query = \OC_DB::prepare('SELECT `id`, `timestamp`, `location`'
128
-			. ' FROM `*PREFIX*files_trash` WHERE `user`=?');
129
-		$result = $query->execute([$user]);
130
-		$array = [];
131
-		while ($row = $result->fetchRow()) {
132
-			if (isset($array[$row['id']])) {
133
-				$array[$row['id']][$row['timestamp']] = $row['location'];
134
-			} else {
135
-				$array[$row['id']] = [$row['timestamp'] => $row['location']];
136
-			}
137
-		}
138
-		return $array;
139
-	}
140
-
141
-	/**
142
-	 * get original location of file
143
-	 *
144
-	 * @param string $user
145
-	 * @param string $filename
146
-	 * @param string $timestamp
147
-	 * @return string original location
148
-	 */
149
-	public static function getLocation($user, $filename, $timestamp) {
150
-		$query = \OC_DB::prepare('SELECT `location` FROM `*PREFIX*files_trash`'
151
-			. ' WHERE `user`=? AND `id`=? AND `timestamp`=?');
152
-		$result = $query->execute([$user, $filename, $timestamp])->fetchAll();
153
-		if (isset($result[0]['location'])) {
154
-			return $result[0]['location'];
155
-		} else {
156
-			return false;
157
-		}
158
-	}
159
-
160
-	private static function setUpTrash($user) {
161
-		$view = new View('/' . $user);
162
-		if (!$view->is_dir('files_trashbin')) {
163
-			$view->mkdir('files_trashbin');
164
-		}
165
-		if (!$view->is_dir('files_trashbin/files')) {
166
-			$view->mkdir('files_trashbin/files');
167
-		}
168
-		if (!$view->is_dir('files_trashbin/versions')) {
169
-			$view->mkdir('files_trashbin/versions');
170
-		}
171
-		if (!$view->is_dir('files_trashbin/keys')) {
172
-			$view->mkdir('files_trashbin/keys');
173
-		}
174
-	}
175
-
176
-
177
-	/**
178
-	 * copy file to owners trash
179
-	 *
180
-	 * @param string $sourcePath
181
-	 * @param string $owner
182
-	 * @param string $targetPath
183
-	 * @param $user
184
-	 * @param integer $timestamp
185
-	 */
186
-	private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) {
187
-		self::setUpTrash($owner);
188
-
189
-		$targetFilename = basename($targetPath);
190
-		$targetLocation = dirname($targetPath);
191
-
192
-		$sourceFilename = basename($sourcePath);
193
-
194
-		$view = new View('/');
195
-
196
-		$target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
197
-		$source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
198
-		$free = $view->free_space($target);
199
-		$isUnknownOrUnlimitedFreeSpace = $free < 0;
200
-		$isEnoughFreeSpaceLeft = $view->filesize($source) < $free;
201
-		if ($isUnknownOrUnlimitedFreeSpace || $isEnoughFreeSpaceLeft) {
202
-			self::copy_recursive($source, $target, $view);
203
-		}
204
-
205
-
206
-		if ($view->file_exists($target)) {
207
-			$query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
208
-			$result = $query->execute([$targetFilename, $timestamp, $targetLocation, $user]);
209
-			if (!$result) {
210
-				\OC::$server->getLogger()->error('trash bin database couldn\'t be updated for the files owner', ['app' => 'files_trashbin']);
211
-			}
212
-		}
213
-	}
214
-
215
-
216
-	/**
217
-	 * move file to the trash bin
218
-	 *
219
-	 * @param string $file_path path to the deleted file/directory relative to the files root directory
220
-	 * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
221
-	 *
222
-	 * @return bool
223
-	 */
224
-	public static function move2trash($file_path, $ownerOnly = false) {
225
-		// get the user for which the filesystem is setup
226
-		$root = Filesystem::getRoot();
227
-		[, $user] = explode('/', $root);
228
-		[$owner, $ownerPath] = self::getUidAndFilename($file_path);
229
-
230
-		// if no owner found (ex: ext storage + share link), will use the current user's trashbin then
231
-		if (is_null($owner)) {
232
-			$owner = $user;
233
-			$ownerPath = $file_path;
234
-		}
235
-
236
-		$ownerView = new View('/' . $owner);
237
-		// file has been deleted in between
238
-		if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) {
239
-			return true;
240
-		}
241
-
242
-		self::setUpTrash($user);
243
-		if ($owner !== $user) {
244
-			// also setup for owner
245
-			self::setUpTrash($owner);
246
-		}
247
-
248
-		$path_parts = pathinfo($ownerPath);
249
-
250
-		$filename = $path_parts['basename'];
251
-		$location = $path_parts['dirname'];
252
-		/** @var ITimeFactory $timeFactory */
253
-		$timeFactory = \OC::$server->query(ITimeFactory::class);
254
-		$timestamp = $timeFactory->getTime();
255
-
256
-		$lockingProvider = \OC::$server->getLockingProvider();
257
-
258
-		// disable proxy to prevent recursive calls
259
-		$trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
260
-		$gotLock = false;
261
-
262
-		while (!$gotLock) {
263
-			try {
264
-				/** @var \OC\Files\Storage\Storage $trashStorage */
265
-				[$trashStorage, $trashInternalPath] = $ownerView->resolvePath($trashPath);
266
-
267
-				$trashStorage->acquireLock($trashInternalPath, ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
268
-				$gotLock = true;
269
-			} catch (LockedException $e) {
270
-				// a file with the same name is being deleted concurrently
271
-				// nudge the timestamp a bit to resolve the conflict
272
-
273
-				$timestamp = $timestamp + 1;
274
-
275
-				$trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
276
-			}
277
-		}
278
-
279
-		/** @var \OC\Files\Storage\Storage $sourceStorage */
280
-		[$sourceStorage, $sourceInternalPath] = $ownerView->resolvePath('/files/' . $ownerPath);
281
-
282
-
283
-		if ($trashStorage->file_exists($trashInternalPath)) {
284
-			$trashStorage->unlink($trashInternalPath);
285
-		}
286
-
287
-		$connection = \OC::$server->getDatabaseConnection();
288
-		$connection->beginTransaction();
289
-		$trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
290
-
291
-		try {
292
-			$moveSuccessful = true;
293
-
294
-			// when moving within the same object store, the cache update done above is enough to move the file
295
-			if (!($trashStorage->instanceOfStorage(ObjectStoreStorage::class) && $trashStorage->getId() === $sourceStorage->getId())) {
296
-				$trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
297
-			}
298
-		} catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) {
299
-			$moveSuccessful = false;
300
-			if ($trashStorage->file_exists($trashInternalPath)) {
301
-				$trashStorage->unlink($trashInternalPath);
302
-			}
303
-			\OC::$server->getLogger()->error('Couldn\'t move ' . $file_path . ' to the trash bin', ['app' => 'files_trashbin']);
304
-		}
305
-
306
-		if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
307
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
308
-				$sourceStorage->rmdir($sourceInternalPath);
309
-			} else {
310
-				$sourceStorage->unlink($sourceInternalPath);
311
-			}
312
-			$connection->rollBack();
313
-			return false;
314
-		}
315
-
316
-		$connection->commit();
317
-
318
-		if ($moveSuccessful) {
319
-			$query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
320
-			$result = $query->execute([$filename, $timestamp, $location, $owner]);
321
-			if (!$result) {
322
-				\OC::$server->getLogger()->error('trash bin database couldn\'t be updated', ['app' => 'files_trashbin']);
323
-			}
324
-			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', ['filePath' => Filesystem::normalizePath($file_path),
325
-				'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)]);
326
-
327
-			self::retainVersions($filename, $owner, $ownerPath, $timestamp);
328
-
329
-			// if owner !== user we need to also add a copy to the users trash
330
-			if ($user !== $owner && $ownerOnly === false) {
331
-				self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp);
332
-			}
333
-		}
334
-
335
-		$trashStorage->releaseLock($trashInternalPath, ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
336
-
337
-		self::scheduleExpire($user);
338
-
339
-		// if owner !== user we also need to update the owners trash size
340
-		if ($owner !== $user) {
341
-			self::scheduleExpire($owner);
342
-		}
343
-
344
-		return $moveSuccessful;
345
-	}
346
-
347
-	/**
348
-	 * Move file versions to trash so that they can be restored later
349
-	 *
350
-	 * @param string $filename of deleted file
351
-	 * @param string $owner owner user id
352
-	 * @param string $ownerPath path relative to the owner's home storage
353
-	 * @param integer $timestamp when the file was deleted
354
-	 */
355
-	private static function retainVersions($filename, $owner, $ownerPath, $timestamp) {
356
-		if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) {
357
-			$user = User::getUser();
358
-			$rootView = new View('/');
359
-
360
-			if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
361
-				if ($owner !== $user) {
362
-					self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView);
363
-				}
364
-				self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
365
-			} elseif ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
366
-				foreach ($versions as $v) {
367
-					if ($owner !== $user) {
368
-						self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp);
369
-					}
370
-					self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
371
-				}
372
-			}
373
-		}
374
-	}
375
-
376
-	/**
377
-	 * Move a file or folder on storage level
378
-	 *
379
-	 * @param View $view
380
-	 * @param string $source
381
-	 * @param string $target
382
-	 * @return bool
383
-	 */
384
-	private static function move(View $view, $source, $target) {
385
-		/** @var \OC\Files\Storage\Storage $sourceStorage */
386
-		[$sourceStorage, $sourceInternalPath] = $view->resolvePath($source);
387
-		/** @var \OC\Files\Storage\Storage $targetStorage */
388
-		[$targetStorage, $targetInternalPath] = $view->resolvePath($target);
389
-		/** @var \OC\Files\Storage\Storage $ownerTrashStorage */
390
-
391
-		$result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
392
-		if ($result) {
393
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
394
-		}
395
-		return $result;
396
-	}
397
-
398
-	/**
399
-	 * Copy a file or folder on storage level
400
-	 *
401
-	 * @param View $view
402
-	 * @param string $source
403
-	 * @param string $target
404
-	 * @return bool
405
-	 */
406
-	private static function copy(View $view, $source, $target) {
407
-		/** @var \OC\Files\Storage\Storage $sourceStorage */
408
-		[$sourceStorage, $sourceInternalPath] = $view->resolvePath($source);
409
-		/** @var \OC\Files\Storage\Storage $targetStorage */
410
-		[$targetStorage, $targetInternalPath] = $view->resolvePath($target);
411
-		/** @var \OC\Files\Storage\Storage $ownerTrashStorage */
412
-
413
-		$result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
414
-		if ($result) {
415
-			$targetStorage->getUpdater()->update($targetInternalPath);
416
-		}
417
-		return $result;
418
-	}
419
-
420
-	/**
421
-	 * Restore a file or folder from trash bin
422
-	 *
423
-	 * @param string $file path to the deleted file/folder relative to "files_trashbin/files/",
424
-	 * including the timestamp suffix ".d12345678"
425
-	 * @param string $filename name of the file/folder
426
-	 * @param int $timestamp time when the file/folder was deleted
427
-	 *
428
-	 * @return bool true on success, false otherwise
429
-	 */
430
-	public static function restore($file, $filename, $timestamp) {
431
-		$user = User::getUser();
432
-		$view = new View('/' . $user);
433
-
434
-		$location = '';
435
-		if ($timestamp) {
436
-			$location = self::getLocation($user, $filename, $timestamp);
437
-			if ($location === false) {
438
-				\OC::$server->getLogger()->error('trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']);
439
-			} else {
440
-				// if location no longer exists, restore file in the root directory
441
-				if ($location !== '/' &&
442
-					(!$view->is_dir('files/' . $location) ||
443
-						!$view->isCreatable('files/' . $location))
444
-				) {
445
-					$location = '';
446
-				}
447
-			}
448
-		}
449
-
450
-		// we need a  extension in case a file/dir with the same name already exists
451
-		$uniqueFilename = self::getUniqueFilename($location, $filename, $view);
452
-
453
-		$source = Filesystem::normalizePath('files_trashbin/files/' . $file);
454
-		$target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
455
-		if (!$view->file_exists($source)) {
456
-			return false;
457
-		}
458
-		$mtime = $view->filemtime($source);
459
-
460
-		// restore file
461
-		if (!$view->isCreatable(dirname($target))) {
462
-			throw new NotPermittedException("Can't restore trash item because the target folder is not writable");
463
-		}
464
-		$restoreResult = $view->rename($source, $target);
465
-
466
-		// handle the restore result
467
-		if ($restoreResult) {
468
-			$fakeRoot = $view->getRoot();
469
-			$view->chroot('/' . $user . '/files');
470
-			$view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
471
-			$view->chroot($fakeRoot);
472
-			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', ['filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
473
-				'trashPath' => Filesystem::normalizePath($file)]);
474
-
475
-			self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
476
-
477
-			if ($timestamp) {
478
-				$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
479
-				$query->execute([$user, $filename, $timestamp]);
480
-			}
481
-
482
-			return true;
483
-		}
484
-
485
-		return false;
486
-	}
487
-
488
-	/**
489
-	 * restore versions from trash bin
490
-	 *
491
-	 * @param View $view file view
492
-	 * @param string $file complete path to file
493
-	 * @param string $filename name of file once it was deleted
494
-	 * @param string $uniqueFilename new file name to restore the file without overwriting existing files
495
-	 * @param string $location location if file
496
-	 * @param int $timestamp deletion time
497
-	 * @return false|null
498
-	 */
499
-	private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) {
500
-		if (\OCP\App::isEnabled('files_versions')) {
501
-			$user = User::getUser();
502
-			$rootView = new View('/');
503
-
504
-			$target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
505
-
506
-			[$owner, $ownerPath] = self::getUidAndFilename($target);
507
-
508
-			// file has been deleted in between
509
-			if (empty($ownerPath)) {
510
-				return false;
511
-			}
512
-
513
-			if ($timestamp) {
514
-				$versionedFile = $filename;
515
-			} else {
516
-				$versionedFile = $file;
517
-			}
518
-
519
-			if ($view->is_dir('/files_trashbin/versions/' . $file)) {
520
-				$rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
521
-			} elseif ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
522
-				foreach ($versions as $v) {
523
-					if ($timestamp) {
524
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
525
-					} else {
526
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
527
-					}
528
-				}
529
-			}
530
-		}
531
-	}
532
-
533
-	/**
534
-	 * delete all files from the trash
535
-	 */
536
-	public static function deleteAll() {
537
-		$user = User::getUser();
538
-		$userRoot = \OC::$server->getUserFolder($user)->getParent();
539
-		$view = new View('/' . $user);
540
-		$fileInfos = $view->getDirectoryContent('files_trashbin/files');
541
-
542
-		try {
543
-			$trash = $userRoot->get('files_trashbin');
544
-		} catch (NotFoundException $e) {
545
-			return false;
546
-		}
547
-
548
-		// Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
549
-		$filePaths = [];
550
-		foreach ($fileInfos as $fileInfo) {
551
-			$filePaths[] = $view->getRelativePath($fileInfo->getPath());
552
-		}
553
-		unset($fileInfos); // save memory
554
-
555
-		// Bulk PreDelete-Hook
556
-		\OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', ['paths' => $filePaths]);
557
-
558
-		// Single-File Hooks
559
-		foreach ($filePaths as $path) {
560
-			self::emitTrashbinPreDelete($path);
561
-		}
562
-
563
-		// actual file deletion
564
-		$trash->delete();
565
-		$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
566
-		$query->execute([$user]);
567
-
568
-		// Bulk PostDelete-Hook
569
-		\OC_Hook::emit('\OCP\Trashbin', 'deleteAll', ['paths' => $filePaths]);
570
-
571
-		// Single-File Hooks
572
-		foreach ($filePaths as $path) {
573
-			self::emitTrashbinPostDelete($path);
574
-		}
575
-
576
-		$trash = $userRoot->newFolder('files_trashbin');
577
-		$trash->newFolder('files');
578
-
579
-		return true;
580
-	}
581
-
582
-	/**
583
-	 * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
584
-	 *
585
-	 * @param string $path
586
-	 */
587
-	protected static function emitTrashbinPreDelete($path) {
588
-		\OC_Hook::emit('\OCP\Trashbin', 'preDelete', ['path' => $path]);
589
-	}
590
-
591
-	/**
592
-	 * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
593
-	 *
594
-	 * @param string $path
595
-	 */
596
-	protected static function emitTrashbinPostDelete($path) {
597
-		\OC_Hook::emit('\OCP\Trashbin', 'delete', ['path' => $path]);
598
-	}
599
-
600
-	/**
601
-	 * delete file from trash bin permanently
602
-	 *
603
-	 * @param string $filename path to the file
604
-	 * @param string $user
605
-	 * @param int $timestamp of deletion time
606
-	 *
607
-	 * @return int size of deleted files
608
-	 */
609
-	public static function delete($filename, $user, $timestamp = null) {
610
-		$userRoot = \OC::$server->getUserFolder($user)->getParent();
611
-		$view = new View('/' . $user);
612
-		$size = 0;
613
-
614
-		if ($timestamp) {
615
-			$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
616
-			$query->execute([$user, $filename, $timestamp]);
617
-			$file = $filename . '.d' . $timestamp;
618
-		} else {
619
-			$file = $filename;
620
-		}
621
-
622
-		$size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
623
-
624
-		try {
625
-			$node = $userRoot->get('/files_trashbin/files/' . $file);
626
-		} catch (NotFoundException $e) {
627
-			return $size;
628
-		}
629
-
630
-		if ($node instanceof Folder) {
631
-			$size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
632
-		} elseif ($node instanceof File) {
633
-			$size += $view->filesize('/files_trashbin/files/' . $file);
634
-		}
635
-
636
-		self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
637
-		$node->delete();
638
-		self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
639
-
640
-		return $size;
641
-	}
642
-
643
-	/**
644
-	 * @param View $view
645
-	 * @param string $file
646
-	 * @param string $filename
647
-	 * @param integer|null $timestamp
648
-	 * @param string $user
649
-	 * @return int
650
-	 */
651
-	private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
652
-		$size = 0;
653
-		if (\OCP\App::isEnabled('files_versions')) {
654
-			if ($view->is_dir('files_trashbin/versions/' . $file)) {
655
-				$size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
656
-				$view->unlink('files_trashbin/versions/' . $file);
657
-			} elseif ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
658
-				foreach ($versions as $v) {
659
-					if ($timestamp) {
660
-						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
661
-						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
662
-					} else {
663
-						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
664
-						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
665
-					}
666
-				}
667
-			}
668
-		}
669
-		return $size;
670
-	}
671
-
672
-	/**
673
-	 * check to see whether a file exists in trashbin
674
-	 *
675
-	 * @param string $filename path to the file
676
-	 * @param int $timestamp of deletion time
677
-	 * @return bool true if file exists, otherwise false
678
-	 */
679
-	public static function file_exists($filename, $timestamp = null) {
680
-		$user = User::getUser();
681
-		$view = new View('/' . $user);
682
-
683
-		if ($timestamp) {
684
-			$filename = $filename . '.d' . $timestamp;
685
-		}
686
-
687
-		$target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
688
-		return $view->file_exists($target);
689
-	}
690
-
691
-	/**
692
-	 * deletes used space for trash bin in db if user was deleted
693
-	 *
694
-	 * @param string $uid id of deleted user
695
-	 * @return bool result of db delete operation
696
-	 */
697
-	public static function deleteUser($uid) {
698
-		$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
699
-		return $query->execute([$uid]);
700
-	}
701
-
702
-	/**
703
-	 * calculate remaining free space for trash bin
704
-	 *
705
-	 * @param integer $trashbinSize current size of the trash bin
706
-	 * @param string $user
707
-	 * @return int available free space for trash bin
708
-	 */
709
-	private static function calculateFreeSpace($trashbinSize, $user) {
710
-		$config = \OC::$server->getConfig();
711
-		$systemTrashbinSize = (int)$config->getAppValue('files_trashbin', 'trashbin_size', '-1');
712
-		$userTrashbinSize = (int)$config->getUserValue($user, 'files_trashbin', 'trashbin_size', '-1');
713
-		$configuredTrashbinSize = ($userTrashbinSize < 0) ? $systemTrashbinSize : $userTrashbinSize;
714
-		if ($configuredTrashbinSize) {
715
-			return $configuredTrashbinSize - $trashbinSize;
716
-		}
717
-
718
-		$softQuota = true;
719
-		$userObject = \OC::$server->getUserManager()->get($user);
720
-		if (is_null($userObject)) {
721
-			return 0;
722
-		}
723
-		$quota = $userObject->getQuota();
724
-		if ($quota === null || $quota === 'none') {
725
-			$quota = Filesystem::free_space('/');
726
-			$softQuota = false;
727
-			// inf or unknown free space
728
-			if ($quota < 0) {
729
-				$quota = PHP_INT_MAX;
730
-			}
731
-		} else {
732
-			$quota = \OCP\Util::computerFileSize($quota);
733
-		}
734
-
735
-		// calculate available space for trash bin
736
-		// subtract size of files and current trash bin size from quota
737
-		if ($softQuota) {
738
-			$userFolder = \OC::$server->getUserFolder($user);
739
-			if (is_null($userFolder)) {
740
-				return 0;
741
-			}
742
-			$free = $quota - $userFolder->getSize(false); // remaining free space for user
743
-			if ($free > 0) {
744
-				$availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
745
-			} else {
746
-				$availableSpace = $free - $trashbinSize;
747
-			}
748
-		} else {
749
-			$availableSpace = $quota;
750
-		}
751
-
752
-		return $availableSpace;
753
-	}
754
-
755
-	/**
756
-	 * resize trash bin if necessary after a new file was added to Nextcloud
757
-	 *
758
-	 * @param string $user user id
759
-	 */
760
-	public static function resizeTrash($user) {
761
-		$size = self::getTrashbinSize($user);
762
-
763
-		$freeSpace = self::calculateFreeSpace($size, $user);
764
-
765
-		if ($freeSpace < 0) {
766
-			self::scheduleExpire($user);
767
-		}
768
-	}
769
-
770
-	/**
771
-	 * clean up the trash bin
772
-	 *
773
-	 * @param string $user
774
-	 */
775
-	public static function expire($user) {
776
-		$trashBinSize = self::getTrashbinSize($user);
777
-		$availableSpace = self::calculateFreeSpace($trashBinSize, $user);
778
-
779
-		$dirContent = Helper::getTrashFiles('/', $user, 'mtime');
780
-
781
-		// delete all files older then $retention_obligation
782
-		[$delSize, $count] = self::deleteExpiredFiles($dirContent, $user);
783
-
784
-		$availableSpace += $delSize;
785
-
786
-		// delete files from trash until we meet the trash bin size limit again
787
-		self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
788
-	}
789
-
790
-	/**
791
-	 * @param string $user
792
-	 */
793
-	private static function scheduleExpire($user) {
794
-		// let the admin disable auto expire
795
-		/** @var Application $application */
796
-		$application = \OC::$server->query(Application::class);
797
-		$expiration = $application->getContainer()->query('Expiration');
798
-		if ($expiration->isEnabled()) {
799
-			\OC::$server->getCommandBus()->push(new Expire($user));
800
-		}
801
-	}
802
-
803
-	/**
804
-	 * if the size limit for the trash bin is reached, we delete the oldest
805
-	 * files in the trash bin until we meet the limit again
806
-	 *
807
-	 * @param array $files
808
-	 * @param string $user
809
-	 * @param int $availableSpace available disc space
810
-	 * @return int size of deleted files
811
-	 */
812
-	protected static function deleteFiles($files, $user, $availableSpace) {
813
-		/** @var Application $application */
814
-		$application = \OC::$server->query(Application::class);
815
-		$expiration = $application->getContainer()->query('Expiration');
816
-		$size = 0;
817
-
818
-		if ($availableSpace < 0) {
819
-			foreach ($files as $file) {
820
-				if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
821
-					$tmp = self::delete($file['name'], $user, $file['mtime']);
822
-					\OC::$server->getLogger()->info('remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', ['app' => 'files_trashbin']);
823
-					$availableSpace += $tmp;
824
-					$size += $tmp;
825
-				} else {
826
-					break;
827
-				}
828
-			}
829
-		}
830
-		return $size;
831
-	}
832
-
833
-	/**
834
-	 * delete files older then max storage time
835
-	 *
836
-	 * @param array $files list of files sorted by mtime
837
-	 * @param string $user
838
-	 * @return integer[] size of deleted files and number of deleted files
839
-	 */
840
-	public static function deleteExpiredFiles($files, $user) {
841
-		/** @var Expiration $expiration */
842
-		$expiration = \OC::$server->query(Expiration::class);
843
-		$size = 0;
844
-		$count = 0;
845
-		foreach ($files as $file) {
846
-			$timestamp = $file['mtime'];
847
-			$filename = $file['name'];
848
-			if ($expiration->isExpired($timestamp)) {
849
-				try {
850
-					$size += self::delete($filename, $user, $timestamp);
851
-					$count++;
852
-				} catch (\OCP\Files\NotPermittedException $e) {
853
-					\OC::$server->getLogger()->logException($e, ['app' => 'files_trashbin', 'level' => \OCP\ILogger::WARN, 'message' => 'Removing "' . $filename . '" from trashbin failed.']);
854
-				}
855
-				\OC::$server->getLogger()->info(
856
-					'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
857
-					['app' => 'files_trashbin']
858
-				);
859
-			} else {
860
-				break;
861
-			}
862
-		}
863
-
864
-		return [$size, $count];
865
-	}
866
-
867
-	/**
868
-	 * recursive copy to copy a whole directory
869
-	 *
870
-	 * @param string $source source path, relative to the users files directory
871
-	 * @param string $destination destination path relative to the users root directoy
872
-	 * @param View $view file view for the users root directory
873
-	 * @return int
874
-	 * @throws Exceptions\CopyRecursiveException
875
-	 */
876
-	private static function copy_recursive($source, $destination, View $view) {
877
-		$size = 0;
878
-		if ($view->is_dir($source)) {
879
-			$view->mkdir($destination);
880
-			$view->touch($destination, $view->filemtime($source));
881
-			foreach ($view->getDirectoryContent($source) as $i) {
882
-				$pathDir = $source . '/' . $i['name'];
883
-				if ($view->is_dir($pathDir)) {
884
-					$size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
885
-				} else {
886
-					$size += $view->filesize($pathDir);
887
-					$result = $view->copy($pathDir, $destination . '/' . $i['name']);
888
-					if (!$result) {
889
-						throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
890
-					}
891
-					$view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
892
-				}
893
-			}
894
-		} else {
895
-			$size += $view->filesize($source);
896
-			$result = $view->copy($source, $destination);
897
-			if (!$result) {
898
-				throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
899
-			}
900
-			$view->touch($destination, $view->filemtime($source));
901
-		}
902
-		return $size;
903
-	}
904
-
905
-	/**
906
-	 * find all versions which belong to the file we want to restore
907
-	 *
908
-	 * @param string $filename name of the file which should be restored
909
-	 * @param int $timestamp timestamp when the file was deleted
910
-	 * @return array
911
-	 */
912
-	private static function getVersionsFromTrash($filename, $timestamp, $user) {
913
-		$view = new View('/' . $user . '/files_trashbin/versions');
914
-		$versions = [];
915
-
916
-		//force rescan of versions, local storage may not have updated the cache
917
-		if (!self::$scannedVersions) {
918
-			/** @var \OC\Files\Storage\Storage $storage */
919
-			[$storage,] = $view->resolvePath('/');
920
-			$storage->getScanner()->scan('files_trashbin/versions');
921
-			self::$scannedVersions = true;
922
-		}
923
-
924
-		if ($timestamp) {
925
-			// fetch for old versions
926
-			$matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
927
-			$offset = -strlen($timestamp) - 2;
928
-		} else {
929
-			$matches = $view->searchRaw($filename . '.v%');
930
-		}
931
-
932
-		if (is_array($matches)) {
933
-			foreach ($matches as $ma) {
934
-				if ($timestamp) {
935
-					$parts = explode('.v', substr($ma['path'], 0, $offset));
936
-					$versions[] = end($parts);
937
-				} else {
938
-					$parts = explode('.v', $ma);
939
-					$versions[] = end($parts);
940
-				}
941
-			}
942
-		}
943
-		return $versions;
944
-	}
945
-
946
-	/**
947
-	 * find unique extension for restored file if a file with the same name already exists
948
-	 *
949
-	 * @param string $location where the file should be restored
950
-	 * @param string $filename name of the file
951
-	 * @param View $view filesystem view relative to users root directory
952
-	 * @return string with unique extension
953
-	 */
954
-	private static function getUniqueFilename($location, $filename, View $view) {
955
-		$ext = pathinfo($filename, PATHINFO_EXTENSION);
956
-		$name = pathinfo($filename, PATHINFO_FILENAME);
957
-		$l = \OC::$server->getL10N('files_trashbin');
958
-
959
-		$location = '/' . trim($location, '/');
960
-
961
-		// if extension is not empty we set a dot in front of it
962
-		if ($ext !== '') {
963
-			$ext = '.' . $ext;
964
-		}
965
-
966
-		if ($view->file_exists('files' . $location . '/' . $filename)) {
967
-			$i = 2;
968
-			$uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
969
-			while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
970
-				$uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
971
-				$i++;
972
-			}
973
-
974
-			return $uniqueName;
975
-		}
976
-
977
-		return $filename;
978
-	}
979
-
980
-	/**
981
-	 * get the size from a given root folder
982
-	 *
983
-	 * @param View $view file view on the root folder
984
-	 * @return integer size of the folder
985
-	 */
986
-	private static function calculateSize($view) {
987
-		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
988
-		if (!file_exists($root)) {
989
-			return 0;
990
-		}
991
-		$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
992
-		$size = 0;
993
-
994
-		/**
995
-		 * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
996
-		 * This bug is fixed in PHP 5.5.9 or before
997
-		 * See #8376
998
-		 */
999
-		$iterator->rewind();
1000
-		while ($iterator->valid()) {
1001
-			$path = $iterator->current();
1002
-			$relpath = substr($path, strlen($root) - 1);
1003
-			if (!$view->is_dir($relpath)) {
1004
-				$size += $view->filesize($relpath);
1005
-			}
1006
-			$iterator->next();
1007
-		}
1008
-		return $size;
1009
-	}
1010
-
1011
-	/**
1012
-	 * get current size of trash bin from a given user
1013
-	 *
1014
-	 * @param string $user user who owns the trash bin
1015
-	 * @return integer trash bin size
1016
-	 */
1017
-	private static function getTrashbinSize($user) {
1018
-		$view = new View('/' . $user);
1019
-		$fileInfo = $view->getFileInfo('/files_trashbin');
1020
-		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
1021
-	}
1022
-
1023
-	/**
1024
-	 * check if trash bin is empty for a given user
1025
-	 *
1026
-	 * @param string $user
1027
-	 * @return bool
1028
-	 */
1029
-	public static function isEmpty($user) {
1030
-		$view = new View('/' . $user . '/files_trashbin');
1031
-		if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
1032
-			while ($file = readdir($dh)) {
1033
-				if (!Filesystem::isIgnoredDir($file)) {
1034
-					return false;
1035
-				}
1036
-			}
1037
-		}
1038
-		return true;
1039
-	}
1040
-
1041
-	/**
1042
-	 * @param $path
1043
-	 * @return string
1044
-	 */
1045
-	public static function preview_icon($path) {
1046
-		return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_trashbin_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
1047
-	}
62
+    // unit: percentage; 50% of available disk space/quota
63
+    public const DEFAULTMAXSIZE = 50;
64
+
65
+    /**
66
+     * Whether versions have already be rescanned during this PHP request
67
+     *
68
+     * @var bool
69
+     */
70
+    private static $scannedVersions = false;
71
+
72
+    /**
73
+     * Ensure we don't need to scan the file during the move to trash
74
+     * by triggering the scan in the pre-hook
75
+     *
76
+     * @param array $params
77
+     */
78
+    public static function ensureFileScannedHook($params) {
79
+        try {
80
+            self::getUidAndFilename($params['path']);
81
+        } catch (NotFoundException $e) {
82
+            // nothing to scan for non existing files
83
+        }
84
+    }
85
+
86
+    /**
87
+     * get the UID of the owner of the file and the path to the file relative to
88
+     * owners files folder
89
+     *
90
+     * @param string $filename
91
+     * @return array
92
+     * @throws \OC\User\NoUserException
93
+     */
94
+    public static function getUidAndFilename($filename) {
95
+        $uid = Filesystem::getOwner($filename);
96
+        $userManager = \OC::$server->getUserManager();
97
+        // if the user with the UID doesn't exists, e.g. because the UID points
98
+        // to a remote user with a federated cloud ID we use the current logged-in
99
+        // user. We need a valid local user to move the file to the right trash bin
100
+        if (!$userManager->userExists($uid)) {
101
+            $uid = User::getUser();
102
+        }
103
+        if (!$uid) {
104
+            // no owner, usually because of share link from ext storage
105
+            return [null, null];
106
+        }
107
+        Filesystem::initMountPoints($uid);
108
+        if ($uid !== User::getUser()) {
109
+            $info = Filesystem::getFileInfo($filename);
110
+            $ownerView = new View('/' . $uid . '/files');
111
+            try {
112
+                $filename = $ownerView->getPath($info['fileid']);
113
+            } catch (NotFoundException $e) {
114
+                $filename = null;
115
+            }
116
+        }
117
+        return [$uid, $filename];
118
+    }
119
+
120
+    /**
121
+     * get original location of files for user
122
+     *
123
+     * @param string $user
124
+     * @return array (filename => array (timestamp => original location))
125
+     */
126
+    public static function getLocations($user) {
127
+        $query = \OC_DB::prepare('SELECT `id`, `timestamp`, `location`'
128
+            . ' FROM `*PREFIX*files_trash` WHERE `user`=?');
129
+        $result = $query->execute([$user]);
130
+        $array = [];
131
+        while ($row = $result->fetchRow()) {
132
+            if (isset($array[$row['id']])) {
133
+                $array[$row['id']][$row['timestamp']] = $row['location'];
134
+            } else {
135
+                $array[$row['id']] = [$row['timestamp'] => $row['location']];
136
+            }
137
+        }
138
+        return $array;
139
+    }
140
+
141
+    /**
142
+     * get original location of file
143
+     *
144
+     * @param string $user
145
+     * @param string $filename
146
+     * @param string $timestamp
147
+     * @return string original location
148
+     */
149
+    public static function getLocation($user, $filename, $timestamp) {
150
+        $query = \OC_DB::prepare('SELECT `location` FROM `*PREFIX*files_trash`'
151
+            . ' WHERE `user`=? AND `id`=? AND `timestamp`=?');
152
+        $result = $query->execute([$user, $filename, $timestamp])->fetchAll();
153
+        if (isset($result[0]['location'])) {
154
+            return $result[0]['location'];
155
+        } else {
156
+            return false;
157
+        }
158
+    }
159
+
160
+    private static function setUpTrash($user) {
161
+        $view = new View('/' . $user);
162
+        if (!$view->is_dir('files_trashbin')) {
163
+            $view->mkdir('files_trashbin');
164
+        }
165
+        if (!$view->is_dir('files_trashbin/files')) {
166
+            $view->mkdir('files_trashbin/files');
167
+        }
168
+        if (!$view->is_dir('files_trashbin/versions')) {
169
+            $view->mkdir('files_trashbin/versions');
170
+        }
171
+        if (!$view->is_dir('files_trashbin/keys')) {
172
+            $view->mkdir('files_trashbin/keys');
173
+        }
174
+    }
175
+
176
+
177
+    /**
178
+     * copy file to owners trash
179
+     *
180
+     * @param string $sourcePath
181
+     * @param string $owner
182
+     * @param string $targetPath
183
+     * @param $user
184
+     * @param integer $timestamp
185
+     */
186
+    private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) {
187
+        self::setUpTrash($owner);
188
+
189
+        $targetFilename = basename($targetPath);
190
+        $targetLocation = dirname($targetPath);
191
+
192
+        $sourceFilename = basename($sourcePath);
193
+
194
+        $view = new View('/');
195
+
196
+        $target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
197
+        $source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
198
+        $free = $view->free_space($target);
199
+        $isUnknownOrUnlimitedFreeSpace = $free < 0;
200
+        $isEnoughFreeSpaceLeft = $view->filesize($source) < $free;
201
+        if ($isUnknownOrUnlimitedFreeSpace || $isEnoughFreeSpaceLeft) {
202
+            self::copy_recursive($source, $target, $view);
203
+        }
204
+
205
+
206
+        if ($view->file_exists($target)) {
207
+            $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
208
+            $result = $query->execute([$targetFilename, $timestamp, $targetLocation, $user]);
209
+            if (!$result) {
210
+                \OC::$server->getLogger()->error('trash bin database couldn\'t be updated for the files owner', ['app' => 'files_trashbin']);
211
+            }
212
+        }
213
+    }
214
+
215
+
216
+    /**
217
+     * move file to the trash bin
218
+     *
219
+     * @param string $file_path path to the deleted file/directory relative to the files root directory
220
+     * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
221
+     *
222
+     * @return bool
223
+     */
224
+    public static function move2trash($file_path, $ownerOnly = false) {
225
+        // get the user for which the filesystem is setup
226
+        $root = Filesystem::getRoot();
227
+        [, $user] = explode('/', $root);
228
+        [$owner, $ownerPath] = self::getUidAndFilename($file_path);
229
+
230
+        // if no owner found (ex: ext storage + share link), will use the current user's trashbin then
231
+        if (is_null($owner)) {
232
+            $owner = $user;
233
+            $ownerPath = $file_path;
234
+        }
235
+
236
+        $ownerView = new View('/' . $owner);
237
+        // file has been deleted in between
238
+        if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) {
239
+            return true;
240
+        }
241
+
242
+        self::setUpTrash($user);
243
+        if ($owner !== $user) {
244
+            // also setup for owner
245
+            self::setUpTrash($owner);
246
+        }
247
+
248
+        $path_parts = pathinfo($ownerPath);
249
+
250
+        $filename = $path_parts['basename'];
251
+        $location = $path_parts['dirname'];
252
+        /** @var ITimeFactory $timeFactory */
253
+        $timeFactory = \OC::$server->query(ITimeFactory::class);
254
+        $timestamp = $timeFactory->getTime();
255
+
256
+        $lockingProvider = \OC::$server->getLockingProvider();
257
+
258
+        // disable proxy to prevent recursive calls
259
+        $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
260
+        $gotLock = false;
261
+
262
+        while (!$gotLock) {
263
+            try {
264
+                /** @var \OC\Files\Storage\Storage $trashStorage */
265
+                [$trashStorage, $trashInternalPath] = $ownerView->resolvePath($trashPath);
266
+
267
+                $trashStorage->acquireLock($trashInternalPath, ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
268
+                $gotLock = true;
269
+            } catch (LockedException $e) {
270
+                // a file with the same name is being deleted concurrently
271
+                // nudge the timestamp a bit to resolve the conflict
272
+
273
+                $timestamp = $timestamp + 1;
274
+
275
+                $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
276
+            }
277
+        }
278
+
279
+        /** @var \OC\Files\Storage\Storage $sourceStorage */
280
+        [$sourceStorage, $sourceInternalPath] = $ownerView->resolvePath('/files/' . $ownerPath);
281
+
282
+
283
+        if ($trashStorage->file_exists($trashInternalPath)) {
284
+            $trashStorage->unlink($trashInternalPath);
285
+        }
286
+
287
+        $connection = \OC::$server->getDatabaseConnection();
288
+        $connection->beginTransaction();
289
+        $trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
290
+
291
+        try {
292
+            $moveSuccessful = true;
293
+
294
+            // when moving within the same object store, the cache update done above is enough to move the file
295
+            if (!($trashStorage->instanceOfStorage(ObjectStoreStorage::class) && $trashStorage->getId() === $sourceStorage->getId())) {
296
+                $trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
297
+            }
298
+        } catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) {
299
+            $moveSuccessful = false;
300
+            if ($trashStorage->file_exists($trashInternalPath)) {
301
+                $trashStorage->unlink($trashInternalPath);
302
+            }
303
+            \OC::$server->getLogger()->error('Couldn\'t move ' . $file_path . ' to the trash bin', ['app' => 'files_trashbin']);
304
+        }
305
+
306
+        if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
307
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
308
+                $sourceStorage->rmdir($sourceInternalPath);
309
+            } else {
310
+                $sourceStorage->unlink($sourceInternalPath);
311
+            }
312
+            $connection->rollBack();
313
+            return false;
314
+        }
315
+
316
+        $connection->commit();
317
+
318
+        if ($moveSuccessful) {
319
+            $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
320
+            $result = $query->execute([$filename, $timestamp, $location, $owner]);
321
+            if (!$result) {
322
+                \OC::$server->getLogger()->error('trash bin database couldn\'t be updated', ['app' => 'files_trashbin']);
323
+            }
324
+            \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', ['filePath' => Filesystem::normalizePath($file_path),
325
+                'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)]);
326
+
327
+            self::retainVersions($filename, $owner, $ownerPath, $timestamp);
328
+
329
+            // if owner !== user we need to also add a copy to the users trash
330
+            if ($user !== $owner && $ownerOnly === false) {
331
+                self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp);
332
+            }
333
+        }
334
+
335
+        $trashStorage->releaseLock($trashInternalPath, ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
336
+
337
+        self::scheduleExpire($user);
338
+
339
+        // if owner !== user we also need to update the owners trash size
340
+        if ($owner !== $user) {
341
+            self::scheduleExpire($owner);
342
+        }
343
+
344
+        return $moveSuccessful;
345
+    }
346
+
347
+    /**
348
+     * Move file versions to trash so that they can be restored later
349
+     *
350
+     * @param string $filename of deleted file
351
+     * @param string $owner owner user id
352
+     * @param string $ownerPath path relative to the owner's home storage
353
+     * @param integer $timestamp when the file was deleted
354
+     */
355
+    private static function retainVersions($filename, $owner, $ownerPath, $timestamp) {
356
+        if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) {
357
+            $user = User::getUser();
358
+            $rootView = new View('/');
359
+
360
+            if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
361
+                if ($owner !== $user) {
362
+                    self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView);
363
+                }
364
+                self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
365
+            } elseif ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
366
+                foreach ($versions as $v) {
367
+                    if ($owner !== $user) {
368
+                        self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp);
369
+                    }
370
+                    self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
371
+                }
372
+            }
373
+        }
374
+    }
375
+
376
+    /**
377
+     * Move a file or folder on storage level
378
+     *
379
+     * @param View $view
380
+     * @param string $source
381
+     * @param string $target
382
+     * @return bool
383
+     */
384
+    private static function move(View $view, $source, $target) {
385
+        /** @var \OC\Files\Storage\Storage $sourceStorage */
386
+        [$sourceStorage, $sourceInternalPath] = $view->resolvePath($source);
387
+        /** @var \OC\Files\Storage\Storage $targetStorage */
388
+        [$targetStorage, $targetInternalPath] = $view->resolvePath($target);
389
+        /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
390
+
391
+        $result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
392
+        if ($result) {
393
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
394
+        }
395
+        return $result;
396
+    }
397
+
398
+    /**
399
+     * Copy a file or folder on storage level
400
+     *
401
+     * @param View $view
402
+     * @param string $source
403
+     * @param string $target
404
+     * @return bool
405
+     */
406
+    private static function copy(View $view, $source, $target) {
407
+        /** @var \OC\Files\Storage\Storage $sourceStorage */
408
+        [$sourceStorage, $sourceInternalPath] = $view->resolvePath($source);
409
+        /** @var \OC\Files\Storage\Storage $targetStorage */
410
+        [$targetStorage, $targetInternalPath] = $view->resolvePath($target);
411
+        /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
412
+
413
+        $result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
414
+        if ($result) {
415
+            $targetStorage->getUpdater()->update($targetInternalPath);
416
+        }
417
+        return $result;
418
+    }
419
+
420
+    /**
421
+     * Restore a file or folder from trash bin
422
+     *
423
+     * @param string $file path to the deleted file/folder relative to "files_trashbin/files/",
424
+     * including the timestamp suffix ".d12345678"
425
+     * @param string $filename name of the file/folder
426
+     * @param int $timestamp time when the file/folder was deleted
427
+     *
428
+     * @return bool true on success, false otherwise
429
+     */
430
+    public static function restore($file, $filename, $timestamp) {
431
+        $user = User::getUser();
432
+        $view = new View('/' . $user);
433
+
434
+        $location = '';
435
+        if ($timestamp) {
436
+            $location = self::getLocation($user, $filename, $timestamp);
437
+            if ($location === false) {
438
+                \OC::$server->getLogger()->error('trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']);
439
+            } else {
440
+                // if location no longer exists, restore file in the root directory
441
+                if ($location !== '/' &&
442
+                    (!$view->is_dir('files/' . $location) ||
443
+                        !$view->isCreatable('files/' . $location))
444
+                ) {
445
+                    $location = '';
446
+                }
447
+            }
448
+        }
449
+
450
+        // we need a  extension in case a file/dir with the same name already exists
451
+        $uniqueFilename = self::getUniqueFilename($location, $filename, $view);
452
+
453
+        $source = Filesystem::normalizePath('files_trashbin/files/' . $file);
454
+        $target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
455
+        if (!$view->file_exists($source)) {
456
+            return false;
457
+        }
458
+        $mtime = $view->filemtime($source);
459
+
460
+        // restore file
461
+        if (!$view->isCreatable(dirname($target))) {
462
+            throw new NotPermittedException("Can't restore trash item because the target folder is not writable");
463
+        }
464
+        $restoreResult = $view->rename($source, $target);
465
+
466
+        // handle the restore result
467
+        if ($restoreResult) {
468
+            $fakeRoot = $view->getRoot();
469
+            $view->chroot('/' . $user . '/files');
470
+            $view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
471
+            $view->chroot($fakeRoot);
472
+            \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', ['filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
473
+                'trashPath' => Filesystem::normalizePath($file)]);
474
+
475
+            self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
476
+
477
+            if ($timestamp) {
478
+                $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
479
+                $query->execute([$user, $filename, $timestamp]);
480
+            }
481
+
482
+            return true;
483
+        }
484
+
485
+        return false;
486
+    }
487
+
488
+    /**
489
+     * restore versions from trash bin
490
+     *
491
+     * @param View $view file view
492
+     * @param string $file complete path to file
493
+     * @param string $filename name of file once it was deleted
494
+     * @param string $uniqueFilename new file name to restore the file without overwriting existing files
495
+     * @param string $location location if file
496
+     * @param int $timestamp deletion time
497
+     * @return false|null
498
+     */
499
+    private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) {
500
+        if (\OCP\App::isEnabled('files_versions')) {
501
+            $user = User::getUser();
502
+            $rootView = new View('/');
503
+
504
+            $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
505
+
506
+            [$owner, $ownerPath] = self::getUidAndFilename($target);
507
+
508
+            // file has been deleted in between
509
+            if (empty($ownerPath)) {
510
+                return false;
511
+            }
512
+
513
+            if ($timestamp) {
514
+                $versionedFile = $filename;
515
+            } else {
516
+                $versionedFile = $file;
517
+            }
518
+
519
+            if ($view->is_dir('/files_trashbin/versions/' . $file)) {
520
+                $rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
521
+            } elseif ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
522
+                foreach ($versions as $v) {
523
+                    if ($timestamp) {
524
+                        $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
525
+                    } else {
526
+                        $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
527
+                    }
528
+                }
529
+            }
530
+        }
531
+    }
532
+
533
+    /**
534
+     * delete all files from the trash
535
+     */
536
+    public static function deleteAll() {
537
+        $user = User::getUser();
538
+        $userRoot = \OC::$server->getUserFolder($user)->getParent();
539
+        $view = new View('/' . $user);
540
+        $fileInfos = $view->getDirectoryContent('files_trashbin/files');
541
+
542
+        try {
543
+            $trash = $userRoot->get('files_trashbin');
544
+        } catch (NotFoundException $e) {
545
+            return false;
546
+        }
547
+
548
+        // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
549
+        $filePaths = [];
550
+        foreach ($fileInfos as $fileInfo) {
551
+            $filePaths[] = $view->getRelativePath($fileInfo->getPath());
552
+        }
553
+        unset($fileInfos); // save memory
554
+
555
+        // Bulk PreDelete-Hook
556
+        \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', ['paths' => $filePaths]);
557
+
558
+        // Single-File Hooks
559
+        foreach ($filePaths as $path) {
560
+            self::emitTrashbinPreDelete($path);
561
+        }
562
+
563
+        // actual file deletion
564
+        $trash->delete();
565
+        $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
566
+        $query->execute([$user]);
567
+
568
+        // Bulk PostDelete-Hook
569
+        \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', ['paths' => $filePaths]);
570
+
571
+        // Single-File Hooks
572
+        foreach ($filePaths as $path) {
573
+            self::emitTrashbinPostDelete($path);
574
+        }
575
+
576
+        $trash = $userRoot->newFolder('files_trashbin');
577
+        $trash->newFolder('files');
578
+
579
+        return true;
580
+    }
581
+
582
+    /**
583
+     * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
584
+     *
585
+     * @param string $path
586
+     */
587
+    protected static function emitTrashbinPreDelete($path) {
588
+        \OC_Hook::emit('\OCP\Trashbin', 'preDelete', ['path' => $path]);
589
+    }
590
+
591
+    /**
592
+     * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
593
+     *
594
+     * @param string $path
595
+     */
596
+    protected static function emitTrashbinPostDelete($path) {
597
+        \OC_Hook::emit('\OCP\Trashbin', 'delete', ['path' => $path]);
598
+    }
599
+
600
+    /**
601
+     * delete file from trash bin permanently
602
+     *
603
+     * @param string $filename path to the file
604
+     * @param string $user
605
+     * @param int $timestamp of deletion time
606
+     *
607
+     * @return int size of deleted files
608
+     */
609
+    public static function delete($filename, $user, $timestamp = null) {
610
+        $userRoot = \OC::$server->getUserFolder($user)->getParent();
611
+        $view = new View('/' . $user);
612
+        $size = 0;
613
+
614
+        if ($timestamp) {
615
+            $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
616
+            $query->execute([$user, $filename, $timestamp]);
617
+            $file = $filename . '.d' . $timestamp;
618
+        } else {
619
+            $file = $filename;
620
+        }
621
+
622
+        $size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
623
+
624
+        try {
625
+            $node = $userRoot->get('/files_trashbin/files/' . $file);
626
+        } catch (NotFoundException $e) {
627
+            return $size;
628
+        }
629
+
630
+        if ($node instanceof Folder) {
631
+            $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
632
+        } elseif ($node instanceof File) {
633
+            $size += $view->filesize('/files_trashbin/files/' . $file);
634
+        }
635
+
636
+        self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
637
+        $node->delete();
638
+        self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
639
+
640
+        return $size;
641
+    }
642
+
643
+    /**
644
+     * @param View $view
645
+     * @param string $file
646
+     * @param string $filename
647
+     * @param integer|null $timestamp
648
+     * @param string $user
649
+     * @return int
650
+     */
651
+    private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
652
+        $size = 0;
653
+        if (\OCP\App::isEnabled('files_versions')) {
654
+            if ($view->is_dir('files_trashbin/versions/' . $file)) {
655
+                $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
656
+                $view->unlink('files_trashbin/versions/' . $file);
657
+            } elseif ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
658
+                foreach ($versions as $v) {
659
+                    if ($timestamp) {
660
+                        $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
661
+                        $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
662
+                    } else {
663
+                        $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
664
+                        $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
665
+                    }
666
+                }
667
+            }
668
+        }
669
+        return $size;
670
+    }
671
+
672
+    /**
673
+     * check to see whether a file exists in trashbin
674
+     *
675
+     * @param string $filename path to the file
676
+     * @param int $timestamp of deletion time
677
+     * @return bool true if file exists, otherwise false
678
+     */
679
+    public static function file_exists($filename, $timestamp = null) {
680
+        $user = User::getUser();
681
+        $view = new View('/' . $user);
682
+
683
+        if ($timestamp) {
684
+            $filename = $filename . '.d' . $timestamp;
685
+        }
686
+
687
+        $target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
688
+        return $view->file_exists($target);
689
+    }
690
+
691
+    /**
692
+     * deletes used space for trash bin in db if user was deleted
693
+     *
694
+     * @param string $uid id of deleted user
695
+     * @return bool result of db delete operation
696
+     */
697
+    public static function deleteUser($uid) {
698
+        $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
699
+        return $query->execute([$uid]);
700
+    }
701
+
702
+    /**
703
+     * calculate remaining free space for trash bin
704
+     *
705
+     * @param integer $trashbinSize current size of the trash bin
706
+     * @param string $user
707
+     * @return int available free space for trash bin
708
+     */
709
+    private static function calculateFreeSpace($trashbinSize, $user) {
710
+        $config = \OC::$server->getConfig();
711
+        $systemTrashbinSize = (int)$config->getAppValue('files_trashbin', 'trashbin_size', '-1');
712
+        $userTrashbinSize = (int)$config->getUserValue($user, 'files_trashbin', 'trashbin_size', '-1');
713
+        $configuredTrashbinSize = ($userTrashbinSize < 0) ? $systemTrashbinSize : $userTrashbinSize;
714
+        if ($configuredTrashbinSize) {
715
+            return $configuredTrashbinSize - $trashbinSize;
716
+        }
717
+
718
+        $softQuota = true;
719
+        $userObject = \OC::$server->getUserManager()->get($user);
720
+        if (is_null($userObject)) {
721
+            return 0;
722
+        }
723
+        $quota = $userObject->getQuota();
724
+        if ($quota === null || $quota === 'none') {
725
+            $quota = Filesystem::free_space('/');
726
+            $softQuota = false;
727
+            // inf or unknown free space
728
+            if ($quota < 0) {
729
+                $quota = PHP_INT_MAX;
730
+            }
731
+        } else {
732
+            $quota = \OCP\Util::computerFileSize($quota);
733
+        }
734
+
735
+        // calculate available space for trash bin
736
+        // subtract size of files and current trash bin size from quota
737
+        if ($softQuota) {
738
+            $userFolder = \OC::$server->getUserFolder($user);
739
+            if (is_null($userFolder)) {
740
+                return 0;
741
+            }
742
+            $free = $quota - $userFolder->getSize(false); // remaining free space for user
743
+            if ($free > 0) {
744
+                $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
745
+            } else {
746
+                $availableSpace = $free - $trashbinSize;
747
+            }
748
+        } else {
749
+            $availableSpace = $quota;
750
+        }
751
+
752
+        return $availableSpace;
753
+    }
754
+
755
+    /**
756
+     * resize trash bin if necessary after a new file was added to Nextcloud
757
+     *
758
+     * @param string $user user id
759
+     */
760
+    public static function resizeTrash($user) {
761
+        $size = self::getTrashbinSize($user);
762
+
763
+        $freeSpace = self::calculateFreeSpace($size, $user);
764
+
765
+        if ($freeSpace < 0) {
766
+            self::scheduleExpire($user);
767
+        }
768
+    }
769
+
770
+    /**
771
+     * clean up the trash bin
772
+     *
773
+     * @param string $user
774
+     */
775
+    public static function expire($user) {
776
+        $trashBinSize = self::getTrashbinSize($user);
777
+        $availableSpace = self::calculateFreeSpace($trashBinSize, $user);
778
+
779
+        $dirContent = Helper::getTrashFiles('/', $user, 'mtime');
780
+
781
+        // delete all files older then $retention_obligation
782
+        [$delSize, $count] = self::deleteExpiredFiles($dirContent, $user);
783
+
784
+        $availableSpace += $delSize;
785
+
786
+        // delete files from trash until we meet the trash bin size limit again
787
+        self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
788
+    }
789
+
790
+    /**
791
+     * @param string $user
792
+     */
793
+    private static function scheduleExpire($user) {
794
+        // let the admin disable auto expire
795
+        /** @var Application $application */
796
+        $application = \OC::$server->query(Application::class);
797
+        $expiration = $application->getContainer()->query('Expiration');
798
+        if ($expiration->isEnabled()) {
799
+            \OC::$server->getCommandBus()->push(new Expire($user));
800
+        }
801
+    }
802
+
803
+    /**
804
+     * if the size limit for the trash bin is reached, we delete the oldest
805
+     * files in the trash bin until we meet the limit again
806
+     *
807
+     * @param array $files
808
+     * @param string $user
809
+     * @param int $availableSpace available disc space
810
+     * @return int size of deleted files
811
+     */
812
+    protected static function deleteFiles($files, $user, $availableSpace) {
813
+        /** @var Application $application */
814
+        $application = \OC::$server->query(Application::class);
815
+        $expiration = $application->getContainer()->query('Expiration');
816
+        $size = 0;
817
+
818
+        if ($availableSpace < 0) {
819
+            foreach ($files as $file) {
820
+                if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
821
+                    $tmp = self::delete($file['name'], $user, $file['mtime']);
822
+                    \OC::$server->getLogger()->info('remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', ['app' => 'files_trashbin']);
823
+                    $availableSpace += $tmp;
824
+                    $size += $tmp;
825
+                } else {
826
+                    break;
827
+                }
828
+            }
829
+        }
830
+        return $size;
831
+    }
832
+
833
+    /**
834
+     * delete files older then max storage time
835
+     *
836
+     * @param array $files list of files sorted by mtime
837
+     * @param string $user
838
+     * @return integer[] size of deleted files and number of deleted files
839
+     */
840
+    public static function deleteExpiredFiles($files, $user) {
841
+        /** @var Expiration $expiration */
842
+        $expiration = \OC::$server->query(Expiration::class);
843
+        $size = 0;
844
+        $count = 0;
845
+        foreach ($files as $file) {
846
+            $timestamp = $file['mtime'];
847
+            $filename = $file['name'];
848
+            if ($expiration->isExpired($timestamp)) {
849
+                try {
850
+                    $size += self::delete($filename, $user, $timestamp);
851
+                    $count++;
852
+                } catch (\OCP\Files\NotPermittedException $e) {
853
+                    \OC::$server->getLogger()->logException($e, ['app' => 'files_trashbin', 'level' => \OCP\ILogger::WARN, 'message' => 'Removing "' . $filename . '" from trashbin failed.']);
854
+                }
855
+                \OC::$server->getLogger()->info(
856
+                    'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
857
+                    ['app' => 'files_trashbin']
858
+                );
859
+            } else {
860
+                break;
861
+            }
862
+        }
863
+
864
+        return [$size, $count];
865
+    }
866
+
867
+    /**
868
+     * recursive copy to copy a whole directory
869
+     *
870
+     * @param string $source source path, relative to the users files directory
871
+     * @param string $destination destination path relative to the users root directoy
872
+     * @param View $view file view for the users root directory
873
+     * @return int
874
+     * @throws Exceptions\CopyRecursiveException
875
+     */
876
+    private static function copy_recursive($source, $destination, View $view) {
877
+        $size = 0;
878
+        if ($view->is_dir($source)) {
879
+            $view->mkdir($destination);
880
+            $view->touch($destination, $view->filemtime($source));
881
+            foreach ($view->getDirectoryContent($source) as $i) {
882
+                $pathDir = $source . '/' . $i['name'];
883
+                if ($view->is_dir($pathDir)) {
884
+                    $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
885
+                } else {
886
+                    $size += $view->filesize($pathDir);
887
+                    $result = $view->copy($pathDir, $destination . '/' . $i['name']);
888
+                    if (!$result) {
889
+                        throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
890
+                    }
891
+                    $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
892
+                }
893
+            }
894
+        } else {
895
+            $size += $view->filesize($source);
896
+            $result = $view->copy($source, $destination);
897
+            if (!$result) {
898
+                throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
899
+            }
900
+            $view->touch($destination, $view->filemtime($source));
901
+        }
902
+        return $size;
903
+    }
904
+
905
+    /**
906
+     * find all versions which belong to the file we want to restore
907
+     *
908
+     * @param string $filename name of the file which should be restored
909
+     * @param int $timestamp timestamp when the file was deleted
910
+     * @return array
911
+     */
912
+    private static function getVersionsFromTrash($filename, $timestamp, $user) {
913
+        $view = new View('/' . $user . '/files_trashbin/versions');
914
+        $versions = [];
915
+
916
+        //force rescan of versions, local storage may not have updated the cache
917
+        if (!self::$scannedVersions) {
918
+            /** @var \OC\Files\Storage\Storage $storage */
919
+            [$storage,] = $view->resolvePath('/');
920
+            $storage->getScanner()->scan('files_trashbin/versions');
921
+            self::$scannedVersions = true;
922
+        }
923
+
924
+        if ($timestamp) {
925
+            // fetch for old versions
926
+            $matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
927
+            $offset = -strlen($timestamp) - 2;
928
+        } else {
929
+            $matches = $view->searchRaw($filename . '.v%');
930
+        }
931
+
932
+        if (is_array($matches)) {
933
+            foreach ($matches as $ma) {
934
+                if ($timestamp) {
935
+                    $parts = explode('.v', substr($ma['path'], 0, $offset));
936
+                    $versions[] = end($parts);
937
+                } else {
938
+                    $parts = explode('.v', $ma);
939
+                    $versions[] = end($parts);
940
+                }
941
+            }
942
+        }
943
+        return $versions;
944
+    }
945
+
946
+    /**
947
+     * find unique extension for restored file if a file with the same name already exists
948
+     *
949
+     * @param string $location where the file should be restored
950
+     * @param string $filename name of the file
951
+     * @param View $view filesystem view relative to users root directory
952
+     * @return string with unique extension
953
+     */
954
+    private static function getUniqueFilename($location, $filename, View $view) {
955
+        $ext = pathinfo($filename, PATHINFO_EXTENSION);
956
+        $name = pathinfo($filename, PATHINFO_FILENAME);
957
+        $l = \OC::$server->getL10N('files_trashbin');
958
+
959
+        $location = '/' . trim($location, '/');
960
+
961
+        // if extension is not empty we set a dot in front of it
962
+        if ($ext !== '') {
963
+            $ext = '.' . $ext;
964
+        }
965
+
966
+        if ($view->file_exists('files' . $location . '/' . $filename)) {
967
+            $i = 2;
968
+            $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
969
+            while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
970
+                $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
971
+                $i++;
972
+            }
973
+
974
+            return $uniqueName;
975
+        }
976
+
977
+        return $filename;
978
+    }
979
+
980
+    /**
981
+     * get the size from a given root folder
982
+     *
983
+     * @param View $view file view on the root folder
984
+     * @return integer size of the folder
985
+     */
986
+    private static function calculateSize($view) {
987
+        $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
988
+        if (!file_exists($root)) {
989
+            return 0;
990
+        }
991
+        $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
992
+        $size = 0;
993
+
994
+        /**
995
+         * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
996
+         * This bug is fixed in PHP 5.5.9 or before
997
+         * See #8376
998
+         */
999
+        $iterator->rewind();
1000
+        while ($iterator->valid()) {
1001
+            $path = $iterator->current();
1002
+            $relpath = substr($path, strlen($root) - 1);
1003
+            if (!$view->is_dir($relpath)) {
1004
+                $size += $view->filesize($relpath);
1005
+            }
1006
+            $iterator->next();
1007
+        }
1008
+        return $size;
1009
+    }
1010
+
1011
+    /**
1012
+     * get current size of trash bin from a given user
1013
+     *
1014
+     * @param string $user user who owns the trash bin
1015
+     * @return integer trash bin size
1016
+     */
1017
+    private static function getTrashbinSize($user) {
1018
+        $view = new View('/' . $user);
1019
+        $fileInfo = $view->getFileInfo('/files_trashbin');
1020
+        return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
1021
+    }
1022
+
1023
+    /**
1024
+     * check if trash bin is empty for a given user
1025
+     *
1026
+     * @param string $user
1027
+     * @return bool
1028
+     */
1029
+    public static function isEmpty($user) {
1030
+        $view = new View('/' . $user . '/files_trashbin');
1031
+        if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
1032
+            while ($file = readdir($dh)) {
1033
+                if (!Filesystem::isIgnoredDir($file)) {
1034
+                    return false;
1035
+                }
1036
+            }
1037
+        }
1038
+        return true;
1039
+    }
1040
+
1041
+    /**
1042
+     * @param $path
1043
+     * @return string
1044
+     */
1045
+    public static function preview_icon($path) {
1046
+        return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_trashbin_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
1047
+    }
1048 1048
 }
Please login to merge, or discard this patch.