trashbin.php 29 KB

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