Trashbin.php 32 KB

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