Trashbin.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  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\Files\Cache\Cache;
  47. use OC\Files\Cache\CacheEntry;
  48. use OC\Files\Cache\CacheQueryBuilder;
  49. use OC\Files\Filesystem;
  50. use OC\Files\ObjectStore\ObjectStoreStorage;
  51. use OC\Files\View;
  52. use OCA\Files_Trashbin\AppInfo\Application;
  53. use OCA\Files_Trashbin\Command\Expire;
  54. use OCP\AppFramework\Utility\ITimeFactory;
  55. use OCP\Files\File;
  56. use OCP\Files\Folder;
  57. use OCP\Files\NotFoundException;
  58. use OCP\Files\NotPermittedException;
  59. use OCP\Lock\ILockingProvider;
  60. use OCP\Lock\LockedException;
  61. use OCP\User;
  62. class Trashbin {
  63. // unit: percentage; 50% of available disk space/quota
  64. public const DEFAULTMAXSIZE = 50;
  65. /**
  66. * Whether versions have already be rescanned during this PHP request
  67. *
  68. * @var bool
  69. */
  70. private static $scannedVersions = false;
  71. /**
  72. * Ensure we don't need to scan the file during the move to trash
  73. * by triggering the scan in the pre-hook
  74. *
  75. * @param array $params
  76. */
  77. public static function ensureFileScannedHook($params) {
  78. try {
  79. self::getUidAndFilename($params['path']);
  80. } catch (NotFoundException $e) {
  81. // nothing to scan for non existing files
  82. }
  83. }
  84. /**
  85. * get the UID of the owner of the file and the path to the file relative to
  86. * owners files folder
  87. *
  88. * @param string $filename
  89. * @return array
  90. * @throws \OC\User\NoUserException
  91. */
  92. public static function getUidAndFilename($filename) {
  93. $uid = Filesystem::getOwner($filename);
  94. $userManager = \OC::$server->getUserManager();
  95. // if the user with the UID doesn't exists, e.g. because the UID points
  96. // to a remote user with a federated cloud ID we use the current logged-in
  97. // user. We need a valid local user to move the file to the right trash bin
  98. if (!$userManager->userExists($uid)) {
  99. $uid = User::getUser();
  100. }
  101. if (!$uid) {
  102. // no owner, usually because of share link from ext storage
  103. return [null, null];
  104. }
  105. Filesystem::initMountPoints($uid);
  106. if ($uid !== User::getUser()) {
  107. $info = Filesystem::getFileInfo($filename);
  108. $ownerView = new View('/' . $uid . '/files');
  109. try {
  110. $filename = $ownerView->getPath($info['fileid']);
  111. } catch (NotFoundException $e) {
  112. $filename = null;
  113. }
  114. }
  115. return [$uid, $filename];
  116. }
  117. /**
  118. * get original location of files for user
  119. *
  120. * @param string $user
  121. * @return array (filename => array (timestamp => original location))
  122. */
  123. public static function getLocations($user) {
  124. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  125. $query->select('id', 'timestamp', 'location')
  126. ->from('files_trash')
  127. ->where($query->expr()->eq('user', $query->createNamedParameter($user)));
  128. $result = $query->executeQuery();
  129. $array = [];
  130. while ($row = $result->fetch()) {
  131. if (isset($array[$row['id']])) {
  132. $array[$row['id']][$row['timestamp']] = $row['location'];
  133. } else {
  134. $array[$row['id']] = [$row['timestamp'] => $row['location']];
  135. }
  136. }
  137. $result->closeCursor();
  138. return $array;
  139. }
  140. /**
  141. * get original location of file
  142. *
  143. * @param string $user
  144. * @param string $filename
  145. * @param string $timestamp
  146. * @return string original location
  147. */
  148. public static function getLocation($user, $filename, $timestamp) {
  149. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  150. $query->select('location')
  151. ->from('files_trash')
  152. ->where($query->expr()->eq('user', $query->createNamedParameter($user)))
  153. ->andWhere($query->expr()->eq('id', $query->createNamedParameter($filename)))
  154. ->andWhere($query->expr()->eq('timestamp', $query->createNamedParameter($timestamp)));
  155. $result = $query->executeQuery();
  156. $row = $result->fetch();
  157. $result->closeCursor();
  158. if (isset($row['location'])) {
  159. return $row['location'];
  160. } else {
  161. return false;
  162. }
  163. }
  164. private static function setUpTrash($user) {
  165. $view = new View('/' . $user);
  166. if (!$view->is_dir('files_trashbin')) {
  167. $view->mkdir('files_trashbin');
  168. }
  169. if (!$view->is_dir('files_trashbin/files')) {
  170. $view->mkdir('files_trashbin/files');
  171. }
  172. if (!$view->is_dir('files_trashbin/versions')) {
  173. $view->mkdir('files_trashbin/versions');
  174. }
  175. if (!$view->is_dir('files_trashbin/keys')) {
  176. $view->mkdir('files_trashbin/keys');
  177. }
  178. }
  179. /**
  180. * copy file to owners trash
  181. *
  182. * @param string $sourcePath
  183. * @param string $owner
  184. * @param string $targetPath
  185. * @param $user
  186. * @param integer $timestamp
  187. */
  188. private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) {
  189. self::setUpTrash($owner);
  190. $targetFilename = basename($targetPath);
  191. $targetLocation = dirname($targetPath);
  192. $sourceFilename = basename($sourcePath);
  193. $view = new View('/');
  194. $target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
  195. $source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
  196. $free = $view->free_space($target);
  197. $isUnknownOrUnlimitedFreeSpace = $free < 0;
  198. $isEnoughFreeSpaceLeft = $view->filesize($source) < $free;
  199. if ($isUnknownOrUnlimitedFreeSpace || $isEnoughFreeSpaceLeft) {
  200. self::copy_recursive($source, $target, $view);
  201. }
  202. if ($view->file_exists($target)) {
  203. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  204. $query->insert('files_trash')
  205. ->setValue('id', $query->createNamedParameter($targetFilename))
  206. ->setValue('timestamp', $query->createNamedParameter($timestamp))
  207. ->setValue('location', $query->createNamedParameter($targetLocation))
  208. ->setValue('user', $query->createNamedParameter($user));
  209. $result = $query->executeUpdate();
  210. if (!$result) {
  211. \OC::$server->getLogger()->error('trash bin database couldn\'t be updated for the files owner', ['app' => 'files_trashbin']);
  212. }
  213. }
  214. }
  215. /**
  216. * move file to the trash bin
  217. *
  218. * @param string $file_path path to the deleted file/directory relative to the files root directory
  219. * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
  220. *
  221. * @return bool
  222. */
  223. public static function move2trash($file_path, $ownerOnly = false) {
  224. // get the user for which the filesystem is setup
  225. $root = Filesystem::getRoot();
  226. [, $user] = explode('/', $root);
  227. [$owner, $ownerPath] = self::getUidAndFilename($file_path);
  228. // if no owner found (ex: ext storage + share link), will use the current user's trashbin then
  229. if (is_null($owner)) {
  230. $owner = $user;
  231. $ownerPath = $file_path;
  232. }
  233. $ownerView = new View('/' . $owner);
  234. // file has been deleted in between
  235. if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) {
  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. /** @var \OC\Files\Storage\Storage $sourceStorage */
  267. [$sourceStorage, $sourceInternalPath] = $ownerView->resolvePath('/files/' . $ownerPath);
  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 && $sourceStorage->filesize($sourceInternalPath) >= $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->getLogger()->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->executeUpdate();
  314. if (!$result) {
  315. \OC::$server->getLogger()->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\App::isEnabled('files_versions') && !empty($ownerPath)) {
  343. $user = 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 = 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->getLogger()->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->executeUpdate();
  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\App::isEnabled('files_versions')) {
  475. $user = 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 = 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->executeUpdate();
  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->executeUpdate();
  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\App::isEnabled('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 = 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->executeUpdate();
  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 $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->getLogger()->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->getLogger()->logException($e, ['app' => 'files_trashbin', 'level' => \OCP\ILogger::WARN, 'message' => 'Removing "' . $filename . '" from trashbin failed.']);
  793. }
  794. \OC::$server->getLogger()->info(
  795. 'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
  796. ['app' => 'files_trashbin']
  797. );
  798. } else {
  799. break;
  800. }
  801. }
  802. return [$size, $count];
  803. }
  804. /**
  805. * recursive copy to copy a whole directory
  806. *
  807. * @param string $source source path, relative to the users files directory
  808. * @param string $destination destination path relative to the users root directoy
  809. * @param View $view file view for the users root directory
  810. * @return int
  811. * @throws Exceptions\CopyRecursiveException
  812. */
  813. private static function copy_recursive($source, $destination, View $view) {
  814. $size = 0;
  815. if ($view->is_dir($source)) {
  816. $view->mkdir($destination);
  817. $view->touch($destination, $view->filemtime($source));
  818. foreach ($view->getDirectoryContent($source) as $i) {
  819. $pathDir = $source . '/' . $i['name'];
  820. if ($view->is_dir($pathDir)) {
  821. $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
  822. } else {
  823. $size += $view->filesize($pathDir);
  824. $result = $view->copy($pathDir, $destination . '/' . $i['name']);
  825. if (!$result) {
  826. throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
  827. }
  828. $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
  829. }
  830. }
  831. } else {
  832. $size += $view->filesize($source);
  833. $result = $view->copy($source, $destination);
  834. if (!$result) {
  835. throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
  836. }
  837. $view->touch($destination, $view->filemtime($source));
  838. }
  839. return $size;
  840. }
  841. /**
  842. * find all versions which belong to the file we want to restore
  843. *
  844. * @param string $filename name of the file which should be restored
  845. * @param int $timestamp timestamp when the file was deleted
  846. * @return array
  847. */
  848. private static function getVersionsFromTrash($filename, $timestamp, $user) {
  849. $view = new View('/' . $user . '/files_trashbin/versions');
  850. $versions = [];
  851. /** @var \OC\Files\Storage\Storage $storage */
  852. [$storage,] = $view->resolvePath('/');
  853. //force rescan of versions, local storage may not have updated the cache
  854. if (!self::$scannedVersions) {
  855. $storage->getScanner()->scan('files_trashbin/versions');
  856. self::$scannedVersions = true;
  857. }
  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->getLogger(),
  873. $cache
  874. );
  875. $normalizedParentPath = ltrim(Filesystem::normalizePath(dirname('files_trashbin/versions/'. $filename)), '/');
  876. $parentId = $cache->getId($normalizedParentPath);
  877. if ($parentId === -1) {
  878. return [];
  879. }
  880. $query->selectFileCache()
  881. ->whereStorageId()
  882. ->andWhere($query->expr()->eq('parent', $query->createNamedParameter($parentId)))
  883. ->andWhere($query->expr()->iLike('name', $query->createNamedParameter($pattern)));
  884. $result = $query->executeQuery();
  885. $entries = $result->fetchAll();
  886. $result->closeCursor();
  887. /** @var CacheEntry[] $matches */
  888. $matches = array_map(function (array $data) {
  889. return Cache::cacheEntryFromData($data, \OC::$server->getMimeTypeLoader());
  890. }, $entries);
  891. foreach ($matches as $ma) {
  892. if ($timestamp) {
  893. $parts = explode('.v', substr($ma['path'], 0, $offset));
  894. $versions[] = end($parts);
  895. } else {
  896. $parts = explode('.v', $ma['path']);
  897. $versions[] = end($parts);
  898. }
  899. }
  900. return $versions;
  901. }
  902. /**
  903. * find unique extension for restored file if a file with the same name already exists
  904. *
  905. * @param string $location where the file should be restored
  906. * @param string $filename name of the file
  907. * @param View $view filesystem view relative to users root directory
  908. * @return string with unique extension
  909. */
  910. private static function getUniqueFilename($location, $filename, View $view) {
  911. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  912. $name = pathinfo($filename, PATHINFO_FILENAME);
  913. $l = \OC::$server->getL10N('files_trashbin');
  914. $location = '/' . trim($location, '/');
  915. // if extension is not empty we set a dot in front of it
  916. if ($ext !== '') {
  917. $ext = '.' . $ext;
  918. }
  919. if ($view->file_exists('files' . $location . '/' . $filename)) {
  920. $i = 2;
  921. $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
  922. while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
  923. $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
  924. $i++;
  925. }
  926. return $uniqueName;
  927. }
  928. return $filename;
  929. }
  930. /**
  931. * get the size from a given root folder
  932. *
  933. * @param View $view file view on the root folder
  934. * @return integer size of the folder
  935. */
  936. private static function calculateSize($view) {
  937. $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
  938. if (!file_exists($root)) {
  939. return 0;
  940. }
  941. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
  942. $size = 0;
  943. /**
  944. * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
  945. * This bug is fixed in PHP 5.5.9 or before
  946. * See #8376
  947. */
  948. $iterator->rewind();
  949. while ($iterator->valid()) {
  950. $path = $iterator->current();
  951. $relpath = substr($path, strlen($root) - 1);
  952. if (!$view->is_dir($relpath)) {
  953. $size += $view->filesize($relpath);
  954. }
  955. $iterator->next();
  956. }
  957. return $size;
  958. }
  959. /**
  960. * get current size of trash bin from a given user
  961. *
  962. * @param string $user user who owns the trash bin
  963. * @return integer trash bin size
  964. */
  965. private static function getTrashbinSize($user) {
  966. $view = new View('/' . $user);
  967. $fileInfo = $view->getFileInfo('/files_trashbin');
  968. return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
  969. }
  970. /**
  971. * check if trash bin is empty for a given user
  972. *
  973. * @param string $user
  974. * @return bool
  975. */
  976. public static function isEmpty($user) {
  977. $view = new View('/' . $user . '/files_trashbin');
  978. if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
  979. while ($file = readdir($dh)) {
  980. if (!Filesystem::isIgnoredDir($file)) {
  981. return false;
  982. }
  983. }
  984. }
  985. return true;
  986. }
  987. /**
  988. * @param $path
  989. * @return string
  990. */
  991. public static function preview_icon($path) {
  992. return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_trashbin_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
  993. }
  994. }