Trashbin.php 38 KB

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