1
0

Trashbin.php 38 KB

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