You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Trashbin.php 37KB

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