Trashbin.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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. $fileInfos = $view->getDirectoryContent('files_trashbin/files');
  413. // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
  414. $filePaths = array();
  415. foreach($fileInfos as $fileInfo){
  416. $filePaths[] = $view->getRelativePath($fileInfo->getPath());
  417. }
  418. unset($fileInfos); // save memory
  419. // Bulk PreDelete-Hook
  420. \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths));
  421. // Single-File Hooks
  422. foreach($filePaths as $path){
  423. self::emitTrashbinPreDelete($path);
  424. }
  425. // actual file deletion
  426. $view->deleteAll('files_trashbin');
  427. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
  428. $query->execute(array($user));
  429. // Bulk PostDelete-Hook
  430. \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths));
  431. // Single-File Hooks
  432. foreach($filePaths as $path){
  433. self::emitTrashbinPostDelete($path);
  434. }
  435. $view->mkdir('files_trashbin');
  436. $view->mkdir('files_trashbin/files');
  437. return true;
  438. }
  439. /**
  440. * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
  441. * @param string $path
  442. */
  443. protected static function emitTrashbinPreDelete($path){
  444. \OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path));
  445. }
  446. /**
  447. * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
  448. * @param string $path
  449. */
  450. protected static function emitTrashbinPostDelete($path){
  451. \OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path));
  452. }
  453. /**
  454. * delete file from trash bin permanently
  455. *
  456. * @param string $filename path to the file
  457. * @param string $user
  458. * @param int $timestamp of deletion time
  459. *
  460. * @return int size of deleted files
  461. */
  462. public static function delete($filename, $user, $timestamp = null) {
  463. $view = new View('/' . $user);
  464. $size = 0;
  465. if ($timestamp) {
  466. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
  467. $query->execute(array($user, $filename, $timestamp));
  468. $file = $filename . '.d' . $timestamp;
  469. } else {
  470. $file = $filename;
  471. }
  472. $size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
  473. if ($view->is_dir('/files_trashbin/files/' . $file)) {
  474. $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
  475. } else {
  476. $size += $view->filesize('/files_trashbin/files/' . $file);
  477. }
  478. self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
  479. $view->unlink('/files_trashbin/files/' . $file);
  480. self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
  481. return $size;
  482. }
  483. /**
  484. * @param View $view
  485. * @param string $file
  486. * @param string $filename
  487. * @param integer|null $timestamp
  488. * @param string $user
  489. * @return int
  490. */
  491. private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
  492. $size = 0;
  493. if (\OCP\App::isEnabled('files_versions')) {
  494. if ($view->is_dir('files_trashbin/versions/' . $file)) {
  495. $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
  496. $view->unlink('files_trashbin/versions/' . $file);
  497. } else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
  498. foreach ($versions as $v) {
  499. if ($timestamp) {
  500. $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
  501. $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
  502. } else {
  503. $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
  504. $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
  505. }
  506. }
  507. }
  508. }
  509. return $size;
  510. }
  511. /**
  512. * check to see whether a file exists in trashbin
  513. *
  514. * @param string $filename path to the file
  515. * @param int $timestamp of deletion time
  516. * @return bool true if file exists, otherwise false
  517. */
  518. public static function file_exists($filename, $timestamp = null) {
  519. $user = User::getUser();
  520. $view = new View('/' . $user);
  521. if ($timestamp) {
  522. $filename = $filename . '.d' . $timestamp;
  523. } else {
  524. $filename = $filename;
  525. }
  526. $target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
  527. return $view->file_exists($target);
  528. }
  529. /**
  530. * deletes used space for trash bin in db if user was deleted
  531. *
  532. * @param string $uid id of deleted user
  533. * @return bool result of db delete operation
  534. */
  535. public static function deleteUser($uid) {
  536. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
  537. return $query->execute(array($uid));
  538. }
  539. /**
  540. * calculate remaining free space for trash bin
  541. *
  542. * @param integer $trashbinSize current size of the trash bin
  543. * @param string $user
  544. * @return int available free space for trash bin
  545. */
  546. private static function calculateFreeSpace($trashbinSize, $user) {
  547. $softQuota = true;
  548. $userObject = \OC::$server->getUserManager()->get($user);
  549. if(is_null($userObject)) {
  550. return 0;
  551. }
  552. $quota = $userObject->getQuota();
  553. if ($quota === null || $quota === 'none') {
  554. $quota = Filesystem::free_space('/');
  555. $softQuota = false;
  556. // inf or unknown free space
  557. if ($quota < 0) {
  558. $quota = PHP_INT_MAX;
  559. }
  560. } else {
  561. $quota = \OCP\Util::computerFileSize($quota);
  562. }
  563. // calculate available space for trash bin
  564. // subtract size of files and current trash bin size from quota
  565. if ($softQuota) {
  566. $userFolder = \OC::$server->getUserFolder($user);
  567. if(is_null($userFolder)) {
  568. return 0;
  569. }
  570. $free = $quota - $userFolder->getSize(); // remaining free space for user
  571. if ($free > 0) {
  572. $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
  573. } else {
  574. $availableSpace = $free - $trashbinSize;
  575. }
  576. } else {
  577. $availableSpace = $quota;
  578. }
  579. return $availableSpace;
  580. }
  581. /**
  582. * resize trash bin if necessary after a new file was added to ownCloud
  583. *
  584. * @param string $user user id
  585. */
  586. public static function resizeTrash($user) {
  587. $size = self::getTrashbinSize($user);
  588. $freeSpace = self::calculateFreeSpace($size, $user);
  589. if ($freeSpace < 0) {
  590. self::scheduleExpire($user);
  591. }
  592. }
  593. /**
  594. * clean up the trash bin
  595. *
  596. * @param string $user
  597. */
  598. public static function expire($user) {
  599. $trashBinSize = self::getTrashbinSize($user);
  600. $availableSpace = self::calculateFreeSpace($trashBinSize, $user);
  601. $dirContent = Helper::getTrashFiles('/', $user, 'mtime');
  602. // delete all files older then $retention_obligation
  603. list($delSize, $count) = self::deleteExpiredFiles($dirContent, $user);
  604. $availableSpace += $delSize;
  605. // delete files from trash until we meet the trash bin size limit again
  606. self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
  607. }
  608. /**
  609. * @param string $user
  610. */
  611. private static function scheduleExpire($user) {
  612. // let the admin disable auto expire
  613. $application = new Application();
  614. $expiration = $application->getContainer()->query('Expiration');
  615. if ($expiration->isEnabled()) {
  616. \OC::$server->getCommandBus()->push(new Expire($user));
  617. }
  618. }
  619. /**
  620. * if the size limit for the trash bin is reached, we delete the oldest
  621. * files in the trash bin until we meet the limit again
  622. *
  623. * @param array $files
  624. * @param string $user
  625. * @param int $availableSpace available disc space
  626. * @return int size of deleted files
  627. */
  628. protected static function deleteFiles($files, $user, $availableSpace) {
  629. $application = new Application();
  630. $expiration = $application->getContainer()->query('Expiration');
  631. $size = 0;
  632. if ($availableSpace < 0) {
  633. foreach ($files as $file) {
  634. if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
  635. $tmp = self::delete($file['name'], $user, $file['mtime']);
  636. \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);
  637. $availableSpace += $tmp;
  638. $size += $tmp;
  639. } else {
  640. break;
  641. }
  642. }
  643. }
  644. return $size;
  645. }
  646. /**
  647. * delete files older then max storage time
  648. *
  649. * @param array $files list of files sorted by mtime
  650. * @param string $user
  651. * @return integer[] size of deleted files and number of deleted files
  652. */
  653. public static function deleteExpiredFiles($files, $user) {
  654. $application = new Application();
  655. $expiration = $application->getContainer()->query('Expiration');
  656. $size = 0;
  657. $count = 0;
  658. foreach ($files as $file) {
  659. $timestamp = $file['mtime'];
  660. $filename = $file['name'];
  661. if ($expiration->isExpired($timestamp)) {
  662. $count++;
  663. $size += self::delete($filename, $user, $timestamp);
  664. \OC::$server->getLogger()->info(
  665. 'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
  666. ['app' => 'files_trashbin']
  667. );
  668. } else {
  669. break;
  670. }
  671. }
  672. return array($size, $count);
  673. }
  674. /**
  675. * recursive copy to copy a whole directory
  676. *
  677. * @param string $source source path, relative to the users files directory
  678. * @param string $destination destination path relative to the users root directoy
  679. * @param View $view file view for the users root directory
  680. * @return int
  681. * @throws Exceptions\CopyRecursiveException
  682. */
  683. private static function copy_recursive($source, $destination, View $view) {
  684. $size = 0;
  685. if ($view->is_dir($source)) {
  686. $view->mkdir($destination);
  687. $view->touch($destination, $view->filemtime($source));
  688. foreach ($view->getDirectoryContent($source) as $i) {
  689. $pathDir = $source . '/' . $i['name'];
  690. if ($view->is_dir($pathDir)) {
  691. $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
  692. } else {
  693. $size += $view->filesize($pathDir);
  694. $result = $view->copy($pathDir, $destination . '/' . $i['name']);
  695. if (!$result) {
  696. throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
  697. }
  698. $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
  699. }
  700. }
  701. } else {
  702. $size += $view->filesize($source);
  703. $result = $view->copy($source, $destination);
  704. if (!$result) {
  705. throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
  706. }
  707. $view->touch($destination, $view->filemtime($source));
  708. }
  709. return $size;
  710. }
  711. /**
  712. * find all versions which belong to the file we want to restore
  713. *
  714. * @param string $filename name of the file which should be restored
  715. * @param int $timestamp timestamp when the file was deleted
  716. * @return array
  717. */
  718. private static function getVersionsFromTrash($filename, $timestamp, $user) {
  719. $view = new View('/' . $user . '/files_trashbin/versions');
  720. $versions = array();
  721. //force rescan of versions, local storage may not have updated the cache
  722. if (!self::$scannedVersions) {
  723. /** @var \OC\Files\Storage\Storage $storage */
  724. list($storage,) = $view->resolvePath('/');
  725. $storage->getScanner()->scan('files_trashbin/versions');
  726. self::$scannedVersions = true;
  727. }
  728. if ($timestamp) {
  729. // fetch for old versions
  730. $matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
  731. $offset = -strlen($timestamp) - 2;
  732. } else {
  733. $matches = $view->searchRaw($filename . '.v%');
  734. }
  735. if (is_array($matches)) {
  736. foreach ($matches as $ma) {
  737. if ($timestamp) {
  738. $parts = explode('.v', substr($ma['path'], 0, $offset));
  739. $versions[] = (end($parts));
  740. } else {
  741. $parts = explode('.v', $ma);
  742. $versions[] = (end($parts));
  743. }
  744. }
  745. }
  746. return $versions;
  747. }
  748. /**
  749. * find unique extension for restored file if a file with the same name already exists
  750. *
  751. * @param string $location where the file should be restored
  752. * @param string $filename name of the file
  753. * @param View $view filesystem view relative to users root directory
  754. * @return string with unique extension
  755. */
  756. private static function getUniqueFilename($location, $filename, View $view) {
  757. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  758. $name = pathinfo($filename, PATHINFO_FILENAME);
  759. $l = \OC::$server->getL10N('files_trashbin');
  760. $location = '/' . trim($location, '/');
  761. // if extension is not empty we set a dot in front of it
  762. if ($ext !== '') {
  763. $ext = '.' . $ext;
  764. }
  765. if ($view->file_exists('files' . $location . '/' . $filename)) {
  766. $i = 2;
  767. $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
  768. while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
  769. $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
  770. $i++;
  771. }
  772. return $uniqueName;
  773. }
  774. return $filename;
  775. }
  776. /**
  777. * get the size from a given root folder
  778. *
  779. * @param View $view file view on the root folder
  780. * @return integer size of the folder
  781. */
  782. private static function calculateSize($view) {
  783. $root = \OC::$server->getConfig()->getSystemValue('datadirectory') . $view->getAbsolutePath('');
  784. if (!file_exists($root)) {
  785. return 0;
  786. }
  787. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
  788. $size = 0;
  789. /**
  790. * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
  791. * This bug is fixed in PHP 5.5.9 or before
  792. * See #8376
  793. */
  794. $iterator->rewind();
  795. while ($iterator->valid()) {
  796. $path = $iterator->current();
  797. $relpath = substr($path, strlen($root) - 1);
  798. if (!$view->is_dir($relpath)) {
  799. $size += $view->filesize($relpath);
  800. }
  801. $iterator->next();
  802. }
  803. return $size;
  804. }
  805. /**
  806. * get current size of trash bin from a given user
  807. *
  808. * @param string $user user who owns the trash bin
  809. * @return integer trash bin size
  810. */
  811. private static function getTrashbinSize($user) {
  812. $view = new View('/' . $user);
  813. $fileInfo = $view->getFileInfo('/files_trashbin');
  814. return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
  815. }
  816. /**
  817. * register hooks
  818. */
  819. public static function registerHooks() {
  820. // create storage wrapper on setup
  821. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage');
  822. //Listen to delete user signal
  823. \OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook');
  824. //Listen to post write hook
  825. \OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook');
  826. // pre and post-rename, disable trash logic for the copy+unlink case
  827. \OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook');
  828. \OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook');
  829. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook');
  830. }
  831. /**
  832. * check if trash bin is empty for a given user
  833. *
  834. * @param string $user
  835. * @return bool
  836. */
  837. public static function isEmpty($user) {
  838. $view = new View('/' . $user . '/files_trashbin');
  839. if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
  840. while ($file = readdir($dh)) {
  841. if (!Filesystem::isIgnoredDir($file)) {
  842. return false;
  843. }
  844. }
  845. }
  846. return true;
  847. }
  848. /**
  849. * @param $path
  850. * @return string
  851. */
  852. public static function preview_icon($path) {
  853. return \OCP\Util::linkToRoute('core_ajax_trashbin_preview', array('x' => 32, 'y' => 32, 'file' => $path));
  854. }
  855. }