Trashbin.php 37 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\Lock\ILockingProvider;
  62. use OCP\Lock\LockedException;
  63. use Psr\Log\LoggerInterface;
  64. class Trashbin {
  65. // unit: percentage; 50% of available disk space/quota
  66. public const DEFAULTMAXSIZE = 50;
  67. /**
  68. * Whether versions have already be rescanned during this PHP request
  69. *
  70. * @var bool
  71. */
  72. private static $scannedVersions = false;
  73. /**
  74. * Ensure we don't need to scan the file during the move to trash
  75. * by triggering the scan in the pre-hook
  76. *
  77. * @param array $params
  78. */
  79. public static function ensureFileScannedHook($params) {
  80. try {
  81. self::getUidAndFilename($params['path']);
  82. } catch (NotFoundException $e) {
  83. // nothing to scan for non existing files
  84. }
  85. }
  86. /**
  87. * get the UID of the owner of the file and the path to the file relative to
  88. * owners files folder
  89. *
  90. * @param string $filename
  91. * @return array
  92. * @throws \OC\User\NoUserException
  93. */
  94. public static function getUidAndFilename($filename) {
  95. $uid = Filesystem::getOwner($filename);
  96. $userManager = \OC::$server->getUserManager();
  97. // if the user with the UID doesn't exists, e.g. because the UID points
  98. // to a remote user with a federated cloud ID we use the current logged-in
  99. // user. We need a valid local user to move the file to the right trash bin
  100. if (!$userManager->userExists($uid)) {
  101. $uid = OC_User::getUser();
  102. }
  103. if (!$uid) {
  104. // no owner, usually because of share link from ext storage
  105. return [null, null];
  106. }
  107. Filesystem::initMountPoints($uid);
  108. if ($uid !== OC_User::getUser()) {
  109. $info = Filesystem::getFileInfo($filename);
  110. $ownerView = new View('/' . $uid . '/files');
  111. try {
  112. $filename = $ownerView->getPath($info['fileid']);
  113. } catch (NotFoundException $e) {
  114. $filename = null;
  115. }
  116. }
  117. return [$uid, $filename];
  118. }
  119. /**
  120. * get original location of files for user
  121. *
  122. * @param string $user
  123. * @return array (filename => array (timestamp => original location))
  124. */
  125. public static function getLocations($user) {
  126. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  127. $query->select('id', 'timestamp', 'location')
  128. ->from('files_trash')
  129. ->where($query->expr()->eq('user', $query->createNamedParameter($user)));
  130. $result = $query->executeQuery();
  131. $array = [];
  132. while ($row = $result->fetch()) {
  133. if (isset($array[$row['id']])) {
  134. $array[$row['id']][$row['timestamp']] = $row['location'];
  135. } else {
  136. $array[$row['id']] = [$row['timestamp'] => $row['location']];
  137. }
  138. }
  139. $result->closeCursor();
  140. return $array;
  141. }
  142. /**
  143. * get original location of file
  144. *
  145. * @param string $user
  146. * @param string $filename
  147. * @param string $timestamp
  148. * @return string original location
  149. */
  150. public static function getLocation($user, $filename, $timestamp) {
  151. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  152. $query->select('location')
  153. ->from('files_trash')
  154. ->where($query->expr()->eq('user', $query->createNamedParameter($user)))
  155. ->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
  156. ->andWhere($query->expr()->eq('timestamp', $query->createNamedParameter($timestamp)));
  157. $result = $query->executeQuery();
  158. $row = $result->fetch();
  159. $result->closeCursor();
  160. if (isset($row['location'])) {
  161. return $row['location'];
  162. } else {
  163. return false;
  164. }
  165. }
  166. private static function setUpTrash($user) {
  167. $view = new View('/' . $user);
  168. if (!$view->is_dir('files_trashbin')) {
  169. $view->mkdir('files_trashbin');
  170. }
  171. if (!$view->is_dir('files_trashbin/files')) {
  172. $view->mkdir('files_trashbin/files');
  173. }
  174. if (!$view->is_dir('files_trashbin/versions')) {
  175. $view->mkdir('files_trashbin/versions');
  176. }
  177. if (!$view->is_dir('files_trashbin/keys')) {
  178. $view->mkdir('files_trashbin/keys');
  179. }
  180. }
  181. /**
  182. * copy file to owners trash
  183. *
  184. * @param string $sourcePath
  185. * @param string $owner
  186. * @param string $targetPath
  187. * @param $user
  188. * @param integer $timestamp
  189. */
  190. private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) {
  191. self::setUpTrash($owner);
  192. $targetFilename = basename($targetPath);
  193. $targetLocation = dirname($targetPath);
  194. $sourceFilename = basename($sourcePath);
  195. $view = new View('/');
  196. $target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
  197. $source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
  198. $free = $view->free_space($target);
  199. $isUnknownOrUnlimitedFreeSpace = $free < 0;
  200. $isEnoughFreeSpaceLeft = $view->filesize($source) < $free;
  201. if ($isUnknownOrUnlimitedFreeSpace || $isEnoughFreeSpaceLeft) {
  202. self::copy_recursive($source, $target, $view);
  203. }
  204. if ($view->file_exists($target)) {
  205. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  206. $query->insert('files_trash')
  207. ->setValue('id', $query->createNamedParameter($targetFilename))
  208. ->setValue('timestamp', $query->createNamedParameter($timestamp))
  209. ->setValue('location', $query->createNamedParameter($targetLocation))
  210. ->setValue('user', $query->createNamedParameter($user));
  211. $result = $query->executeStatement();
  212. if (!$result) {
  213. \OC::$server->get(LoggerInterface::class)->error('trash bin database couldn\'t be updated for the files owner', ['app' => 'files_trashbin']);
  214. }
  215. }
  216. }
  217. /**
  218. * move file to the trash bin
  219. *
  220. * @param string $file_path path to the deleted file/directory relative to the files root directory
  221. * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
  222. *
  223. * @return bool
  224. */
  225. public static function move2trash($file_path, $ownerOnly = false) {
  226. // get the user for which the filesystem is setup
  227. $root = Filesystem::getRoot();
  228. [, $user] = explode('/', $root);
  229. [$owner, $ownerPath] = self::getUidAndFilename($file_path);
  230. // if no owner found (ex: ext storage + share link), will use the current user's trashbin then
  231. if (is_null($owner)) {
  232. $owner = $user;
  233. $ownerPath = $file_path;
  234. }
  235. $ownerView = new View('/' . $owner);
  236. // file has been deleted in between
  237. if (is_null($ownerPath) || $ownerPath === '') {
  238. return true;
  239. }
  240. $sourceInfo = $ownerView->getFileInfo('/files/' . $ownerPath);
  241. if ($sourceInfo === false) {
  242. return true;
  243. }
  244. self::setUpTrash($user);
  245. if ($owner !== $user) {
  246. // also setup for owner
  247. self::setUpTrash($owner);
  248. }
  249. $path_parts = pathinfo($ownerPath);
  250. $filename = $path_parts['basename'];
  251. $location = $path_parts['dirname'];
  252. /** @var ITimeFactory $timeFactory */
  253. $timeFactory = \OC::$server->query(ITimeFactory::class);
  254. $timestamp = $timeFactory->getTime();
  255. $lockingProvider = \OC::$server->getLockingProvider();
  256. // disable proxy to prevent recursive calls
  257. $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
  258. $gotLock = false;
  259. while (!$gotLock) {
  260. try {
  261. /** @var \OC\Files\Storage\Storage $trashStorage */
  262. [$trashStorage, $trashInternalPath] = $ownerView->resolvePath($trashPath);
  263. $trashStorage->acquireLock($trashInternalPath, ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  264. $gotLock = true;
  265. } catch (LockedException $e) {
  266. // a file with the same name is being deleted concurrently
  267. // nudge the timestamp a bit to resolve the conflict
  268. $timestamp = $timestamp + 1;
  269. $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
  270. }
  271. }
  272. $sourceStorage = $sourceInfo->getStorage();
  273. $sourceInternalPath = $sourceInfo->getInternalPath();
  274. if ($trashStorage->file_exists($trashInternalPath)) {
  275. $trashStorage->unlink($trashInternalPath);
  276. }
  277. $config = \OC::$server->getConfig();
  278. $systemTrashbinSize = (int)$config->getAppValue('files_trashbin', 'trashbin_size', '-1');
  279. $userTrashbinSize = (int)$config->getUserValue($owner, 'files_trashbin', 'trashbin_size', '-1');
  280. $configuredTrashbinSize = ($userTrashbinSize < 0) ? $systemTrashbinSize : $userTrashbinSize;
  281. if ($configuredTrashbinSize >= 0 && $sourceInfo->getSize() >= $configuredTrashbinSize) {
  282. return false;
  283. }
  284. $trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
  285. try {
  286. $moveSuccessful = true;
  287. // when moving within the same object store, the cache update done above is enough to move the file
  288. if (!($trashStorage->instanceOfStorage(ObjectStoreStorage::class) && $trashStorage->getId() === $sourceStorage->getId())) {
  289. $trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
  290. }
  291. } catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) {
  292. $moveSuccessful = false;
  293. if ($trashStorage->file_exists($trashInternalPath)) {
  294. $trashStorage->unlink($trashInternalPath);
  295. }
  296. \OC::$server->get(LoggerInterface::class)->error('Couldn\'t move ' . $file_path . ' to the trash bin', ['app' => 'files_trashbin']);
  297. }
  298. if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
  299. if ($sourceStorage->is_dir($sourceInternalPath)) {
  300. $sourceStorage->rmdir($sourceInternalPath);
  301. } else {
  302. $sourceStorage->unlink($sourceInternalPath);
  303. }
  304. if ($sourceStorage->file_exists($sourceInternalPath)) {
  305. // undo the cache move
  306. $sourceStorage->getUpdater()->renameFromStorage($trashStorage, $trashInternalPath, $sourceInternalPath);
  307. } else {
  308. $trashStorage->getUpdater()->remove($trashInternalPath);
  309. }
  310. return false;
  311. }
  312. if ($moveSuccessful) {
  313. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  314. $query->insert('files_trash')
  315. ->setValue('id', $query->createNamedParameter($filename))
  316. ->setValue('timestamp', $query->createNamedParameter($timestamp))
  317. ->setValue('location', $query->createNamedParameter($location))
  318. ->setValue('user', $query->createNamedParameter($owner));
  319. $result = $query->executeStatement();
  320. if (!$result) {
  321. \OC::$server->get(LoggerInterface::class)->error('trash bin database couldn\'t be updated', ['app' => 'files_trashbin']);
  322. }
  323. \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', ['filePath' => Filesystem::normalizePath($file_path),
  324. 'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)]);
  325. self::retainVersions($filename, $owner, $ownerPath, $timestamp);
  326. // if owner !== user we need to also add a copy to the users trash
  327. if ($user !== $owner && $ownerOnly === false) {
  328. self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp);
  329. }
  330. }
  331. $trashStorage->releaseLock($trashInternalPath, ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  332. self::scheduleExpire($user);
  333. // if owner !== user we also need to update the owners trash size
  334. if ($owner !== $user) {
  335. self::scheduleExpire($owner);
  336. }
  337. return $moveSuccessful;
  338. }
  339. /**
  340. * Move file versions to trash so that they can be restored later
  341. *
  342. * @param string $filename of deleted file
  343. * @param string $owner owner user id
  344. * @param string $ownerPath path relative to the owner's home storage
  345. * @param integer $timestamp when the file was deleted
  346. */
  347. private static function retainVersions($filename, $owner, $ownerPath, $timestamp) {
  348. if (\OCP\Server::get(IAppManager::class)->isEnabledForUser('files_versions') && !empty($ownerPath)) {
  349. $user = OC_User::getUser();
  350. $rootView = new View('/');
  351. if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
  352. if ($owner !== $user) {
  353. self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView);
  354. }
  355. self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
  356. } elseif ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
  357. foreach ($versions as $v) {
  358. if ($owner !== $user) {
  359. self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp);
  360. }
  361. self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
  362. }
  363. }
  364. }
  365. }
  366. /**
  367. * Move a file or folder on storage level
  368. *
  369. * @param View $view
  370. * @param string $source
  371. * @param string $target
  372. * @return bool
  373. */
  374. private static function move(View $view, $source, $target) {
  375. /** @var \OC\Files\Storage\Storage $sourceStorage */
  376. [$sourceStorage, $sourceInternalPath] = $view->resolvePath($source);
  377. /** @var \OC\Files\Storage\Storage $targetStorage */
  378. [$targetStorage, $targetInternalPath] = $view->resolvePath($target);
  379. /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
  380. $result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  381. if ($result) {
  382. $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  383. }
  384. return $result;
  385. }
  386. /**
  387. * Copy a file or folder on storage level
  388. *
  389. * @param View $view
  390. * @param string $source
  391. * @param string $target
  392. * @return bool
  393. */
  394. private static function copy(View $view, $source, $target) {
  395. /** @var \OC\Files\Storage\Storage $sourceStorage */
  396. [$sourceStorage, $sourceInternalPath] = $view->resolvePath($source);
  397. /** @var \OC\Files\Storage\Storage $targetStorage */
  398. [$targetStorage, $targetInternalPath] = $view->resolvePath($target);
  399. /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
  400. $result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  401. if ($result) {
  402. $targetStorage->getUpdater()->update($targetInternalPath);
  403. }
  404. return $result;
  405. }
  406. /**
  407. * Restore a file or folder from trash bin
  408. *
  409. * @param string $file path to the deleted file/folder relative to "files_trashbin/files/",
  410. * including the timestamp suffix ".d12345678"
  411. * @param string $filename name of the file/folder
  412. * @param int $timestamp time when the file/folder was deleted
  413. *
  414. * @return bool true on success, false otherwise
  415. */
  416. public static function restore($file, $filename, $timestamp) {
  417. $user = OC_User::getUser();
  418. $view = new View('/' . $user);
  419. $location = '';
  420. if ($timestamp) {
  421. $location = self::getLocation($user, $filename, $timestamp);
  422. if ($location === false) {
  423. \OC::$server->get(LoggerInterface::class)->error('trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', ['app' => 'files_trashbin']);
  424. } else {
  425. // if location no longer exists, restore file in the root directory
  426. if ($location !== '/' &&
  427. (!$view->is_dir('files/' . $location) ||
  428. !$view->isCreatable('files/' . $location))
  429. ) {
  430. $location = '';
  431. }
  432. }
  433. }
  434. // we need a extension in case a file/dir with the same name already exists
  435. $uniqueFilename = self::getUniqueFilename($location, $filename, $view);
  436. $source = Filesystem::normalizePath('files_trashbin/files/' . $file);
  437. $target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
  438. if (!$view->file_exists($source)) {
  439. return false;
  440. }
  441. $mtime = $view->filemtime($source);
  442. // restore file
  443. if (!$view->isCreatable(dirname($target))) {
  444. throw new NotPermittedException("Can't restore trash item because the target folder is not writable");
  445. }
  446. $restoreResult = $view->rename($source, $target);
  447. // handle the restore result
  448. if ($restoreResult) {
  449. $fakeRoot = $view->getRoot();
  450. $view->chroot('/' . $user . '/files');
  451. $view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
  452. $view->chroot($fakeRoot);
  453. \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', ['filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
  454. 'trashPath' => Filesystem::normalizePath($file)]);
  455. self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
  456. if ($timestamp) {
  457. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  458. $query->delete('files_trash')
  459. ->where($query->expr()->eq('user', $query->createNamedParameter($user)))
  460. ->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
  461. ->andWhere($query->expr()->eq('timestamp', $query->createNamedParameter($timestamp)));
  462. $query->executeStatement();
  463. }
  464. return true;
  465. }
  466. return false;
  467. }
  468. /**
  469. * restore versions from trash bin
  470. *
  471. * @param View $view file view
  472. * @param string $file complete path to file
  473. * @param string $filename name of file once it was deleted
  474. * @param string $uniqueFilename new file name to restore the file without overwriting existing files
  475. * @param string $location location if file
  476. * @param int $timestamp deletion time
  477. * @return false|null
  478. */
  479. private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) {
  480. if (\OCP\Server::get(IAppManager::class)->isEnabledForUser('files_versions')) {
  481. $user = OC_User::getUser();
  482. $rootView = new View('/');
  483. $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
  484. [$owner, $ownerPath] = self::getUidAndFilename($target);
  485. // file has been deleted in between
  486. if (empty($ownerPath)) {
  487. return false;
  488. }
  489. if ($timestamp) {
  490. $versionedFile = $filename;
  491. } else {
  492. $versionedFile = $file;
  493. }
  494. if ($view->is_dir('/files_trashbin/versions/' . $file)) {
  495. $rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
  496. } elseif ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
  497. foreach ($versions as $v) {
  498. if ($timestamp) {
  499. $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
  500. } else {
  501. $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
  502. }
  503. }
  504. }
  505. }
  506. }
  507. /**
  508. * delete all files from the trash
  509. */
  510. public static function deleteAll() {
  511. $user = OC_User::getUser();
  512. $userRoot = \OC::$server->getUserFolder($user)->getParent();
  513. $view = new View('/' . $user);
  514. $fileInfos = $view->getDirectoryContent('files_trashbin/files');
  515. try {
  516. $trash = $userRoot->get('files_trashbin');
  517. } catch (NotFoundException $e) {
  518. return false;
  519. }
  520. // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
  521. $filePaths = [];
  522. foreach ($fileInfos as $fileInfo) {
  523. $filePaths[] = $view->getRelativePath($fileInfo->getPath());
  524. }
  525. unset($fileInfos); // save memory
  526. // Bulk PreDelete-Hook
  527. \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', ['paths' => $filePaths]);
  528. // Single-File Hooks
  529. foreach ($filePaths as $path) {
  530. self::emitTrashbinPreDelete($path);
  531. }
  532. // actual file deletion
  533. $trash->delete();
  534. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  535. $query->delete('files_trash')
  536. ->where($query->expr()->eq('user', $query->createNamedParameter($user)));
  537. $query->executeStatement();
  538. // Bulk PostDelete-Hook
  539. \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', ['paths' => $filePaths]);
  540. // Single-File Hooks
  541. foreach ($filePaths as $path) {
  542. self::emitTrashbinPostDelete($path);
  543. }
  544. $trash = $userRoot->newFolder('files_trashbin');
  545. $trash->newFolder('files');
  546. return true;
  547. }
  548. /**
  549. * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
  550. *
  551. * @param string $path
  552. */
  553. protected static function emitTrashbinPreDelete($path) {
  554. \OC_Hook::emit('\OCP\Trashbin', 'preDelete', ['path' => $path]);
  555. }
  556. /**
  557. * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
  558. *
  559. * @param string $path
  560. */
  561. protected static function emitTrashbinPostDelete($path) {
  562. \OC_Hook::emit('\OCP\Trashbin', 'delete', ['path' => $path]);
  563. }
  564. /**
  565. * delete file from trash bin permanently
  566. *
  567. * @param string $filename path to the file
  568. * @param string $user
  569. * @param int $timestamp of deletion time
  570. *
  571. * @return int size of deleted files
  572. */
  573. public static function delete($filename, $user, $timestamp = null) {
  574. $userRoot = \OC::$server->getUserFolder($user)->getParent();
  575. $view = new View('/' . $user);
  576. $size = 0;
  577. if ($timestamp) {
  578. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  579. $query->delete('files_trash')
  580. ->where($query->expr()->eq('user', $query->createNamedParameter($user)))
  581. ->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
  582. ->andWhere($query->expr()->eq('timestamp', $query->createNamedParameter($timestamp)));
  583. $query->executeStatement();
  584. $file = $filename . '.d' . $timestamp;
  585. } else {
  586. $file = $filename;
  587. }
  588. $size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
  589. try {
  590. $node = $userRoot->get('/files_trashbin/files/' . $file);
  591. } catch (NotFoundException $e) {
  592. return $size;
  593. }
  594. if ($node instanceof Folder) {
  595. $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
  596. } elseif ($node instanceof File) {
  597. $size += $view->filesize('/files_trashbin/files/' . $file);
  598. }
  599. self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
  600. $node->delete();
  601. self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
  602. return $size;
  603. }
  604. /**
  605. * @param View $view
  606. * @param string $file
  607. * @param string $filename
  608. * @param integer|null $timestamp
  609. * @param string $user
  610. * @return int
  611. */
  612. private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
  613. $size = 0;
  614. if (\OCP\Server::get(IAppManager::class)->isEnabledForUser('files_versions')) {
  615. if ($view->is_dir('files_trashbin/versions/' . $file)) {
  616. $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
  617. $view->unlink('files_trashbin/versions/' . $file);
  618. } elseif ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
  619. foreach ($versions as $v) {
  620. if ($timestamp) {
  621. $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
  622. $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
  623. } else {
  624. $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
  625. $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
  626. }
  627. }
  628. }
  629. }
  630. return $size;
  631. }
  632. /**
  633. * check to see whether a file exists in trashbin
  634. *
  635. * @param string $filename path to the file
  636. * @param int $timestamp of deletion time
  637. * @return bool true if file exists, otherwise false
  638. */
  639. public static function file_exists($filename, $timestamp = null) {
  640. $user = OC_User::getUser();
  641. $view = new View('/' . $user);
  642. if ($timestamp) {
  643. $filename = $filename . '.d' . $timestamp;
  644. }
  645. $target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
  646. return $view->file_exists($target);
  647. }
  648. /**
  649. * deletes used space for trash bin in db if user was deleted
  650. *
  651. * @param string $uid id of deleted user
  652. * @return bool result of db delete operation
  653. */
  654. public static function deleteUser($uid) {
  655. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  656. $query->delete('files_trash')
  657. ->where($query->expr()->eq('user', $query->createNamedParameter($uid)));
  658. return (bool) $query->executeStatement();
  659. }
  660. /**
  661. * calculate remaining free space for trash bin
  662. *
  663. * @param integer $trashbinSize current size of the trash bin
  664. * @param string $user
  665. * @return int available free space for trash bin
  666. */
  667. private static function calculateFreeSpace($trashbinSize, $user) {
  668. $config = \OC::$server->getConfig();
  669. $userTrashbinSize = (int)$config->getUserValue($user, 'files_trashbin', 'trashbin_size', '-1');
  670. if ($userTrashbinSize > -1) {
  671. return $userTrashbinSize - $trashbinSize;
  672. }
  673. $systemTrashbinSize = (int)$config->getAppValue('files_trashbin', 'trashbin_size', '-1');
  674. if ($systemTrashbinSize > -1) {
  675. return $systemTrashbinSize - $trashbinSize;
  676. }
  677. $softQuota = true;
  678. $userObject = \OC::$server->getUserManager()->get($user);
  679. if (is_null($userObject)) {
  680. return 0;
  681. }
  682. $quota = $userObject->getQuota();
  683. if ($quota === null || $quota === 'none') {
  684. $quota = Filesystem::free_space('/');
  685. $softQuota = false;
  686. // inf or unknown free space
  687. if ($quota < 0) {
  688. $quota = PHP_INT_MAX;
  689. }
  690. } else {
  691. $quota = \OCP\Util::computerFileSize($quota);
  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 (int)$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 $availableSpace available disc space
  757. * @return int size of deleted files
  758. */
  759. protected static function deleteFiles($files, $user, $availableSpace) {
  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 integer[] 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
  822. * @throws Exceptions\CopyRecursiveException
  823. */
  824. private static function copy_recursive($source, $destination, View $view) {
  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. * @return array
  858. */
  859. private static function getVersionsFromTrash($filename, $timestamp, $user) {
  860. $view = new View('/' . $user . '/files_trashbin/versions');
  861. $versions = [];
  862. /** @var \OC\Files\Storage\Storage $storage */
  863. [$storage,] = $view->resolvePath('/');
  864. //force rescan of versions, local storage may not have updated the cache
  865. $waitstart = time();
  866. while (!self::$scannedVersions) {
  867. try {
  868. $storage->getScanner()->scan('files_trashbin/versions');
  869. self::$scannedVersions = true;
  870. } catch (LockedException $e) {
  871. /* a concurrent remove/restore from trash occurred,
  872. * retry with a maximum wait time of approx. 15 seconds
  873. */
  874. if (time() - $waitstart > 15) {
  875. throw $e;
  876. }
  877. usleep(50000 + rand(0, 10000));
  878. }
  879. }
  880. $pattern = \OC::$server->getDatabaseConnection()->escapeLikeParameter(basename($filename));
  881. if ($timestamp) {
  882. // fetch for old versions
  883. $escapedTimestamp = \OC::$server->getDatabaseConnection()->escapeLikeParameter($timestamp);
  884. $pattern .= '.v%.d' . $escapedTimestamp;
  885. $offset = -strlen($escapedTimestamp) - 2;
  886. } else {
  887. $pattern .= '.v%';
  888. }
  889. // Manually fetch all versions from the file cache to be able to filter them by their parent
  890. $cache = $storage->getCache('');
  891. $query = new CacheQueryBuilder(
  892. \OC::$server->getDatabaseConnection(),
  893. \OC::$server->getSystemConfig(),
  894. \OC::$server->get(LoggerInterface::class)
  895. );
  896. $normalizedParentPath = ltrim(Filesystem::normalizePath(dirname('files_trashbin/versions/'. $filename)), '/');
  897. $parentId = $cache->getId($normalizedParentPath);
  898. if ($parentId === -1) {
  899. return [];
  900. }
  901. $query->selectFileCache()
  902. ->whereStorageId($cache->getNumericStorageId())
  903. ->andWhere($query->expr()->eq('parent', $query->createNamedParameter($parentId)))
  904. ->andWhere($query->expr()->iLike('name', $query->createNamedParameter($pattern)));
  905. $result = $query->executeQuery();
  906. $entries = $result->fetchAll();
  907. $result->closeCursor();
  908. /** @var CacheEntry[] $matches */
  909. $matches = array_map(function (array $data) {
  910. return Cache::cacheEntryFromData($data, \OC::$server->getMimeTypeLoader());
  911. }, $entries);
  912. foreach ($matches as $ma) {
  913. if ($timestamp) {
  914. $parts = explode('.v', substr($ma['path'], 0, $offset));
  915. $versions[] = end($parts);
  916. } else {
  917. $parts = explode('.v', $ma['path']);
  918. $versions[] = end($parts);
  919. }
  920. }
  921. return $versions;
  922. }
  923. /**
  924. * find unique extension for restored file if a file with the same name already exists
  925. *
  926. * @param string $location where the file should be restored
  927. * @param string $filename name of the file
  928. * @param View $view filesystem view relative to users root directory
  929. * @return string with unique extension
  930. */
  931. private static function getUniqueFilename($location, $filename, View $view) {
  932. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  933. $name = pathinfo($filename, PATHINFO_FILENAME);
  934. $l = \OC::$server->getL10N('files_trashbin');
  935. $location = '/' . trim($location, '/');
  936. // if extension is not empty we set a dot in front of it
  937. if ($ext !== '') {
  938. $ext = '.' . $ext;
  939. }
  940. if ($view->file_exists('files' . $location . '/' . $filename)) {
  941. $i = 2;
  942. $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
  943. while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
  944. $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
  945. $i++;
  946. }
  947. return $uniqueName;
  948. }
  949. return $filename;
  950. }
  951. /**
  952. * get the size from a given root folder
  953. *
  954. * @param View $view file view on the root folder
  955. * @return integer size of the folder
  956. */
  957. private static function calculateSize($view) {
  958. $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
  959. if (!file_exists($root)) {
  960. return 0;
  961. }
  962. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
  963. $size = 0;
  964. /**
  965. * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
  966. * This bug is fixed in PHP 5.5.9 or before
  967. * See #8376
  968. */
  969. $iterator->rewind();
  970. while ($iterator->valid()) {
  971. $path = $iterator->current();
  972. $relpath = substr($path, strlen($root) - 1);
  973. if (!$view->is_dir($relpath)) {
  974. $size += $view->filesize($relpath);
  975. }
  976. $iterator->next();
  977. }
  978. return $size;
  979. }
  980. /**
  981. * get current size of trash bin from a given user
  982. *
  983. * @param string $user user who owns the trash bin
  984. * @return integer trash bin size
  985. */
  986. private static function getTrashbinSize($user) {
  987. $view = new View('/' . $user);
  988. $fileInfo = $view->getFileInfo('/files_trashbin');
  989. return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
  990. }
  991. /**
  992. * check if trash bin is empty for a given user
  993. *
  994. * @param string $user
  995. * @return bool
  996. */
  997. public static function isEmpty($user) {
  998. $view = new View('/' . $user . '/files_trashbin');
  999. if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
  1000. while ($file = readdir($dh)) {
  1001. if (!Filesystem::isIgnoredDir($file)) {
  1002. return false;
  1003. }
  1004. }
  1005. }
  1006. return true;
  1007. }
  1008. /**
  1009. * @param $path
  1010. * @return string
  1011. */
  1012. public static function preview_icon($path) {
  1013. return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_trashbin_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
  1014. }
  1015. }