Trashbin.php 38 KB

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