1
0

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