Trashbin.php 32 KB

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