Trashbin.php 32 KB

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