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 33KB

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