Trashbin.php 30 KB

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