Passed
Push — master ( b62d14...39cc19 )
by Roeland
23:30 queued 12:09
created
apps/files_trashbin/lib/Trashbin.php 2 patches
Indentation   +988 added lines, -988 removed lines patch added patch discarded remove patch
@@ -59,992 +59,992 @@
 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
-		$userTrashbinSize = (int)$config->getUserValue($user, 'files_trashbin', 'trashbin_size', '-1');
712
-		if ($userTrashbinSize > -1) {
713
-			return $userTrashbinSize - $trashbinSize;
714
-		}
715
-		$systemTrashbinSize = (int)$config->getAppValue('files_trashbin', 'trashbin_size', '-1');
716
-		if ($systemTrashbinSize > -1) {
717
-			return $systemTrashbinSize - $trashbinSize;
718
-		}
719
-
720
-		$softQuota = true;
721
-		$userObject = \OC::$server->getUserManager()->get($user);
722
-		if (is_null($userObject)) {
723
-			return 0;
724
-		}
725
-		$quota = $userObject->getQuota();
726
-		if ($quota === null || $quota === 'none') {
727
-			$quota = Filesystem::free_space('/');
728
-			$softQuota = false;
729
-			// inf or unknown free space
730
-			if ($quota < 0) {
731
-				$quota = PHP_INT_MAX;
732
-			}
733
-		} else {
734
-			$quota = \OCP\Util::computerFileSize($quota);
735
-		}
736
-
737
-		// calculate available space for trash bin
738
-		// subtract size of files and current trash bin size from quota
739
-		if ($softQuota) {
740
-			$userFolder = \OC::$server->getUserFolder($user);
741
-			if (is_null($userFolder)) {
742
-				return 0;
743
-			}
744
-			$free = $quota - $userFolder->getSize(false); // remaining free space for user
745
-			if ($free > 0) {
746
-				$availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
747
-			} else {
748
-				$availableSpace = $free - $trashbinSize;
749
-			}
750
-		} else {
751
-			$availableSpace = $quota;
752
-		}
753
-
754
-		return $availableSpace;
755
-	}
756
-
757
-	/**
758
-	 * resize trash bin if necessary after a new file was added to Nextcloud
759
-	 *
760
-	 * @param string $user user id
761
-	 */
762
-	public static function resizeTrash($user) {
763
-		$size = self::getTrashbinSize($user);
764
-
765
-		$freeSpace = self::calculateFreeSpace($size, $user);
766
-
767
-		if ($freeSpace < 0) {
768
-			self::scheduleExpire($user);
769
-		}
770
-	}
771
-
772
-	/**
773
-	 * clean up the trash bin
774
-	 *
775
-	 * @param string $user
776
-	 */
777
-	public static function expire($user) {
778
-		$trashBinSize = self::getTrashbinSize($user);
779
-		$availableSpace = self::calculateFreeSpace($trashBinSize, $user);
780
-
781
-		$dirContent = Helper::getTrashFiles('/', $user, 'mtime');
782
-
783
-		// delete all files older then $retention_obligation
784
-		[$delSize, $count] = self::deleteExpiredFiles($dirContent, $user);
785
-
786
-		$availableSpace += $delSize;
787
-
788
-		// delete files from trash until we meet the trash bin size limit again
789
-		self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
790
-	}
791
-
792
-	/**
793
-	 * @param string $user
794
-	 */
795
-	private static function scheduleExpire($user) {
796
-		// let the admin disable auto expire
797
-		/** @var Application $application */
798
-		$application = \OC::$server->query(Application::class);
799
-		$expiration = $application->getContainer()->query('Expiration');
800
-		if ($expiration->isEnabled()) {
801
-			\OC::$server->getCommandBus()->push(new Expire($user));
802
-		}
803
-	}
804
-
805
-	/**
806
-	 * if the size limit for the trash bin is reached, we delete the oldest
807
-	 * files in the trash bin until we meet the limit again
808
-	 *
809
-	 * @param array $files
810
-	 * @param string $user
811
-	 * @param int $availableSpace available disc space
812
-	 * @return int size of deleted files
813
-	 */
814
-	protected static function deleteFiles($files, $user, $availableSpace) {
815
-		/** @var Application $application */
816
-		$application = \OC::$server->query(Application::class);
817
-		$expiration = $application->getContainer()->query('Expiration');
818
-		$size = 0;
819
-
820
-		if ($availableSpace < 0) {
821
-			foreach ($files as $file) {
822
-				if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
823
-					$tmp = self::delete($file['name'], $user, $file['mtime']);
824
-					\OC::$server->getLogger()->info('remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', ['app' => 'files_trashbin']);
825
-					$availableSpace += $tmp;
826
-					$size += $tmp;
827
-				} else {
828
-					break;
829
-				}
830
-			}
831
-		}
832
-		return $size;
833
-	}
834
-
835
-	/**
836
-	 * delete files older then max storage time
837
-	 *
838
-	 * @param array $files list of files sorted by mtime
839
-	 * @param string $user
840
-	 * @return integer[] size of deleted files and number of deleted files
841
-	 */
842
-	public static function deleteExpiredFiles($files, $user) {
843
-		/** @var Expiration $expiration */
844
-		$expiration = \OC::$server->query(Expiration::class);
845
-		$size = 0;
846
-		$count = 0;
847
-		foreach ($files as $file) {
848
-			$timestamp = $file['mtime'];
849
-			$filename = $file['name'];
850
-			if ($expiration->isExpired($timestamp)) {
851
-				try {
852
-					$size += self::delete($filename, $user, $timestamp);
853
-					$count++;
854
-				} catch (\OCP\Files\NotPermittedException $e) {
855
-					\OC::$server->getLogger()->logException($e, ['app' => 'files_trashbin', 'level' => \OCP\ILogger::WARN, 'message' => 'Removing "' . $filename . '" from trashbin failed.']);
856
-				}
857
-				\OC::$server->getLogger()->info(
858
-					'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
859
-					['app' => 'files_trashbin']
860
-				);
861
-			} else {
862
-				break;
863
-			}
864
-		}
865
-
866
-		return [$size, $count];
867
-	}
868
-
869
-	/**
870
-	 * recursive copy to copy a whole directory
871
-	 *
872
-	 * @param string $source source path, relative to the users files directory
873
-	 * @param string $destination destination path relative to the users root directoy
874
-	 * @param View $view file view for the users root directory
875
-	 * @return int
876
-	 * @throws Exceptions\CopyRecursiveException
877
-	 */
878
-	private static function copy_recursive($source, $destination, View $view) {
879
-		$size = 0;
880
-		if ($view->is_dir($source)) {
881
-			$view->mkdir($destination);
882
-			$view->touch($destination, $view->filemtime($source));
883
-			foreach ($view->getDirectoryContent($source) as $i) {
884
-				$pathDir = $source . '/' . $i['name'];
885
-				if ($view->is_dir($pathDir)) {
886
-					$size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
887
-				} else {
888
-					$size += $view->filesize($pathDir);
889
-					$result = $view->copy($pathDir, $destination . '/' . $i['name']);
890
-					if (!$result) {
891
-						throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
892
-					}
893
-					$view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
894
-				}
895
-			}
896
-		} else {
897
-			$size += $view->filesize($source);
898
-			$result = $view->copy($source, $destination);
899
-			if (!$result) {
900
-				throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
901
-			}
902
-			$view->touch($destination, $view->filemtime($source));
903
-		}
904
-		return $size;
905
-	}
906
-
907
-	/**
908
-	 * find all versions which belong to the file we want to restore
909
-	 *
910
-	 * @param string $filename name of the file which should be restored
911
-	 * @param int $timestamp timestamp when the file was deleted
912
-	 * @return array
913
-	 */
914
-	private static function getVersionsFromTrash($filename, $timestamp, $user) {
915
-		$view = new View('/' . $user . '/files_trashbin/versions');
916
-		$versions = [];
917
-
918
-		//force rescan of versions, local storage may not have updated the cache
919
-		if (!self::$scannedVersions) {
920
-			/** @var \OC\Files\Storage\Storage $storage */
921
-			[$storage,] = $view->resolvePath('/');
922
-			$storage->getScanner()->scan('files_trashbin/versions');
923
-			self::$scannedVersions = true;
924
-		}
925
-
926
-		if ($timestamp) {
927
-			// fetch for old versions
928
-			$matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
929
-			$offset = -strlen($timestamp) - 2;
930
-		} else {
931
-			$matches = $view->searchRaw($filename . '.v%');
932
-		}
933
-
934
-		if (is_array($matches)) {
935
-			foreach ($matches as $ma) {
936
-				if ($timestamp) {
937
-					$parts = explode('.v', substr($ma['path'], 0, $offset));
938
-					$versions[] = end($parts);
939
-				} else {
940
-					$parts = explode('.v', $ma);
941
-					$versions[] = end($parts);
942
-				}
943
-			}
944
-		}
945
-		return $versions;
946
-	}
947
-
948
-	/**
949
-	 * find unique extension for restored file if a file with the same name already exists
950
-	 *
951
-	 * @param string $location where the file should be restored
952
-	 * @param string $filename name of the file
953
-	 * @param View $view filesystem view relative to users root directory
954
-	 * @return string with unique extension
955
-	 */
956
-	private static function getUniqueFilename($location, $filename, View $view) {
957
-		$ext = pathinfo($filename, PATHINFO_EXTENSION);
958
-		$name = pathinfo($filename, PATHINFO_FILENAME);
959
-		$l = \OC::$server->getL10N('files_trashbin');
960
-
961
-		$location = '/' . trim($location, '/');
962
-
963
-		// if extension is not empty we set a dot in front of it
964
-		if ($ext !== '') {
965
-			$ext = '.' . $ext;
966
-		}
967
-
968
-		if ($view->file_exists('files' . $location . '/' . $filename)) {
969
-			$i = 2;
970
-			$uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
971
-			while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
972
-				$uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
973
-				$i++;
974
-			}
975
-
976
-			return $uniqueName;
977
-		}
978
-
979
-		return $filename;
980
-	}
981
-
982
-	/**
983
-	 * get the size from a given root folder
984
-	 *
985
-	 * @param View $view file view on the root folder
986
-	 * @return integer size of the folder
987
-	 */
988
-	private static function calculateSize($view) {
989
-		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
990
-		if (!file_exists($root)) {
991
-			return 0;
992
-		}
993
-		$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
994
-		$size = 0;
995
-
996
-		/**
997
-		 * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
998
-		 * This bug is fixed in PHP 5.5.9 or before
999
-		 * See #8376
1000
-		 */
1001
-		$iterator->rewind();
1002
-		while ($iterator->valid()) {
1003
-			$path = $iterator->current();
1004
-			$relpath = substr($path, strlen($root) - 1);
1005
-			if (!$view->is_dir($relpath)) {
1006
-				$size += $view->filesize($relpath);
1007
-			}
1008
-			$iterator->next();
1009
-		}
1010
-		return $size;
1011
-	}
1012
-
1013
-	/**
1014
-	 * get current size of trash bin from a given user
1015
-	 *
1016
-	 * @param string $user user who owns the trash bin
1017
-	 * @return integer trash bin size
1018
-	 */
1019
-	private static function getTrashbinSize($user) {
1020
-		$view = new View('/' . $user);
1021
-		$fileInfo = $view->getFileInfo('/files_trashbin');
1022
-		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
1023
-	}
1024
-
1025
-	/**
1026
-	 * check if trash bin is empty for a given user
1027
-	 *
1028
-	 * @param string $user
1029
-	 * @return bool
1030
-	 */
1031
-	public static function isEmpty($user) {
1032
-		$view = new View('/' . $user . '/files_trashbin');
1033
-		if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
1034
-			while ($file = readdir($dh)) {
1035
-				if (!Filesystem::isIgnoredDir($file)) {
1036
-					return false;
1037
-				}
1038
-			}
1039
-		}
1040
-		return true;
1041
-	}
1042
-
1043
-	/**
1044
-	 * @param $path
1045
-	 * @return string
1046
-	 */
1047
-	public static function preview_icon($path) {
1048
-		return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_trashbin_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
1049
-	}
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
+        $userTrashbinSize = (int)$config->getUserValue($user, 'files_trashbin', 'trashbin_size', '-1');
712
+        if ($userTrashbinSize > -1) {
713
+            return $userTrashbinSize - $trashbinSize;
714
+        }
715
+        $systemTrashbinSize = (int)$config->getAppValue('files_trashbin', 'trashbin_size', '-1');
716
+        if ($systemTrashbinSize > -1) {
717
+            return $systemTrashbinSize - $trashbinSize;
718
+        }
719
+
720
+        $softQuota = true;
721
+        $userObject = \OC::$server->getUserManager()->get($user);
722
+        if (is_null($userObject)) {
723
+            return 0;
724
+        }
725
+        $quota = $userObject->getQuota();
726
+        if ($quota === null || $quota === 'none') {
727
+            $quota = Filesystem::free_space('/');
728
+            $softQuota = false;
729
+            // inf or unknown free space
730
+            if ($quota < 0) {
731
+                $quota = PHP_INT_MAX;
732
+            }
733
+        } else {
734
+            $quota = \OCP\Util::computerFileSize($quota);
735
+        }
736
+
737
+        // calculate available space for trash bin
738
+        // subtract size of files and current trash bin size from quota
739
+        if ($softQuota) {
740
+            $userFolder = \OC::$server->getUserFolder($user);
741
+            if (is_null($userFolder)) {
742
+                return 0;
743
+            }
744
+            $free = $quota - $userFolder->getSize(false); // remaining free space for user
745
+            if ($free > 0) {
746
+                $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
747
+            } else {
748
+                $availableSpace = $free - $trashbinSize;
749
+            }
750
+        } else {
751
+            $availableSpace = $quota;
752
+        }
753
+
754
+        return $availableSpace;
755
+    }
756
+
757
+    /**
758
+     * resize trash bin if necessary after a new file was added to Nextcloud
759
+     *
760
+     * @param string $user user id
761
+     */
762
+    public static function resizeTrash($user) {
763
+        $size = self::getTrashbinSize($user);
764
+
765
+        $freeSpace = self::calculateFreeSpace($size, $user);
766
+
767
+        if ($freeSpace < 0) {
768
+            self::scheduleExpire($user);
769
+        }
770
+    }
771
+
772
+    /**
773
+     * clean up the trash bin
774
+     *
775
+     * @param string $user
776
+     */
777
+    public static function expire($user) {
778
+        $trashBinSize = self::getTrashbinSize($user);
779
+        $availableSpace = self::calculateFreeSpace($trashBinSize, $user);
780
+
781
+        $dirContent = Helper::getTrashFiles('/', $user, 'mtime');
782
+
783
+        // delete all files older then $retention_obligation
784
+        [$delSize, $count] = self::deleteExpiredFiles($dirContent, $user);
785
+
786
+        $availableSpace += $delSize;
787
+
788
+        // delete files from trash until we meet the trash bin size limit again
789
+        self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
790
+    }
791
+
792
+    /**
793
+     * @param string $user
794
+     */
795
+    private static function scheduleExpire($user) {
796
+        // let the admin disable auto expire
797
+        /** @var Application $application */
798
+        $application = \OC::$server->query(Application::class);
799
+        $expiration = $application->getContainer()->query('Expiration');
800
+        if ($expiration->isEnabled()) {
801
+            \OC::$server->getCommandBus()->push(new Expire($user));
802
+        }
803
+    }
804
+
805
+    /**
806
+     * if the size limit for the trash bin is reached, we delete the oldest
807
+     * files in the trash bin until we meet the limit again
808
+     *
809
+     * @param array $files
810
+     * @param string $user
811
+     * @param int $availableSpace available disc space
812
+     * @return int size of deleted files
813
+     */
814
+    protected static function deleteFiles($files, $user, $availableSpace) {
815
+        /** @var Application $application */
816
+        $application = \OC::$server->query(Application::class);
817
+        $expiration = $application->getContainer()->query('Expiration');
818
+        $size = 0;
819
+
820
+        if ($availableSpace < 0) {
821
+            foreach ($files as $file) {
822
+                if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
823
+                    $tmp = self::delete($file['name'], $user, $file['mtime']);
824
+                    \OC::$server->getLogger()->info('remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', ['app' => 'files_trashbin']);
825
+                    $availableSpace += $tmp;
826
+                    $size += $tmp;
827
+                } else {
828
+                    break;
829
+                }
830
+            }
831
+        }
832
+        return $size;
833
+    }
834
+
835
+    /**
836
+     * delete files older then max storage time
837
+     *
838
+     * @param array $files list of files sorted by mtime
839
+     * @param string $user
840
+     * @return integer[] size of deleted files and number of deleted files
841
+     */
842
+    public static function deleteExpiredFiles($files, $user) {
843
+        /** @var Expiration $expiration */
844
+        $expiration = \OC::$server->query(Expiration::class);
845
+        $size = 0;
846
+        $count = 0;
847
+        foreach ($files as $file) {
848
+            $timestamp = $file['mtime'];
849
+            $filename = $file['name'];
850
+            if ($expiration->isExpired($timestamp)) {
851
+                try {
852
+                    $size += self::delete($filename, $user, $timestamp);
853
+                    $count++;
854
+                } catch (\OCP\Files\NotPermittedException $e) {
855
+                    \OC::$server->getLogger()->logException($e, ['app' => 'files_trashbin', 'level' => \OCP\ILogger::WARN, 'message' => 'Removing "' . $filename . '" from trashbin failed.']);
856
+                }
857
+                \OC::$server->getLogger()->info(
858
+                    'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
859
+                    ['app' => 'files_trashbin']
860
+                );
861
+            } else {
862
+                break;
863
+            }
864
+        }
865
+
866
+        return [$size, $count];
867
+    }
868
+
869
+    /**
870
+     * recursive copy to copy a whole directory
871
+     *
872
+     * @param string $source source path, relative to the users files directory
873
+     * @param string $destination destination path relative to the users root directoy
874
+     * @param View $view file view for the users root directory
875
+     * @return int
876
+     * @throws Exceptions\CopyRecursiveException
877
+     */
878
+    private static function copy_recursive($source, $destination, View $view) {
879
+        $size = 0;
880
+        if ($view->is_dir($source)) {
881
+            $view->mkdir($destination);
882
+            $view->touch($destination, $view->filemtime($source));
883
+            foreach ($view->getDirectoryContent($source) as $i) {
884
+                $pathDir = $source . '/' . $i['name'];
885
+                if ($view->is_dir($pathDir)) {
886
+                    $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
887
+                } else {
888
+                    $size += $view->filesize($pathDir);
889
+                    $result = $view->copy($pathDir, $destination . '/' . $i['name']);
890
+                    if (!$result) {
891
+                        throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
892
+                    }
893
+                    $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
894
+                }
895
+            }
896
+        } else {
897
+            $size += $view->filesize($source);
898
+            $result = $view->copy($source, $destination);
899
+            if (!$result) {
900
+                throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
901
+            }
902
+            $view->touch($destination, $view->filemtime($source));
903
+        }
904
+        return $size;
905
+    }
906
+
907
+    /**
908
+     * find all versions which belong to the file we want to restore
909
+     *
910
+     * @param string $filename name of the file which should be restored
911
+     * @param int $timestamp timestamp when the file was deleted
912
+     * @return array
913
+     */
914
+    private static function getVersionsFromTrash($filename, $timestamp, $user) {
915
+        $view = new View('/' . $user . '/files_trashbin/versions');
916
+        $versions = [];
917
+
918
+        //force rescan of versions, local storage may not have updated the cache
919
+        if (!self::$scannedVersions) {
920
+            /** @var \OC\Files\Storage\Storage $storage */
921
+            [$storage,] = $view->resolvePath('/');
922
+            $storage->getScanner()->scan('files_trashbin/versions');
923
+            self::$scannedVersions = true;
924
+        }
925
+
926
+        if ($timestamp) {
927
+            // fetch for old versions
928
+            $matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
929
+            $offset = -strlen($timestamp) - 2;
930
+        } else {
931
+            $matches = $view->searchRaw($filename . '.v%');
932
+        }
933
+
934
+        if (is_array($matches)) {
935
+            foreach ($matches as $ma) {
936
+                if ($timestamp) {
937
+                    $parts = explode('.v', substr($ma['path'], 0, $offset));
938
+                    $versions[] = end($parts);
939
+                } else {
940
+                    $parts = explode('.v', $ma);
941
+                    $versions[] = end($parts);
942
+                }
943
+            }
944
+        }
945
+        return $versions;
946
+    }
947
+
948
+    /**
949
+     * find unique extension for restored file if a file with the same name already exists
950
+     *
951
+     * @param string $location where the file should be restored
952
+     * @param string $filename name of the file
953
+     * @param View $view filesystem view relative to users root directory
954
+     * @return string with unique extension
955
+     */
956
+    private static function getUniqueFilename($location, $filename, View $view) {
957
+        $ext = pathinfo($filename, PATHINFO_EXTENSION);
958
+        $name = pathinfo($filename, PATHINFO_FILENAME);
959
+        $l = \OC::$server->getL10N('files_trashbin');
960
+
961
+        $location = '/' . trim($location, '/');
962
+
963
+        // if extension is not empty we set a dot in front of it
964
+        if ($ext !== '') {
965
+            $ext = '.' . $ext;
966
+        }
967
+
968
+        if ($view->file_exists('files' . $location . '/' . $filename)) {
969
+            $i = 2;
970
+            $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
971
+            while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
972
+                $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
973
+                $i++;
974
+            }
975
+
976
+            return $uniqueName;
977
+        }
978
+
979
+        return $filename;
980
+    }
981
+
982
+    /**
983
+     * get the size from a given root folder
984
+     *
985
+     * @param View $view file view on the root folder
986
+     * @return integer size of the folder
987
+     */
988
+    private static function calculateSize($view) {
989
+        $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
990
+        if (!file_exists($root)) {
991
+            return 0;
992
+        }
993
+        $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
994
+        $size = 0;
995
+
996
+        /**
997
+         * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
998
+         * This bug is fixed in PHP 5.5.9 or before
999
+         * See #8376
1000
+         */
1001
+        $iterator->rewind();
1002
+        while ($iterator->valid()) {
1003
+            $path = $iterator->current();
1004
+            $relpath = substr($path, strlen($root) - 1);
1005
+            if (!$view->is_dir($relpath)) {
1006
+                $size += $view->filesize($relpath);
1007
+            }
1008
+            $iterator->next();
1009
+        }
1010
+        return $size;
1011
+    }
1012
+
1013
+    /**
1014
+     * get current size of trash bin from a given user
1015
+     *
1016
+     * @param string $user user who owns the trash bin
1017
+     * @return integer trash bin size
1018
+     */
1019
+    private static function getTrashbinSize($user) {
1020
+        $view = new View('/' . $user);
1021
+        $fileInfo = $view->getFileInfo('/files_trashbin');
1022
+        return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
1023
+    }
1024
+
1025
+    /**
1026
+     * check if trash bin is empty for a given user
1027
+     *
1028
+     * @param string $user
1029
+     * @return bool
1030
+     */
1031
+    public static function isEmpty($user) {
1032
+        $view = new View('/' . $user . '/files_trashbin');
1033
+        if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
1034
+            while ($file = readdir($dh)) {
1035
+                if (!Filesystem::isIgnoredDir($file)) {
1036
+                    return false;
1037
+                }
1038
+            }
1039
+        }
1040
+        return true;
1041
+    }
1042
+
1043
+    /**
1044
+     * @param $path
1045
+     * @return string
1046
+     */
1047
+    public static function preview_icon($path) {
1048
+        return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_trashbin_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
1049
+    }
1050 1050
 }
Please login to merge, or discard this patch.
Spacing   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 		Filesystem::initMountPoints($uid);
108 108
 		if ($uid !== User::getUser()) {
109 109
 			$info = Filesystem::getFileInfo($filename);
110
-			$ownerView = new View('/' . $uid . '/files');
110
+			$ownerView = new View('/'.$uid.'/files');
111 111
 			try {
112 112
 				$filename = $ownerView->getPath($info['fileid']);
113 113
 			} catch (NotFoundException $e) {
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 	}
159 159
 
160 160
 	private static function setUpTrash($user) {
161
-		$view = new View('/' . $user);
161
+		$view = new View('/'.$user);
162 162
 		if (!$view->is_dir('files_trashbin')) {
163 163
 			$view->mkdir('files_trashbin');
164 164
 		}
@@ -193,8 +193,8 @@  discard block
 block discarded – undo
193 193
 
194 194
 		$view = new View('/');
195 195
 
196
-		$target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
197
-		$source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
196
+		$target = $user.'/files_trashbin/files/'.$targetFilename.'.d'.$timestamp;
197
+		$source = $owner.'/files_trashbin/files/'.$sourceFilename.'.d'.$timestamp;
198 198
 		$free = $view->free_space($target);
199 199
 		$isUnknownOrUnlimitedFreeSpace = $free < 0;
200 200
 		$isEnoughFreeSpaceLeft = $view->filesize($source) < $free;
@@ -233,9 +233,9 @@  discard block
 block discarded – undo
233 233
 			$ownerPath = $file_path;
234 234
 		}
235 235
 
236
-		$ownerView = new View('/' . $owner);
236
+		$ownerView = new View('/'.$owner);
237 237
 		// file has been deleted in between
238
-		if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) {
238
+		if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/'.$ownerPath)) {
239 239
 			return true;
240 240
 		}
241 241
 
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 		$lockingProvider = \OC::$server->getLockingProvider();
257 257
 
258 258
 		// disable proxy to prevent recursive calls
259
-		$trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
259
+		$trashPath = '/files_trashbin/files/'.$filename.'.d'.$timestamp;
260 260
 		$gotLock = false;
261 261
 
262 262
 		while (!$gotLock) {
@@ -272,12 +272,12 @@  discard block
 block discarded – undo
272 272
 
273 273
 				$timestamp = $timestamp + 1;
274 274
 
275
-				$trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
275
+				$trashPath = '/files_trashbin/files/'.$filename.'.d'.$timestamp;
276 276
 			}
277 277
 		}
278 278
 
279 279
 		/** @var \OC\Files\Storage\Storage $sourceStorage */
280
-		[$sourceStorage, $sourceInternalPath] = $ownerView->resolvePath('/files/' . $ownerPath);
280
+		[$sourceStorage, $sourceInternalPath] = $ownerView->resolvePath('/files/'.$ownerPath);
281 281
 
282 282
 
283 283
 		if ($trashStorage->file_exists($trashInternalPath)) {
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
 			if ($trashStorage->file_exists($trashInternalPath)) {
301 301
 				$trashStorage->unlink($trashInternalPath);
302 302
 			}
303
-			\OC::$server->getLogger()->error('Couldn\'t move ' . $file_path . ' to the trash bin', ['app' => 'files_trashbin']);
303
+			\OC::$server->getLogger()->error('Couldn\'t move '.$file_path.' to the trash bin', ['app' => 'files_trashbin']);
304 304
 		}
305 305
 
306 306
 		if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
@@ -322,7 +322,7 @@  discard block
 block discarded – undo
322 322
 				\OC::$server->getLogger()->error('trash bin database couldn\'t be updated', ['app' => 'files_trashbin']);
323 323
 			}
324 324
 			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', ['filePath' => Filesystem::normalizePath($file_path),
325
-				'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)]);
325
+				'trashPath' => Filesystem::normalizePath($filename.'.d'.$timestamp)]);
326 326
 
327 327
 			self::retainVersions($filename, $owner, $ownerPath, $timestamp);
328 328
 
@@ -357,17 +357,17 @@  discard block
 block discarded – undo
357 357
 			$user = User::getUser();
358 358
 			$rootView = new View('/');
359 359
 
360
-			if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
360
+			if ($rootView->is_dir($owner.'/files_versions/'.$ownerPath)) {
361 361
 				if ($owner !== $user) {
362
-					self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView);
362
+					self::copy_recursive($owner.'/files_versions/'.$ownerPath, $owner.'/files_trashbin/versions/'.basename($ownerPath).'.d'.$timestamp, $rootView);
363 363
 				}
364
-				self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
364
+				self::move($rootView, $owner.'/files_versions/'.$ownerPath, $user.'/files_trashbin/versions/'.$filename.'.d'.$timestamp);
365 365
 			} elseif ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
366 366
 				foreach ($versions as $v) {
367 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);
368
+						self::copy($rootView, $owner.'/files_versions'.$v['path'].'.v'.$v['version'], $owner.'/files_trashbin/versions/'.$v['name'].'.v'.$v['version'].'.d'.$timestamp);
369 369
 					}
370
-					self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
370
+					self::move($rootView, $owner.'/files_versions'.$v['path'].'.v'.$v['version'], $user.'/files_trashbin/versions/'.$filename.'.v'.$v['version'].'.d'.$timestamp);
371 371
 				}
372 372
 			}
373 373
 		}
@@ -429,18 +429,18 @@  discard block
 block discarded – undo
429 429
 	 */
430 430
 	public static function restore($file, $filename, $timestamp) {
431 431
 		$user = User::getUser();
432
-		$view = new View('/' . $user);
432
+		$view = new View('/'.$user);
433 433
 
434 434
 		$location = '';
435 435
 		if ($timestamp) {
436 436
 			$location = self::getLocation($user, $filename, $timestamp);
437 437
 			if ($location === false) {
438
-				\OC::$server->getLogger()->error('trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']);
438
+				\OC::$server->getLogger()->error('trash bin database inconsistent! ($user: '.$user.' $filename: '.$filename.', $timestamp: '.$timestamp.')', ['app' => 'files_trashbin']);
439 439
 			} else {
440 440
 				// if location no longer exists, restore file in the root directory
441 441
 				if ($location !== '/' &&
442
-					(!$view->is_dir('files/' . $location) ||
443
-						!$view->isCreatable('files/' . $location))
442
+					(!$view->is_dir('files/'.$location) ||
443
+						!$view->isCreatable('files/'.$location))
444 444
 				) {
445 445
 					$location = '';
446 446
 				}
@@ -450,8 +450,8 @@  discard block
 block discarded – undo
450 450
 		// we need a  extension in case a file/dir with the same name already exists
451 451
 		$uniqueFilename = self::getUniqueFilename($location, $filename, $view);
452 452
 
453
-		$source = Filesystem::normalizePath('files_trashbin/files/' . $file);
454
-		$target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
453
+		$source = Filesystem::normalizePath('files_trashbin/files/'.$file);
454
+		$target = Filesystem::normalizePath('files/'.$location.'/'.$uniqueFilename);
455 455
 		if (!$view->file_exists($source)) {
456 456
 			return false;
457 457
 		}
@@ -466,10 +466,10 @@  discard block
 block discarded – undo
466 466
 		// handle the restore result
467 467
 		if ($restoreResult) {
468 468
 			$fakeRoot = $view->getRoot();
469
-			$view->chroot('/' . $user . '/files');
470
-			$view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
469
+			$view->chroot('/'.$user.'/files');
470
+			$view->touch('/'.$location.'/'.$uniqueFilename, $mtime);
471 471
 			$view->chroot($fakeRoot);
472
-			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', ['filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
472
+			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', ['filePath' => Filesystem::normalizePath('/'.$location.'/'.$uniqueFilename),
473 473
 				'trashPath' => Filesystem::normalizePath($file)]);
474 474
 
475 475
 			self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
 			$user = User::getUser();
502 502
 			$rootView = new View('/');
503 503
 
504
-			$target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
504
+			$target = Filesystem::normalizePath('/'.$location.'/'.$uniqueFilename);
505 505
 
506 506
 			[$owner, $ownerPath] = self::getUidAndFilename($target);
507 507
 
@@ -516,14 +516,14 @@  discard block
 block discarded – undo
516 516
 				$versionedFile = $file;
517 517
 			}
518 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));
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 521
 			} elseif ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
522 522
 				foreach ($versions as $v) {
523 523
 					if ($timestamp) {
524
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
524
+						$rootView->rename($user.'/files_trashbin/versions/'.$versionedFile.'.v'.$v.'.d'.$timestamp, $owner.'/files_versions/'.$ownerPath.'.v'.$v);
525 525
 					} else {
526
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
526
+						$rootView->rename($user.'/files_trashbin/versions/'.$versionedFile.'.v'.$v, $owner.'/files_versions/'.$ownerPath.'.v'.$v);
527 527
 					}
528 528
 				}
529 529
 			}
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
 	public static function deleteAll() {
537 537
 		$user = User::getUser();
538 538
 		$userRoot = \OC::$server->getUserFolder($user)->getParent();
539
-		$view = new View('/' . $user);
539
+		$view = new View('/'.$user);
540 540
 		$fileInfos = $view->getDirectoryContent('files_trashbin/files');
541 541
 
542 542
 		try {
@@ -608,13 +608,13 @@  discard block
 block discarded – undo
608 608
 	 */
609 609
 	public static function delete($filename, $user, $timestamp = null) {
610 610
 		$userRoot = \OC::$server->getUserFolder($user)->getParent();
611
-		$view = new View('/' . $user);
611
+		$view = new View('/'.$user);
612 612
 		$size = 0;
613 613
 
614 614
 		if ($timestamp) {
615 615
 			$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
616 616
 			$query->execute([$user, $filename, $timestamp]);
617
-			$file = $filename . '.d' . $timestamp;
617
+			$file = $filename.'.d'.$timestamp;
618 618
 		} else {
619 619
 			$file = $filename;
620 620
 		}
@@ -622,20 +622,20 @@  discard block
 block discarded – undo
622 622
 		$size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
623 623
 
624 624
 		try {
625
-			$node = $userRoot->get('/files_trashbin/files/' . $file);
625
+			$node = $userRoot->get('/files_trashbin/files/'.$file);
626 626
 		} catch (NotFoundException $e) {
627 627
 			return $size;
628 628
 		}
629 629
 
630 630
 		if ($node instanceof Folder) {
631
-			$size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
631
+			$size += self::calculateSize(new View('/'.$user.'/files_trashbin/files/'.$file));
632 632
 		} elseif ($node instanceof File) {
633
-			$size += $view->filesize('/files_trashbin/files/' . $file);
633
+			$size += $view->filesize('/files_trashbin/files/'.$file);
634 634
 		}
635 635
 
636
-		self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
636
+		self::emitTrashbinPreDelete('/files_trashbin/files/'.$file);
637 637
 		$node->delete();
638
-		self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
638
+		self::emitTrashbinPostDelete('/files_trashbin/files/'.$file);
639 639
 
640 640
 		return $size;
641 641
 	}
@@ -651,17 +651,17 @@  discard block
 block discarded – undo
651 651
 	private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
652 652
 		$size = 0;
653 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);
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 657
 			} elseif ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
658 658
 				foreach ($versions as $v) {
659 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);
660
+						$size += $view->filesize('/files_trashbin/versions/'.$filename.'.v'.$v.'.d'.$timestamp);
661
+						$view->unlink('/files_trashbin/versions/'.$filename.'.v'.$v.'.d'.$timestamp);
662 662
 					} else {
663
-						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
664
-						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
663
+						$size += $view->filesize('/files_trashbin/versions/'.$filename.'.v'.$v);
664
+						$view->unlink('/files_trashbin/versions/'.$filename.'.v'.$v);
665 665
 					}
666 666
 				}
667 667
 			}
@@ -678,13 +678,13 @@  discard block
 block discarded – undo
678 678
 	 */
679 679
 	public static function file_exists($filename, $timestamp = null) {
680 680
 		$user = User::getUser();
681
-		$view = new View('/' . $user);
681
+		$view = new View('/'.$user);
682 682
 
683 683
 		if ($timestamp) {
684
-			$filename = $filename . '.d' . $timestamp;
684
+			$filename = $filename.'.d'.$timestamp;
685 685
 		}
686 686
 
687
-		$target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
687
+		$target = Filesystem::normalizePath('files_trashbin/files/'.$filename);
688 688
 		return $view->file_exists($target);
689 689
 	}
690 690
 
@@ -708,11 +708,11 @@  discard block
 block discarded – undo
708 708
 	 */
709 709
 	private static function calculateFreeSpace($trashbinSize, $user) {
710 710
 		$config = \OC::$server->getConfig();
711
-		$userTrashbinSize = (int)$config->getUserValue($user, 'files_trashbin', 'trashbin_size', '-1');
711
+		$userTrashbinSize = (int) $config->getUserValue($user, 'files_trashbin', 'trashbin_size', '-1');
712 712
 		if ($userTrashbinSize > -1) {
713 713
 			return $userTrashbinSize - $trashbinSize;
714 714
 		}
715
-		$systemTrashbinSize = (int)$config->getAppValue('files_trashbin', 'trashbin_size', '-1');
715
+		$systemTrashbinSize = (int) $config->getAppValue('files_trashbin', 'trashbin_size', '-1');
716 716
 		if ($systemTrashbinSize > -1) {
717 717
 			return $systemTrashbinSize - $trashbinSize;
718 718
 		}
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
 			foreach ($files as $file) {
822 822
 				if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
823 823
 					$tmp = self::delete($file['name'], $user, $file['mtime']);
824
-					\OC::$server->getLogger()->info('remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', ['app' => 'files_trashbin']);
824
+					\OC::$server->getLogger()->info('remove "'.$file['name'].'" ('.$tmp.'B) to meet the limit of trash bin size (50% of available quota)', ['app' => 'files_trashbin']);
825 825
 					$availableSpace += $tmp;
826 826
 					$size += $tmp;
827 827
 				} else {
@@ -852,10 +852,10 @@  discard block
 block discarded – undo
852 852
 					$size += self::delete($filename, $user, $timestamp);
853 853
 					$count++;
854 854
 				} catch (\OCP\Files\NotPermittedException $e) {
855
-					\OC::$server->getLogger()->logException($e, ['app' => 'files_trashbin', 'level' => \OCP\ILogger::WARN, 'message' => 'Removing "' . $filename . '" from trashbin failed.']);
855
+					\OC::$server->getLogger()->logException($e, ['app' => 'files_trashbin', 'level' => \OCP\ILogger::WARN, 'message' => 'Removing "'.$filename.'" from trashbin failed.']);
856 856
 				}
857 857
 				\OC::$server->getLogger()->info(
858
-					'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
858
+					'Remove "'.$filename.'" from trashbin because it exceeds max retention obligation term.',
859 859
 					['app' => 'files_trashbin']
860 860
 				);
861 861
 			} else {
@@ -881,16 +881,16 @@  discard block
 block discarded – undo
881 881
 			$view->mkdir($destination);
882 882
 			$view->touch($destination, $view->filemtime($source));
883 883
 			foreach ($view->getDirectoryContent($source) as $i) {
884
-				$pathDir = $source . '/' . $i['name'];
884
+				$pathDir = $source.'/'.$i['name'];
885 885
 				if ($view->is_dir($pathDir)) {
886
-					$size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
886
+					$size += self::copy_recursive($pathDir, $destination.'/'.$i['name'], $view);
887 887
 				} else {
888 888
 					$size += $view->filesize($pathDir);
889
-					$result = $view->copy($pathDir, $destination . '/' . $i['name']);
889
+					$result = $view->copy($pathDir, $destination.'/'.$i['name']);
890 890
 					if (!$result) {
891 891
 						throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
892 892
 					}
893
-					$view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
893
+					$view->touch($destination.'/'.$i['name'], $view->filemtime($pathDir));
894 894
 				}
895 895
 			}
896 896
 		} else {
@@ -912,23 +912,23 @@  discard block
 block discarded – undo
912 912
 	 * @return array
913 913
 	 */
914 914
 	private static function getVersionsFromTrash($filename, $timestamp, $user) {
915
-		$view = new View('/' . $user . '/files_trashbin/versions');
915
+		$view = new View('/'.$user.'/files_trashbin/versions');
916 916
 		$versions = [];
917 917
 
918 918
 		//force rescan of versions, local storage may not have updated the cache
919 919
 		if (!self::$scannedVersions) {
920 920
 			/** @var \OC\Files\Storage\Storage $storage */
921
-			[$storage,] = $view->resolvePath('/');
921
+			[$storage, ] = $view->resolvePath('/');
922 922
 			$storage->getScanner()->scan('files_trashbin/versions');
923 923
 			self::$scannedVersions = true;
924 924
 		}
925 925
 
926 926
 		if ($timestamp) {
927 927
 			// fetch for old versions
928
-			$matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
928
+			$matches = $view->searchRaw($filename.'.v%.d'.$timestamp);
929 929
 			$offset = -strlen($timestamp) - 2;
930 930
 		} else {
931
-			$matches = $view->searchRaw($filename . '.v%');
931
+			$matches = $view->searchRaw($filename.'.v%');
932 932
 		}
933 933
 
934 934
 		if (is_array($matches)) {
@@ -958,18 +958,18 @@  discard block
 block discarded – undo
958 958
 		$name = pathinfo($filename, PATHINFO_FILENAME);
959 959
 		$l = \OC::$server->getL10N('files_trashbin');
960 960
 
961
-		$location = '/' . trim($location, '/');
961
+		$location = '/'.trim($location, '/');
962 962
 
963 963
 		// if extension is not empty we set a dot in front of it
964 964
 		if ($ext !== '') {
965
-			$ext = '.' . $ext;
965
+			$ext = '.'.$ext;
966 966
 		}
967 967
 
968
-		if ($view->file_exists('files' . $location . '/' . $filename)) {
968
+		if ($view->file_exists('files'.$location.'/'.$filename)) {
969 969
 			$i = 2;
970
-			$uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
971
-			while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
972
-				$uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
970
+			$uniqueName = $name." (".$l->t("restored").")".$ext;
971
+			while ($view->file_exists('files'.$location.'/'.$uniqueName)) {
972
+				$uniqueName = $name." (".$l->t("restored")." ".$i.")".$ext;
973 973
 				$i++;
974 974
 			}
975 975
 
@@ -986,7 +986,7 @@  discard block
 block discarded – undo
986 986
 	 * @return integer size of the folder
987 987
 	 */
988 988
 	private static function calculateSize($view) {
989
-		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
989
+		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').$view->getAbsolutePath('');
990 990
 		if (!file_exists($root)) {
991 991
 			return 0;
992 992
 		}
@@ -1017,7 +1017,7 @@  discard block
 block discarded – undo
1017 1017
 	 * @return integer trash bin size
1018 1018
 	 */
1019 1019
 	private static function getTrashbinSize($user) {
1020
-		$view = new View('/' . $user);
1020
+		$view = new View('/'.$user);
1021 1021
 		$fileInfo = $view->getFileInfo('/files_trashbin');
1022 1022
 		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
1023 1023
 	}
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
 	 * @return bool
1030 1030
 	 */
1031 1031
 	public static function isEmpty($user) {
1032
-		$view = new View('/' . $user . '/files_trashbin');
1032
+		$view = new View('/'.$user.'/files_trashbin');
1033 1033
 		if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
1034 1034
 			while ($file = readdir($dh)) {
1035 1035
 				if (!Filesystem::isIgnoredDir($file)) {
Please login to merge, or discard this patch.