1
0

Trashbin.php 38 KB

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