Trashbin.php 33 KB

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