1<?php
2/**
3 * @copyright Copyright (c) 2016, ownCloud, Inc.
4 *
5 * @author Bart Visscher <bartv@thisnet.nl>
6 * @author Bastien Ho <bastienho@urbancube.fr>
7 * @author Bjoern Schiessle <bjoern@schiessle.org>
8 * @author Björn Schießle <bjoern@schiessle.org>
9 * @author Christoph Wurst <christoph@winzerhof-wurst.at>
10 * @author Daniel Kesselberg <mail@danielkesselberg.de>
11 * @author Florin Peter <github@florin-peter.de>
12 * @author Georg Ehrke <oc.list@georgehrke.com>
13 * @author Joas Schilling <coding@schilljs.com>
14 * @author Jörn Friedrich Dreyer <jfd@butonic.de>
15 * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
16 * @author Julius Härtl <jus@bitgrid.net>
17 * @author Lars Knickrehm <mail@lars-sh.de>
18 * @author Lukas Reschke <lukas@statuscode.ch>
19 * @author Morris Jobke <hey@morrisjobke.de>
20 * @author Qingping Hou <dave2008713@gmail.com>
21 * @author Robin Appelman <robin@icewind.nl>
22 * @author Robin McCorkell <robin@mccorkell.me.uk>
23 * @author Roeland Jago Douma <roeland@famdouma.nl>
24 * @author Sjors van der Pluijm <sjors@desjors.nl>
25 * @author Steven Bühner <buehner@me.com>
26 * @author Thomas Müller <thomas.mueller@tmit.eu>
27 * @author Victor Dubiniuk <dubiniuk@owncloud.com>
28 * @author Vincent Petry <vincent@nextcloud.com>
29 *
30 * @license AGPL-3.0
31 *
32 * This code is free software: you can redistribute it and/or modify
33 * it under the terms of the GNU Affero General Public License, version 3,
34 * as published by the Free Software Foundation.
35 *
36 * This program is distributed in the hope that it will be useful,
37 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 * GNU Affero General Public License for more details.
40 *
41 * You should have received a copy of the GNU Affero General Public License, version 3,
42 * along with this program. If not, see <http://www.gnu.org/licenses/>
43 *
44 */
45namespace OCA\Files_Trashbin;
46
47use OC_User;
48use OC\Files\Cache\Cache;
49use OC\Files\Cache\CacheEntry;
50use OC\Files\Cache\CacheQueryBuilder;
51use OC\Files\Filesystem;
52use OC\Files\ObjectStore\ObjectStoreStorage;
53use OC\Files\View;
54use OCA\Files_Trashbin\AppInfo\Application;
55use OCA\Files_Trashbin\Command\Expire;
56use OCP\AppFramework\Utility\ITimeFactory;
57use OCP\Files\File;
58use OCP\Files\Folder;
59use OCP\Files\NotFoundException;
60use OCP\Files\NotPermittedException;
61use OCP\Lock\ILockingProvider;
62use OCP\Lock\LockedException;
63
64class Trashbin {
65
66	// unit: percentage; 50% of available disk space/quota
67	public const DEFAULTMAXSIZE = 50;
68
69	/**
70	 * Whether versions have already be rescanned during this PHP request
71	 *
72	 * @var bool
73	 */
74	private static $scannedVersions = false;
75
76	/**
77	 * Ensure we don't need to scan the file during the move to trash
78	 * by triggering the scan in the pre-hook
79	 *
80	 * @param array $params
81	 */
82	public static function ensureFileScannedHook($params) {
83		try {
84			self::getUidAndFilename($params['path']);
85		} catch (NotFoundException $e) {
86			// nothing to scan for non existing files
87		}
88	}
89
90	/**
91	 * get the UID of the owner of the file and the path to the file relative to
92	 * owners files folder
93	 *
94	 * @param string $filename
95	 * @return array
96	 * @throws \OC\User\NoUserException
97	 */
98	public static function getUidAndFilename($filename) {
99		$uid = Filesystem::getOwner($filename);
100		$userManager = \OC::$server->getUserManager();
101		// if the user with the UID doesn't exists, e.g. because the UID points
102		// to a remote user with a federated cloud ID we use the current logged-in
103		// user. We need a valid local user to move the file to the right trash bin
104		if (!$userManager->userExists($uid)) {
105			$uid = OC_User::getUser();
106		}
107		if (!$uid) {
108			// no owner, usually because of share link from ext storage
109			return [null, null];
110		}
111		Filesystem::initMountPoints($uid);
112		if ($uid !== OC_User::getUser()) {
113			$info = Filesystem::getFileInfo($filename);
114			$ownerView = new View('/' . $uid . '/files');
115			try {
116				$filename = $ownerView->getPath($info['fileid']);
117			} catch (NotFoundException $e) {
118				$filename = null;
119			}
120		}
121		return [$uid, $filename];
122	}
123
124	/**
125	 * get original location of files for user
126	 *
127	 * @param string $user
128	 * @return array (filename => array (timestamp => original location))
129	 */
130	public static function getLocations($user) {
131		$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
132		$query->select('id', 'timestamp', 'location')
133			->from('files_trash')
134			->where($query->expr()->eq('user', $query->createNamedParameter($user)));
135		$result = $query->executeQuery();
136		$array = [];
137		while ($row = $result->fetch()) {
138			if (isset($array[$row['id']])) {
139				$array[$row['id']][$row['timestamp']] = $row['location'];
140			} else {
141				$array[$row['id']] = [$row['timestamp'] => $row['location']];
142			}
143		}
144		$result->closeCursor();
145		return $array;
146	}
147
148	/**
149	 * get original location of file
150	 *
151	 * @param string $user
152	 * @param string $filename
153	 * @param string $timestamp
154	 * @return string original location
155	 */
156	public static function getLocation($user, $filename, $timestamp) {
157		$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
158		$query->select('location')
159			->from('files_trash')
160			->where($query->expr()->eq('user', $query->createNamedParameter($user)))
161			->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
162			->andWhere($query->expr()->eq('timestamp', $query->createNamedParameter($timestamp)));
163
164		$result = $query->executeQuery();
165		$row = $result->fetch();
166		$result->closeCursor();
167
168		if (isset($row['location'])) {
169			return $row['location'];
170		} else {
171			return false;
172		}
173	}
174
175	private static function setUpTrash($user) {
176		$view = new View('/' . $user);
177		if (!$view->is_dir('files_trashbin')) {
178			$view->mkdir('files_trashbin');
179		}
180		if (!$view->is_dir('files_trashbin/files')) {
181			$view->mkdir('files_trashbin/files');
182		}
183		if (!$view->is_dir('files_trashbin/versions')) {
184			$view->mkdir('files_trashbin/versions');
185		}
186		if (!$view->is_dir('files_trashbin/keys')) {
187			$view->mkdir('files_trashbin/keys');
188		}
189	}
190
191
192	/**
193	 * copy file to owners trash
194	 *
195	 * @param string $sourcePath
196	 * @param string $owner
197	 * @param string $targetPath
198	 * @param $user
199	 * @param integer $timestamp
200	 */
201	private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) {
202		self::setUpTrash($owner);
203
204		$targetFilename = basename($targetPath);
205		$targetLocation = dirname($targetPath);
206
207		$sourceFilename = basename($sourcePath);
208
209		$view = new View('/');
210
211		$target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
212		$source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
213		$free = $view->free_space($target);
214		$isUnknownOrUnlimitedFreeSpace = $free < 0;
215		$isEnoughFreeSpaceLeft = $view->filesize($source) < $free;
216		if ($isUnknownOrUnlimitedFreeSpace || $isEnoughFreeSpaceLeft) {
217			self::copy_recursive($source, $target, $view);
218		}
219
220
221		if ($view->file_exists($target)) {
222			$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
223			$query->insert('files_trash')
224				->setValue('id', $query->createNamedParameter($targetFilename))
225				->setValue('timestamp', $query->createNamedParameter($timestamp))
226				->setValue('location', $query->createNamedParameter($targetLocation))
227				->setValue('user', $query->createNamedParameter($user));
228			$result = $query->executeStatement();
229			if (!$result) {
230				\OC::$server->getLogger()->error('trash bin database couldn\'t be updated for the files owner', ['app' => 'files_trashbin']);
231			}
232		}
233	}
234
235
236	/**
237	 * move file to the trash bin
238	 *
239	 * @param string $file_path path to the deleted file/directory relative to the files root directory
240	 * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
241	 *
242	 * @return bool
243	 */
244	public static function move2trash($file_path, $ownerOnly = false) {
245		// get the user for which the filesystem is setup
246		$root = Filesystem::getRoot();
247		[, $user] = explode('/', $root);
248		[$owner, $ownerPath] = self::getUidAndFilename($file_path);
249
250		// if no owner found (ex: ext storage + share link), will use the current user's trashbin then
251		if (is_null($owner)) {
252			$owner = $user;
253			$ownerPath = $file_path;
254		}
255
256		$ownerView = new View('/' . $owner);
257		// file has been deleted in between
258		if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) {
259			return true;
260		}
261
262		self::setUpTrash($user);
263		if ($owner !== $user) {
264			// also setup for owner
265			self::setUpTrash($owner);
266		}
267
268		$path_parts = pathinfo($ownerPath);
269
270		$filename = $path_parts['basename'];
271		$location = $path_parts['dirname'];
272		/** @var ITimeFactory $timeFactory */
273		$timeFactory = \OC::$server->query(ITimeFactory::class);
274		$timestamp = $timeFactory->getTime();
275
276		$lockingProvider = \OC::$server->getLockingProvider();
277
278		// disable proxy to prevent recursive calls
279		$trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
280		$gotLock = false;
281
282		while (!$gotLock) {
283			try {
284				/** @var \OC\Files\Storage\Storage $trashStorage */
285				[$trashStorage, $trashInternalPath] = $ownerView->resolvePath($trashPath);
286
287				$trashStorage->acquireLock($trashInternalPath, ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
288				$gotLock = true;
289			} catch (LockedException $e) {
290				// a file with the same name is being deleted concurrently
291				// nudge the timestamp a bit to resolve the conflict
292
293				$timestamp = $timestamp + 1;
294
295				$trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
296			}
297		}
298
299		/** @var \OC\Files\Storage\Storage $sourceStorage */
300		[$sourceStorage, $sourceInternalPath] = $ownerView->resolvePath('/files/' . $ownerPath);
301
302
303		if ($trashStorage->file_exists($trashInternalPath)) {
304			$trashStorage->unlink($trashInternalPath);
305		}
306
307		$config = \OC::$server->getConfig();
308		$systemTrashbinSize = (int)$config->getAppValue('files_trashbin', 'trashbin_size', '-1');
309		$userTrashbinSize = (int)$config->getUserValue($owner, 'files_trashbin', 'trashbin_size', '-1');
310		$configuredTrashbinSize = ($userTrashbinSize < 0) ? $systemTrashbinSize : $userTrashbinSize;
311		if ($configuredTrashbinSize >= 0 && $sourceStorage->filesize($sourceInternalPath) >= $configuredTrashbinSize) {
312			return false;
313		}
314
315		$trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
316
317		try {
318			$moveSuccessful = true;
319
320			// when moving within the same object store, the cache update done above is enough to move the file
321			if (!($trashStorage->instanceOfStorage(ObjectStoreStorage::class) && $trashStorage->getId() === $sourceStorage->getId())) {
322				$trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
323			}
324		} catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) {
325			$moveSuccessful = false;
326			if ($trashStorage->file_exists($trashInternalPath)) {
327				$trashStorage->unlink($trashInternalPath);
328			}
329			\OC::$server->getLogger()->error('Couldn\'t move ' . $file_path . ' to the trash bin', ['app' => 'files_trashbin']);
330		}
331
332		if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
333			if ($sourceStorage->is_dir($sourceInternalPath)) {
334				$sourceStorage->rmdir($sourceInternalPath);
335			} else {
336				$sourceStorage->unlink($sourceInternalPath);
337			}
338
339			if ($sourceStorage->file_exists($sourceInternalPath)) {
340				// undo the cache move
341				$sourceStorage->getUpdater()->renameFromStorage($trashStorage, $trashInternalPath, $sourceInternalPath);
342			} else {
343				$trashStorage->getUpdater()->remove($trashInternalPath);
344			}
345			return false;
346		}
347
348		if ($moveSuccessful) {
349			$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
350			$query->insert('files_trash')
351				->setValue('id', $query->createNamedParameter($filename))
352				->setValue('timestamp', $query->createNamedParameter($timestamp))
353				->setValue('location', $query->createNamedParameter($location))
354				->setValue('user', $query->createNamedParameter($owner));
355			$result = $query->executeStatement();
356			if (!$result) {
357				\OC::$server->getLogger()->error('trash bin database couldn\'t be updated', ['app' => 'files_trashbin']);
358			}
359			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', ['filePath' => Filesystem::normalizePath($file_path),
360				'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)]);
361
362			self::retainVersions($filename, $owner, $ownerPath, $timestamp);
363
364			// if owner !== user we need to also add a copy to the users trash
365			if ($user !== $owner && $ownerOnly === false) {
366				self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp);
367			}
368		}
369
370		$trashStorage->releaseLock($trashInternalPath, ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
371
372		self::scheduleExpire($user);
373
374		// if owner !== user we also need to update the owners trash size
375		if ($owner !== $user) {
376			self::scheduleExpire($owner);
377		}
378
379		return $moveSuccessful;
380	}
381
382	/**
383	 * Move file versions to trash so that they can be restored later
384	 *
385	 * @param string $filename of deleted file
386	 * @param string $owner owner user id
387	 * @param string $ownerPath path relative to the owner's home storage
388	 * @param integer $timestamp when the file was deleted
389	 */
390	private static function retainVersions($filename, $owner, $ownerPath, $timestamp) {
391		if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) {
392			$user = OC_User::getUser();
393			$rootView = new View('/');
394
395			if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
396				if ($owner !== $user) {
397					self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView);
398				}
399				self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
400			} elseif ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
401				foreach ($versions as $v) {
402					if ($owner !== $user) {
403						self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp);
404					}
405					self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
406				}
407			}
408		}
409	}
410
411	/**
412	 * Move a file or folder on storage level
413	 *
414	 * @param View $view
415	 * @param string $source
416	 * @param string $target
417	 * @return bool
418	 */
419	private static function move(View $view, $source, $target) {
420		/** @var \OC\Files\Storage\Storage $sourceStorage */
421		[$sourceStorage, $sourceInternalPath] = $view->resolvePath($source);
422		/** @var \OC\Files\Storage\Storage $targetStorage */
423		[$targetStorage, $targetInternalPath] = $view->resolvePath($target);
424		/** @var \OC\Files\Storage\Storage $ownerTrashStorage */
425
426		$result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
427		if ($result) {
428			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
429		}
430		return $result;
431	}
432
433	/**
434	 * Copy a file or folder on storage level
435	 *
436	 * @param View $view
437	 * @param string $source
438	 * @param string $target
439	 * @return bool
440	 */
441	private static function copy(View $view, $source, $target) {
442		/** @var \OC\Files\Storage\Storage $sourceStorage */
443		[$sourceStorage, $sourceInternalPath] = $view->resolvePath($source);
444		/** @var \OC\Files\Storage\Storage $targetStorage */
445		[$targetStorage, $targetInternalPath] = $view->resolvePath($target);
446		/** @var \OC\Files\Storage\Storage $ownerTrashStorage */
447
448		$result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
449		if ($result) {
450			$targetStorage->getUpdater()->update($targetInternalPath);
451		}
452		return $result;
453	}
454
455	/**
456	 * Restore a file or folder from trash bin
457	 *
458	 * @param string $file path to the deleted file/folder relative to "files_trashbin/files/",
459	 * including the timestamp suffix ".d12345678"
460	 * @param string $filename name of the file/folder
461	 * @param int $timestamp time when the file/folder was deleted
462	 *
463	 * @return bool true on success, false otherwise
464	 */
465	public static function restore($file, $filename, $timestamp) {
466		$user = OC_User::getUser();
467		$view = new View('/' . $user);
468
469		$location = '';
470		if ($timestamp) {
471			$location = self::getLocation($user, $filename, $timestamp);
472			if ($location === false) {
473				\OC::$server->getLogger()->error('trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']);
474			} else {
475				// if location no longer exists, restore file in the root directory
476				if ($location !== '/' &&
477					(!$view->is_dir('files/' . $location) ||
478						!$view->isCreatable('files/' . $location))
479				) {
480					$location = '';
481				}
482			}
483		}
484
485		// we need a  extension in case a file/dir with the same name already exists
486		$uniqueFilename = self::getUniqueFilename($location, $filename, $view);
487
488		$source = Filesystem::normalizePath('files_trashbin/files/' . $file);
489		$target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
490		if (!$view->file_exists($source)) {
491			return false;
492		}
493		$mtime = $view->filemtime($source);
494
495		// restore file
496		if (!$view->isCreatable(dirname($target))) {
497			throw new NotPermittedException("Can't restore trash item because the target folder is not writable");
498		}
499		$restoreResult = $view->rename($source, $target);
500
501		// handle the restore result
502		if ($restoreResult) {
503			$fakeRoot = $view->getRoot();
504			$view->chroot('/' . $user . '/files');
505			$view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
506			$view->chroot($fakeRoot);
507			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', ['filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
508				'trashPath' => Filesystem::normalizePath($file)]);
509
510			self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
511
512			if ($timestamp) {
513				$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
514				$query->delete('files_trash')
515					->where($query->expr()->eq('user', $query->createNamedParameter($user)))
516					->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
517					->andWhere($query->expr()->eq('timestamp', $query->createNamedParameter($timestamp)));
518				$query->executeStatement();
519			}
520
521			return true;
522		}
523
524		return false;
525	}
526
527	/**
528	 * restore versions from trash bin
529	 *
530	 * @param View $view file view
531	 * @param string $file complete path to file
532	 * @param string $filename name of file once it was deleted
533	 * @param string $uniqueFilename new file name to restore the file without overwriting existing files
534	 * @param string $location location if file
535	 * @param int $timestamp deletion time
536	 * @return false|null
537	 */
538	private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) {
539		if (\OCP\App::isEnabled('files_versions')) {
540			$user = OC_User::getUser();
541			$rootView = new View('/');
542
543			$target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
544
545			[$owner, $ownerPath] = self::getUidAndFilename($target);
546
547			// file has been deleted in between
548			if (empty($ownerPath)) {
549				return false;
550			}
551
552			if ($timestamp) {
553				$versionedFile = $filename;
554			} else {
555				$versionedFile = $file;
556			}
557
558			if ($view->is_dir('/files_trashbin/versions/' . $file)) {
559				$rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
560			} elseif ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
561				foreach ($versions as $v) {
562					if ($timestamp) {
563						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
564					} else {
565						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
566					}
567				}
568			}
569		}
570	}
571
572	/**
573	 * delete all files from the trash
574	 */
575	public static function deleteAll() {
576		$user = OC_User::getUser();
577		$userRoot = \OC::$server->getUserFolder($user)->getParent();
578		$view = new View('/' . $user);
579		$fileInfos = $view->getDirectoryContent('files_trashbin/files');
580
581		try {
582			$trash = $userRoot->get('files_trashbin');
583		} catch (NotFoundException $e) {
584			return false;
585		}
586
587		// Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
588		$filePaths = [];
589		foreach ($fileInfos as $fileInfo) {
590			$filePaths[] = $view->getRelativePath($fileInfo->getPath());
591		}
592		unset($fileInfos); // save memory
593
594		// Bulk PreDelete-Hook
595		\OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', ['paths' => $filePaths]);
596
597		// Single-File Hooks
598		foreach ($filePaths as $path) {
599			self::emitTrashbinPreDelete($path);
600		}
601
602		// actual file deletion
603		$trash->delete();
604
605		$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
606		$query->delete('files_trash')
607			->where($query->expr()->eq('user', $query->createNamedParameter($user)));
608		$query->executeStatement();
609
610		// Bulk PostDelete-Hook
611		\OC_Hook::emit('\OCP\Trashbin', 'deleteAll', ['paths' => $filePaths]);
612
613		// Single-File Hooks
614		foreach ($filePaths as $path) {
615			self::emitTrashbinPostDelete($path);
616		}
617
618		$trash = $userRoot->newFolder('files_trashbin');
619		$trash->newFolder('files');
620
621		return true;
622	}
623
624	/**
625	 * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
626	 *
627	 * @param string $path
628	 */
629	protected static function emitTrashbinPreDelete($path) {
630		\OC_Hook::emit('\OCP\Trashbin', 'preDelete', ['path' => $path]);
631	}
632
633	/**
634	 * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
635	 *
636	 * @param string $path
637	 */
638	protected static function emitTrashbinPostDelete($path) {
639		\OC_Hook::emit('\OCP\Trashbin', 'delete', ['path' => $path]);
640	}
641
642	/**
643	 * delete file from trash bin permanently
644	 *
645	 * @param string $filename path to the file
646	 * @param string $user
647	 * @param int $timestamp of deletion time
648	 *
649	 * @return int size of deleted files
650	 */
651	public static function delete($filename, $user, $timestamp = null) {
652		$userRoot = \OC::$server->getUserFolder($user)->getParent();
653		$view = new View('/' . $user);
654		$size = 0;
655
656		if ($timestamp) {
657			$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
658			$query->delete('files_trash')
659				->where($query->expr()->eq('user', $query->createNamedParameter($user)))
660				->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
661				->andWhere($query->expr()->eq('timestamp', $query->createNamedParameter($timestamp)));
662			$query->executeStatement();
663
664			$file = $filename . '.d' . $timestamp;
665		} else {
666			$file = $filename;
667		}
668
669		$size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
670
671		try {
672			$node = $userRoot->get('/files_trashbin/files/' . $file);
673		} catch (NotFoundException $e) {
674			return $size;
675		}
676
677		if ($node instanceof Folder) {
678			$size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
679		} elseif ($node instanceof File) {
680			$size += $view->filesize('/files_trashbin/files/' . $file);
681		}
682
683		self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
684		$node->delete();
685		self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
686
687		return $size;
688	}
689
690	/**
691	 * @param View $view
692	 * @param string $file
693	 * @param string $filename
694	 * @param integer|null $timestamp
695	 * @param string $user
696	 * @return int
697	 */
698	private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
699		$size = 0;
700		if (\OCP\App::isEnabled('files_versions')) {
701			if ($view->is_dir('files_trashbin/versions/' . $file)) {
702				$size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
703				$view->unlink('files_trashbin/versions/' . $file);
704			} elseif ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
705				foreach ($versions as $v) {
706					if ($timestamp) {
707						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
708						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
709					} else {
710						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
711						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
712					}
713				}
714			}
715		}
716		return $size;
717	}
718
719	/**
720	 * check to see whether a file exists in trashbin
721	 *
722	 * @param string $filename path to the file
723	 * @param int $timestamp of deletion time
724	 * @return bool true if file exists, otherwise false
725	 */
726	public static function file_exists($filename, $timestamp = null) {
727		$user = OC_User::getUser();
728		$view = new View('/' . $user);
729
730		if ($timestamp) {
731			$filename = $filename . '.d' . $timestamp;
732		}
733
734		$target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
735		return $view->file_exists($target);
736	}
737
738	/**
739	 * deletes used space for trash bin in db if user was deleted
740	 *
741	 * @param string $uid id of deleted user
742	 * @return bool result of db delete operation
743	 */
744	public static function deleteUser($uid) {
745		$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
746		$query->delete('files_trash')
747			->where($query->expr()->eq('user', $query->createNamedParameter($uid)));
748		return (bool) $query->executeStatement();
749	}
750
751	/**
752	 * calculate remaining free space for trash bin
753	 *
754	 * @param integer $trashbinSize current size of the trash bin
755	 * @param string $user
756	 * @return int available free space for trash bin
757	 */
758	private static function calculateFreeSpace($trashbinSize, $user) {
759		$config = \OC::$server->getConfig();
760		$userTrashbinSize = (int)$config->getUserValue($user, 'files_trashbin', 'trashbin_size', '-1');
761		if ($userTrashbinSize > -1) {
762			return $userTrashbinSize - $trashbinSize;
763		}
764		$systemTrashbinSize = (int)$config->getAppValue('files_trashbin', 'trashbin_size', '-1');
765		if ($systemTrashbinSize > -1) {
766			return $systemTrashbinSize - $trashbinSize;
767		}
768
769		$softQuota = true;
770		$userObject = \OC::$server->getUserManager()->get($user);
771		if (is_null($userObject)) {
772			return 0;
773		}
774		$quota = $userObject->getQuota();
775		if ($quota === null || $quota === 'none') {
776			$quota = Filesystem::free_space('/');
777			$softQuota = false;
778			// inf or unknown free space
779			if ($quota < 0) {
780				$quota = PHP_INT_MAX;
781			}
782		} else {
783			$quota = \OCP\Util::computerFileSize($quota);
784		}
785
786		// calculate available space for trash bin
787		// subtract size of files and current trash bin size from quota
788		if ($softQuota) {
789			$userFolder = \OC::$server->getUserFolder($user);
790			if (is_null($userFolder)) {
791				return 0;
792			}
793			$free = $quota - $userFolder->getSize(false); // remaining free space for user
794			if ($free > 0) {
795				$availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
796			} else {
797				$availableSpace = $free - $trashbinSize;
798			}
799		} else {
800			$availableSpace = $quota;
801		}
802
803		return $availableSpace;
804	}
805
806	/**
807	 * resize trash bin if necessary after a new file was added to Nextcloud
808	 *
809	 * @param string $user user id
810	 */
811	public static function resizeTrash($user) {
812		$size = self::getTrashbinSize($user);
813
814		$freeSpace = self::calculateFreeSpace($size, $user);
815
816		if ($freeSpace < 0) {
817			self::scheduleExpire($user);
818		}
819	}
820
821	/**
822	 * clean up the trash bin
823	 *
824	 * @param string $user
825	 */
826	public static function expire($user) {
827		$trashBinSize = self::getTrashbinSize($user);
828		$availableSpace = self::calculateFreeSpace($trashBinSize, $user);
829
830		$dirContent = Helper::getTrashFiles('/', $user, 'mtime');
831
832		// delete all files older then $retention_obligation
833		[$delSize, $count] = self::deleteExpiredFiles($dirContent, $user);
834
835		$availableSpace += $delSize;
836
837		// delete files from trash until we meet the trash bin size limit again
838		self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
839	}
840
841	/**
842	 * @param string $user
843	 */
844	private static function scheduleExpire($user) {
845		// let the admin disable auto expire
846		/** @var Application $application */
847		$application = \OC::$server->query(Application::class);
848		$expiration = $application->getContainer()->query('Expiration');
849		if ($expiration->isEnabled()) {
850			\OC::$server->getCommandBus()->push(new Expire($user));
851		}
852	}
853
854	/**
855	 * if the size limit for the trash bin is reached, we delete the oldest
856	 * files in the trash bin until we meet the limit again
857	 *
858	 * @param array $files
859	 * @param string $user
860	 * @param int $availableSpace available disc space
861	 * @return int size of deleted files
862	 */
863	protected static function deleteFiles($files, $user, $availableSpace) {
864		/** @var Application $application */
865		$application = \OC::$server->query(Application::class);
866		$expiration = $application->getContainer()->query('Expiration');
867		$size = 0;
868
869		if ($availableSpace < 0) {
870			foreach ($files as $file) {
871				if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
872					$tmp = self::delete($file['name'], $user, $file['mtime']);
873					\OC::$server->getLogger()->info('remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', ['app' => 'files_trashbin']);
874					$availableSpace += $tmp;
875					$size += $tmp;
876				} else {
877					break;
878				}
879			}
880		}
881		return $size;
882	}
883
884	/**
885	 * delete files older then max storage time
886	 *
887	 * @param array $files list of files sorted by mtime
888	 * @param string $user
889	 * @return integer[] size of deleted files and number of deleted files
890	 */
891	public static function deleteExpiredFiles($files, $user) {
892		/** @var Expiration $expiration */
893		$expiration = \OC::$server->query(Expiration::class);
894		$size = 0;
895		$count = 0;
896		foreach ($files as $file) {
897			$timestamp = $file['mtime'];
898			$filename = $file['name'];
899			if ($expiration->isExpired($timestamp)) {
900				try {
901					$size += self::delete($filename, $user, $timestamp);
902					$count++;
903				} catch (\OCP\Files\NotPermittedException $e) {
904					\OC::$server->getLogger()->logException($e, ['app' => 'files_trashbin', 'level' => \OCP\ILogger::WARN, 'message' => 'Removing "' . $filename . '" from trashbin failed.']);
905				}
906				\OC::$server->getLogger()->info(
907					'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
908					['app' => 'files_trashbin']
909				);
910			} else {
911				break;
912			}
913		}
914
915		return [$size, $count];
916	}
917
918	/**
919	 * recursive copy to copy a whole directory
920	 *
921	 * @param string $source source path, relative to the users files directory
922	 * @param string $destination destination path relative to the users root directoy
923	 * @param View $view file view for the users root directory
924	 * @return int
925	 * @throws Exceptions\CopyRecursiveException
926	 */
927	private static function copy_recursive($source, $destination, View $view) {
928		$size = 0;
929		if ($view->is_dir($source)) {
930			$view->mkdir($destination);
931			$view->touch($destination, $view->filemtime($source));
932			foreach ($view->getDirectoryContent($source) as $i) {
933				$pathDir = $source . '/' . $i['name'];
934				if ($view->is_dir($pathDir)) {
935					$size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
936				} else {
937					$size += $view->filesize($pathDir);
938					$result = $view->copy($pathDir, $destination . '/' . $i['name']);
939					if (!$result) {
940						throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
941					}
942					$view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
943				}
944			}
945		} else {
946			$size += $view->filesize($source);
947			$result = $view->copy($source, $destination);
948			if (!$result) {
949				throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
950			}
951			$view->touch($destination, $view->filemtime($source));
952		}
953		return $size;
954	}
955
956	/**
957	 * find all versions which belong to the file we want to restore
958	 *
959	 * @param string $filename name of the file which should be restored
960	 * @param int $timestamp timestamp when the file was deleted
961	 * @return array
962	 */
963	private static function getVersionsFromTrash($filename, $timestamp, $user) {
964		$view = new View('/' . $user . '/files_trashbin/versions');
965		$versions = [];
966
967		/** @var \OC\Files\Storage\Storage $storage */
968		[$storage,] = $view->resolvePath('/');
969
970		//force rescan of versions, local storage may not have updated the cache
971		if (!self::$scannedVersions) {
972			$storage->getScanner()->scan('files_trashbin/versions');
973			self::$scannedVersions = true;
974		}
975
976		$pattern = \OC::$server->getDatabaseConnection()->escapeLikeParameter(basename($filename));
977		if ($timestamp) {
978			// fetch for old versions
979			$escapedTimestamp = \OC::$server->getDatabaseConnection()->escapeLikeParameter($timestamp);
980			$pattern .= '.v%.d' . $escapedTimestamp;
981			$offset = -strlen($escapedTimestamp) - 2;
982		} else {
983			$pattern .= '.v%';
984		}
985
986		// Manually fetch all versions from the file cache to be able to filter them by their parent
987		$cache = $storage->getCache('');
988		$query = new CacheQueryBuilder(
989			\OC::$server->getDatabaseConnection(),
990			\OC::$server->getSystemConfig(),
991			\OC::$server->getLogger()
992		);
993		$normalizedParentPath = ltrim(Filesystem::normalizePath(dirname('files_trashbin/versions/'. $filename)), '/');
994		$parentId = $cache->getId($normalizedParentPath);
995		if ($parentId === -1) {
996			return [];
997		}
998
999		$query->selectFileCache()
1000			->whereStorageId($cache->getNumericStorageId())
1001			->andWhere($query->expr()->eq('parent', $query->createNamedParameter($parentId)))
1002			->andWhere($query->expr()->iLike('name', $query->createNamedParameter($pattern)));
1003
1004		$result = $query->executeQuery();
1005		$entries = $result->fetchAll();
1006		$result->closeCursor();
1007
1008		/** @var CacheEntry[] $matches */
1009		$matches = array_map(function (array $data) {
1010			return Cache::cacheEntryFromData($data, \OC::$server->getMimeTypeLoader());
1011		}, $entries);
1012
1013		foreach ($matches as $ma) {
1014			if ($timestamp) {
1015				$parts = explode('.v', substr($ma['path'], 0, $offset));
1016				$versions[] = end($parts);
1017			} else {
1018				$parts = explode('.v', $ma['path']);
1019				$versions[] = end($parts);
1020			}
1021		}
1022
1023		return $versions;
1024	}
1025
1026	/**
1027	 * find unique extension for restored file if a file with the same name already exists
1028	 *
1029	 * @param string $location where the file should be restored
1030	 * @param string $filename name of the file
1031	 * @param View $view filesystem view relative to users root directory
1032	 * @return string with unique extension
1033	 */
1034	private static function getUniqueFilename($location, $filename, View $view) {
1035		$ext = pathinfo($filename, PATHINFO_EXTENSION);
1036		$name = pathinfo($filename, PATHINFO_FILENAME);
1037		$l = \OC::$server->getL10N('files_trashbin');
1038
1039		$location = '/' . trim($location, '/');
1040
1041		// if extension is not empty we set a dot in front of it
1042		if ($ext !== '') {
1043			$ext = '.' . $ext;
1044		}
1045
1046		if ($view->file_exists('files' . $location . '/' . $filename)) {
1047			$i = 2;
1048			$uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
1049			while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
1050				$uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
1051				$i++;
1052			}
1053
1054			return $uniqueName;
1055		}
1056
1057		return $filename;
1058	}
1059
1060	/**
1061	 * get the size from a given root folder
1062	 *
1063	 * @param View $view file view on the root folder
1064	 * @return integer size of the folder
1065	 */
1066	private static function calculateSize($view) {
1067		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
1068		if (!file_exists($root)) {
1069			return 0;
1070		}
1071		$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
1072		$size = 0;
1073
1074		/**
1075		 * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
1076		 * This bug is fixed in PHP 5.5.9 or before
1077		 * See #8376
1078		 */
1079		$iterator->rewind();
1080		while ($iterator->valid()) {
1081			$path = $iterator->current();
1082			$relpath = substr($path, strlen($root) - 1);
1083			if (!$view->is_dir($relpath)) {
1084				$size += $view->filesize($relpath);
1085			}
1086			$iterator->next();
1087		}
1088		return $size;
1089	}
1090
1091	/**
1092	 * get current size of trash bin from a given user
1093	 *
1094	 * @param string $user user who owns the trash bin
1095	 * @return integer trash bin size
1096	 */
1097	private static function getTrashbinSize($user) {
1098		$view = new View('/' . $user);
1099		$fileInfo = $view->getFileInfo('/files_trashbin');
1100		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
1101	}
1102
1103	/**
1104	 * check if trash bin is empty for a given user
1105	 *
1106	 * @param string $user
1107	 * @return bool
1108	 */
1109	public static function isEmpty($user) {
1110		$view = new View('/' . $user . '/files_trashbin');
1111		if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
1112			while ($file = readdir($dh)) {
1113				if (!Filesystem::isIgnoredDir($file)) {
1114					return false;
1115				}
1116			}
1117		}
1118		return true;
1119	}
1120
1121	/**
1122	 * @param $path
1123	 * @return string
1124	 */
1125	public static function preview_icon($path) {
1126		return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_trashbin_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
1127	}
1128}
1129