1
0

Trashbin.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  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/' . static::getTrashFilename($targetFilename, $timestamp);
  191. $source = $owner . '/files_trashbin/files/' . static::getTrashFilename($sourceFilename, $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/' . static::getTrashFilename($filename, $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/' . static::getTrashFilename($filename, $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(static::getTrashFilename($filename, $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/' . static::getTrashFilename(basename($ownerPath), $timestamp), $rootView);
  348. }
  349. self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . static::getTrashFilename($filename, $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/' . static::getTrashFilename($v['name'] . '.v' . $v['version'], $timestamp));
  354. }
  355. self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . static::getTrashFilename($filename . '.v' . $v['version'], $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/' . static::getTrashFilename($versionedFile . '.v' . $v, $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 = static::getTrashFilename($filename, $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/' . static::getTrashFilename($filename . '.v' . $v, $timestamp));
  616. $view->unlink('/files_trashbin/versions/' . static::getTrashFilename($filename . '.v' . $v, $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 = static::getTrashFilename($filename, $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. /**
  994. * Return the filename used in the trash bin
  995. */
  996. public static function getTrashFilename(string $filename, int $timestamp): string {
  997. $trashFilename = $filename . '.d' . $timestamp;
  998. $length = strlen($trashFilename);
  999. // oc_filecache `name` column has a limit of 250 chars
  1000. $maxLength = 250;
  1001. if ($length > $maxLength) {
  1002. $trashFilename = substr_replace(
  1003. $trashFilename,
  1004. '',
  1005. $maxLength / 2,
  1006. $length - $maxLength
  1007. );
  1008. }
  1009. return $trashFilename;
  1010. }
  1011. }