Trashbin.php 38 KB

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