trashbin.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. <?php
  2. /**
  3. * ownCloud - trash bin
  4. *
  5. * @author Bjoern Schiessle
  6. * @copyright 2013 Bjoern Schiessle schiessle@owncloud.com
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  10. * License as published by the Free Software Foundation; either
  11. * version 3 of the License, or any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public
  19. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. namespace OCA\Files_Trashbin;
  23. class Trashbin {
  24. // how long do we keep files in the trash bin if no other value is defined in the config file (unit: days)
  25. const DEFAULT_RETENTION_OBLIGATION = 30;
  26. // unit: percentage; 50% of available disk space/quota
  27. const DEFAULTMAXSIZE = 50;
  28. public static function getUidAndFilename($filename) {
  29. $uid = \OC\Files\Filesystem::getOwner($filename);
  30. \OC\Files\Filesystem::initMountPoints($uid);
  31. if ($uid != \OCP\User::getUser()) {
  32. $info = \OC\Files\Filesystem::getFileInfo($filename);
  33. $ownerView = new \OC\Files\View('/' . $uid . '/files');
  34. $filename = $ownerView->getPath($info['fileid']);
  35. }
  36. return array($uid, $filename);
  37. }
  38. /**
  39. * move file to the trash bin
  40. *
  41. * @param $file_path path to the deleted file/directory relative to the files root directory
  42. */
  43. public static function move2trash($file_path) {
  44. $user = \OCP\User::getUser();
  45. $view = new \OC\Files\View('/' . $user);
  46. if (!$view->is_dir('files_trashbin')) {
  47. $view->mkdir('files_trashbin');
  48. }
  49. if (!$view->is_dir('files_trashbin/files')) {
  50. $view->mkdir('files_trashbin/files');
  51. }
  52. if (!$view->is_dir('files_trashbin/versions')) {
  53. $view->mkdir('files_trashbin/versions');
  54. }
  55. if (!$view->is_dir('files_trashbin/keyfiles')) {
  56. $view->mkdir('files_trashbin/keyfiles');
  57. }
  58. if (!$view->is_dir('files_trashbin/share-keys')) {
  59. $view->mkdir('files_trashbin/share-keys');
  60. }
  61. $path_parts = pathinfo($file_path);
  62. $filename = $path_parts['basename'];
  63. $location = $path_parts['dirname'];
  64. $timestamp = time();
  65. $mime = $view->getMimeType('files' . $file_path);
  66. if ($view->is_dir('files' . $file_path)) {
  67. $type = 'dir';
  68. } else {
  69. $type = 'file';
  70. }
  71. $trashbinSize = self::getTrashbinSize($user);
  72. if ($trashbinSize === false || $trashbinSize < 0) {
  73. $trashbinSize = self::calculateSize(new \OC\Files\View('/' . $user . '/files_trashbin'));
  74. }
  75. // disable proxy to prevent recursive calls
  76. $proxyStatus = \OC_FileProxy::$enabled;
  77. \OC_FileProxy::$enabled = false;
  78. $sizeOfAddedFiles = self::copy_recursive($file_path, 'files_trashbin/files/' . $filename . '.d' . $timestamp, $view);
  79. \OC_FileProxy::$enabled = $proxyStatus;
  80. if ($view->file_exists('files_trashbin/files/' . $filename . '.d' . $timestamp)) {
  81. $trashbinSize += $sizeOfAddedFiles;
  82. $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`type`,`mime`,`user`) VALUES (?,?,?,?,?,?)");
  83. $result = $query->execute(array($filename, $timestamp, $location, $type, $mime, $user));
  84. if (!$result) { // if file couldn't be added to the database than also don't store it in the trash bin.
  85. $view->deleteAll('files_trashbin/files/' . $filename . '.d' . $timestamp);
  86. \OC_Log::write('files_trashbin', 'trash bin database couldn\'t be updated', \OC_log::ERROR);
  87. return;
  88. }
  89. \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => \OC\Files\Filesystem::normalizePath($file_path),
  90. 'trashPath' => \OC\Files\Filesystem::normalizePath($filename . '.d' . $timestamp)));
  91. $trashbinSize += self::retainVersions($file_path, $filename, $timestamp);
  92. $trashbinSize += self::retainEncryptionKeys($file_path, $filename, $timestamp);
  93. } else {
  94. \OC_Log::write('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OC_log::ERROR);
  95. }
  96. $trashbinSize -= self::expire($trashbinSize);
  97. self::setTrashbinSize($user, $trashbinSize);
  98. }
  99. /**
  100. * Move file versions to trash so that they can be restored later
  101. *
  102. * @param $file_path path to original file
  103. * @param $filename of deleted file
  104. * @param $timestamp when the file was deleted
  105. *
  106. * @return size of stored versions
  107. */
  108. private static function retainVersions($file_path, $filename, $timestamp) {
  109. $size = 0;
  110. if (\OCP\App::isEnabled('files_versions')) {
  111. // disable proxy to prevent recursive calls
  112. $proxyStatus = \OC_FileProxy::$enabled;
  113. \OC_FileProxy::$enabled = false;
  114. $user = \OCP\User::getUser();
  115. $rootView = new \OC\Files\View('/');
  116. list($owner, $ownerPath) = self::getUidAndFilename($file_path);
  117. if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
  118. $size += self::calculateSize(new \OC\Files\View('/' . $owner . '/files_versions/' . $ownerPath));
  119. $rootView->rename($owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
  120. } else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
  121. foreach ($versions as $v) {
  122. $size += $rootView->filesize($owner . '/files_versions' . $v['path'] . '.v' . $v['version']);
  123. $rootView->rename($owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
  124. }
  125. }
  126. // enable proxy
  127. \OC_FileProxy::$enabled = $proxyStatus;
  128. }
  129. return $size;
  130. }
  131. /**
  132. * Move encryption keys to trash so that they can be restored later
  133. *
  134. * @param $file_path path to original file
  135. * @param $filename of deleted file
  136. * @param $timestamp when the file was deleted
  137. *
  138. * @return size of encryption keys
  139. */
  140. private static function retainEncryptionKeys($file_path, $filename, $timestamp) {
  141. $size = 0;
  142. if (\OCP\App::isEnabled('files_encryption')) {
  143. $user = \OCP\User::getUser();
  144. $rootView = new \OC\Files\View('/');
  145. list($owner, $ownerPath) = self::getUidAndFilename($file_path);
  146. $util = new \OCA\Encryption\Util(new \OC_FilesystemView('/'), $user);
  147. // disable proxy to prevent recursive calls
  148. $proxyStatus = \OC_FileProxy::$enabled;
  149. \OC_FileProxy::$enabled = false;
  150. if ($util->isSystemWideMountPoint($ownerPath)) {
  151. $baseDir = '/files_encryption/';
  152. } else {
  153. $baseDir = $owner . '/files_encryption/';
  154. }
  155. $keyfile = \OC\Files\Filesystem::normalizePath($baseDir . '/keyfiles/' . $ownerPath);
  156. if ($rootView->is_dir($keyfile) || $rootView->file_exists($keyfile . '.key')) {
  157. // move keyfiles
  158. if ($rootView->is_dir($keyfile)) {
  159. $size += self::calculateSize(new \OC\Files\View($keyfile));
  160. $rootView->rename($keyfile, $user . '/files_trashbin/keyfiles/' . $filename . '.d' . $timestamp);
  161. } else {
  162. $size += $rootView->filesize($keyfile . '.key');
  163. $rootView->rename($keyfile . '.key', $user . '/files_trashbin/keyfiles/' . $filename . '.key.d' . $timestamp);
  164. }
  165. }
  166. // retain share keys
  167. $sharekeys = \OC\Files\Filesystem::normalizePath($baseDir . '/share-keys/' . $ownerPath);
  168. if ($rootView->is_dir($sharekeys)) {
  169. $size += self::calculateSize(new \OC\Files\View($sharekeys));
  170. $rootView->rename($sharekeys, $user . '/files_trashbin/share-keys/' . $filename . '.d' . $timestamp);
  171. } else {
  172. // get local path to share-keys
  173. $localShareKeysPath = $rootView->getLocalFile($sharekeys);
  174. $escapedLocalShareKeysPath = preg_replace('/(\*|\?|\[)/', '[$1]', $localShareKeysPath);
  175. // handle share-keys
  176. $matches = glob($escapedLocalShareKeysPath . '*.shareKey');
  177. foreach ($matches as $src) {
  178. // get source file parts
  179. $pathinfo = pathinfo($src);
  180. // we only want to keep the owners key so we can access the private key
  181. $ownerShareKey = $filename . '.' . $user . '.shareKey';
  182. // if we found the share-key for the owner, we need to move it to files_trashbin
  183. if ($pathinfo['basename'] == $ownerShareKey) {
  184. // calculate size
  185. $size += $rootView->filesize($sharekeys . '.' . $user . '.shareKey');
  186. // move file
  187. $rootView->rename($sharekeys . '.' . $user . '.shareKey', $user . '/files_trashbin/share-keys/' . $ownerShareKey . '.d' . $timestamp);
  188. } else {
  189. // calculate size
  190. $size += filesize($src);
  191. // don't keep other share-keys
  192. unlink($src);
  193. }
  194. }
  195. }
  196. // enable proxy
  197. \OC_FileProxy::$enabled = $proxyStatus;
  198. }
  199. return $size;
  200. }
  201. /**
  202. * restore files from trash bin
  203. * @param $file path to the deleted file
  204. * @param $filename name of the file
  205. * @param $timestamp time when the file was deleted
  206. *
  207. * @return bool
  208. */
  209. public static function restore($file, $filename, $timestamp) {
  210. $user = \OCP\User::getUser();
  211. $view = new \OC\Files\View('/' . $user);
  212. $trashbinSize = self::getTrashbinSize($user);
  213. if ($trashbinSize === false || $trashbinSize < 0) {
  214. $trashbinSize = self::calculateSize(new \OC\Files\View('/' . $user . '/files_trashbin'));
  215. }
  216. if ($timestamp) {
  217. $query = \OC_DB::prepare('SELECT `location`,`type` FROM `*PREFIX*files_trash`'
  218. . ' WHERE `user`=? AND `id`=? AND `timestamp`=?');
  219. $result = $query->execute(array($user, $filename, $timestamp))->fetchAll();
  220. if (count($result) !== 1) {
  221. \OC_Log::write('files_trashbin', 'trash bin database inconsistent!', \OC_Log::ERROR);
  222. return false;
  223. }
  224. // if location no longer exists, restore file in the root directory
  225. $location = $result[0]['location'];
  226. if ($result[0]['location'] !== '/' &&
  227. (!$view->is_dir('files' . $result[0]['location']) ||
  228. !$view->isUpdatable('files' . $result[0]['location']))) {
  229. $location = '';
  230. }
  231. } else {
  232. $path_parts = pathinfo($file);
  233. $result[] = array(
  234. 'location' => $path_parts['dirname'],
  235. 'type' => $view->is_dir('/files_trashbin/files/' . $file) ? 'dir' : 'files',
  236. );
  237. $location = '';
  238. }
  239. // we need a extension in case a file/dir with the same name already exists
  240. $uniqueFilename = self::getUniqueFilename($location, $filename, $view);
  241. $source = \OC\Files\Filesystem::normalizePath('files_trashbin/files/' . $file);
  242. $target = \OC\Files\Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
  243. $mtime = $view->filemtime($source);
  244. // disable proxy to prevent recursive calls
  245. $proxyStatus = \OC_FileProxy::$enabled;
  246. \OC_FileProxy::$enabled = false;
  247. // restore file
  248. $restoreResult = $view->rename($source, $target);
  249. // handle the restore result
  250. if ($restoreResult) {
  251. $fakeRoot = $view->getRoot();
  252. $view->chroot('/' . $user . '/files');
  253. $view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
  254. $view->chroot($fakeRoot);
  255. \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => \OC\Files\Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
  256. 'trashPath' => \OC\Files\Filesystem::normalizePath($file)));
  257. if ($view->is_dir($target)) {
  258. $trashbinSize -= self::calculateSize(new \OC\Files\View('/' . $user . '/' . $target));
  259. } else {
  260. $trashbinSize -= $view->filesize($target);
  261. }
  262. $trashbinSize -= self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
  263. $trashbinSize -= self::restoreEncryptionKeys($view, $file, $filename, $uniqueFilename, $location, $timestamp);
  264. if ($timestamp) {
  265. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
  266. $query->execute(array($user, $filename, $timestamp));
  267. }
  268. self::setTrashbinSize($user, $trashbinSize);
  269. // enable proxy
  270. \OC_FileProxy::$enabled = $proxyStatus;
  271. return true;
  272. }
  273. // enable proxy
  274. \OC_FileProxy::$enabled = $proxyStatus;
  275. return false;
  276. }
  277. /**
  278. * @brief restore versions from trash bin
  279. *
  280. * @param \OC\Files\View $view file view
  281. * @param $file complete path to file
  282. * @param $filename name of file once it was deleted
  283. * @param $uniqueFilename new file name to restore the file without overwriting existing files
  284. * @param $location location if file
  285. * @param $timestamp deleteion time
  286. *
  287. * @return size of restored versions
  288. */
  289. private static function restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp) {
  290. $size = 0;
  291. if (\OCP\App::isEnabled('files_versions')) {
  292. // disable proxy to prevent recursive calls
  293. $proxyStatus = \OC_FileProxy::$enabled;
  294. \OC_FileProxy::$enabled = false;
  295. $user = \OCP\User::getUser();
  296. $rootView = new \OC\Files\View('/');
  297. $target = \OC\Files\Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
  298. list($owner, $ownerPath) = self::getUidAndFilename($target);
  299. if ($timestamp) {
  300. $versionedFile = $filename;
  301. } else {
  302. $versionedFile = $file;
  303. }
  304. if ($view->is_dir('/files_trashbin/versions/' . $file)) {
  305. $size += self::calculateSize(new \OC\Files\View('/' . $user . '/' . 'files_trashbin/versions/' . $file));
  306. $rootView->rename(\OC\Files\Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), \OC\Files\Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
  307. } else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp)) {
  308. foreach ($versions as $v) {
  309. if ($timestamp) {
  310. $size += $view->filesize('files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp);
  311. $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
  312. } else {
  313. $size += $view->filesize('files_trashbin/versions/' . $versionedFile . '.v' . $v);
  314. $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
  315. }
  316. }
  317. }
  318. // enable proxy
  319. \OC_FileProxy::$enabled = $proxyStatus;
  320. }
  321. return $size;
  322. }
  323. /**
  324. * @brief restore encryption keys from trash bin
  325. *
  326. * @param \OC\Files\View $view
  327. * @param $file complete path to file
  328. * @param $filename name of file
  329. * @param $uniqueFilename new file name to restore the file without overwriting existing files
  330. * @param $location location of file
  331. * @param $timestamp deleteion time
  332. *
  333. * @return size of restored encrypted file
  334. */
  335. private static function restoreEncryptionKeys($view, $file, $filename, $uniqueFilename, $location, $timestamp) {
  336. // Take care of encryption keys TODO! Get '.key' in file between file name and delete date (also for permanent delete!)
  337. $size = 0;
  338. if (\OCP\App::isEnabled('files_encryption')) {
  339. $user = \OCP\User::getUser();
  340. $rootView = new \OC\Files\View('/');
  341. $target = \OC\Files\Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
  342. list($owner, $ownerPath) = self::getUidAndFilename($target);
  343. $util = new \OCA\Encryption\Util(new \OC_FilesystemView('/'), $user);
  344. if ($util->isSystemWideMountPoint($ownerPath)) {
  345. $baseDir = '/files_encryption/';
  346. } else {
  347. $baseDir = $owner . '/files_encryption/';
  348. }
  349. $path_parts = pathinfo($file);
  350. $source_location = $path_parts['dirname'];
  351. if ($view->is_dir('/files_trashbin/keyfiles/' . $file)) {
  352. if ($source_location != '.') {
  353. $keyfile = \OC\Files\Filesystem::normalizePath($user . '/files_trashbin/keyfiles/' . $source_location . '/' . $filename);
  354. $sharekey = \OC\Files\Filesystem::normalizePath($user . '/files_trashbin/share-keys/' . $source_location . '/' . $filename);
  355. } else {
  356. $keyfile = \OC\Files\Filesystem::normalizePath($user . '/files_trashbin/keyfiles/' . $filename);
  357. $sharekey = \OC\Files\Filesystem::normalizePath($user . '/files_trashbin/share-keys/' . $filename);
  358. }
  359. } else {
  360. $keyfile = \OC\Files\Filesystem::normalizePath($user . '/files_trashbin/keyfiles/' . $source_location . '/' . $filename . '.key');
  361. }
  362. if ($timestamp) {
  363. $keyfile .= '.d' . $timestamp;
  364. }
  365. // disable proxy to prevent recursive calls
  366. $proxyStatus = \OC_FileProxy::$enabled;
  367. \OC_FileProxy::$enabled = false;
  368. if ($rootView->file_exists($keyfile)) {
  369. // handle directory
  370. if ($rootView->is_dir($keyfile)) {
  371. // handle keyfiles
  372. $size += self::calculateSize(new \OC\Files\View($keyfile));
  373. $rootView->rename($keyfile, $baseDir . '/keyfiles/' . $ownerPath);
  374. // handle share-keys
  375. if ($timestamp) {
  376. $sharekey .= '.d' . $timestamp;
  377. }
  378. $size += self::calculateSize(new \OC\Files\View($sharekey));
  379. $rootView->rename($sharekey, $baseDir . '/share-keys/' . $ownerPath);
  380. } else {
  381. // handle keyfiles
  382. $size += $rootView->filesize($keyfile);
  383. $rootView->rename($keyfile, $baseDir . '/keyfiles/' . $ownerPath . '.key');
  384. // handle share-keys
  385. $ownerShareKey = \OC\Files\Filesystem::normalizePath($user . '/files_trashbin/share-keys/' . $source_location . '/' . $filename . '.' . $user . '.shareKey');
  386. if ($timestamp) {
  387. $ownerShareKey .= '.d' . $timestamp;
  388. }
  389. $size += $rootView->filesize($ownerShareKey);
  390. // move only owners key
  391. $rootView->rename($ownerShareKey, $baseDir . '/share-keys/' . $ownerPath . '.' . $user . '.shareKey');
  392. // try to re-share if file is shared
  393. $filesystemView = new \OC_FilesystemView('/');
  394. $session = new \OCA\Encryption\Session($filesystemView);
  395. $util = new \OCA\Encryption\Util($filesystemView, $user);
  396. // fix the file size
  397. $absolutePath = \OC\Files\Filesystem::normalizePath('/' . $owner . '/files/' . $ownerPath);
  398. $util->fixFileSize($absolutePath);
  399. // get current sharing state
  400. $sharingEnabled = \OCP\Share::isEnabled();
  401. // get users sharing this file
  402. $usersSharing = $util->getSharingUsersArray($sharingEnabled, $target, $user);
  403. // Attempt to set shareKey
  404. $util->setSharedFileKeyfiles($session, $usersSharing, $target);
  405. }
  406. }
  407. // enable proxy
  408. \OC_FileProxy::$enabled = $proxyStatus;
  409. }
  410. return $size;
  411. }
  412. /**
  413. * @brief delete file from trash bin permanently
  414. *
  415. * @param $filename path to the file
  416. * @param $timestamp of deletion time
  417. *
  418. * @return size of deleted files
  419. */
  420. public static function delete($filename, $timestamp = null) {
  421. $user = \OCP\User::getUser();
  422. $view = new \OC\Files\View('/' . $user);
  423. $size = 0;
  424. $trashbinSize = self::getTrashbinSize($user);
  425. if ($trashbinSize === false || $trashbinSize < 0) {
  426. $trashbinSize = self::calculateSize(new \OC\Files\View('/' . $user . '/files_trashbin'));
  427. }
  428. if ($timestamp) {
  429. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
  430. $query->execute(array($user, $filename, $timestamp));
  431. $file = $filename . '.d' . $timestamp;
  432. } else {
  433. $file = $filename;
  434. }
  435. $size += self::deleteVersions($view, $file, $filename, $timestamp);
  436. $size += self::deleteEncryptionKeys($view, $file, $filename, $timestamp);
  437. if ($view->is_dir('/files_trashbin/files/' . $file)) {
  438. $size += self::calculateSize(new \OC\Files\View('/' . $user . '/files_trashbin/files/' . $file));
  439. } else {
  440. $size += $view->filesize('/files_trashbin/files/' . $file);
  441. }
  442. $view->unlink('/files_trashbin/files/' . $file);
  443. \OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => '/files_trashbin/files/' . $file));
  444. $trashbinSize -= $size;
  445. self::setTrashbinSize($user, $trashbinSize);
  446. return $size;
  447. }
  448. private static function deleteVersions($view, $file, $filename, $timestamp) {
  449. $size = 0;
  450. if (\OCP\App::isEnabled('files_versions')) {
  451. $user = \OCP\User::getUser();
  452. if ($view->is_dir('files_trashbin/versions/' . $file)) {
  453. $size += self::calculateSize(new \OC\Files\view('/' . $user . '/files_trashbin/versions/' . $file));
  454. $view->unlink('files_trashbin/versions/' . $file);
  455. } else if ($versions = self::getVersionsFromTrash($filename, $timestamp)) {
  456. foreach ($versions as $v) {
  457. if ($timestamp) {
  458. $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
  459. $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
  460. } else {
  461. $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
  462. $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
  463. }
  464. }
  465. }
  466. }
  467. return $size;
  468. }
  469. private static function deleteEncryptionKeys($view, $file, $filename, $timestamp) {
  470. $size = 0;
  471. if (\OCP\App::isEnabled('files_encryption')) {
  472. $user = \OCP\User::getUser();
  473. if ($view->is_dir('/files_trashbin/files/' . $file)) {
  474. $keyfile = \OC\Files\Filesystem::normalizePath('files_trashbin/keyfiles/' . $filename);
  475. $sharekeys = \OC\Files\Filesystem::normalizePath('files_trashbin/share-keys/' . $filename);
  476. } else {
  477. $keyfile = \OC\Files\Filesystem::normalizePath('files_trashbin/keyfiles/' . $filename . '.key');
  478. $sharekeys = \OC\Files\Filesystem::normalizePath('files_trashbin/share-keys/' . $filename . '.' . $user . '.shareKey');
  479. }
  480. if ($timestamp) {
  481. $keyfile .= '.d' . $timestamp;
  482. $sharekeys .= '.d' . $timestamp;
  483. }
  484. if ($view->file_exists($keyfile)) {
  485. if ($view->is_dir($keyfile)) {
  486. $size += self::calculateSize(new \OC\Files\View('/' . $user . '/' . $keyfile));
  487. $size += self::calculateSize(new \OC\Files\View('/' . $user . '/' . $sharekeys));
  488. } else {
  489. $size += $view->filesize($keyfile);
  490. $size += $view->filesize($sharekeys);
  491. }
  492. $view->unlink($keyfile);
  493. $view->unlink($sharekeys);
  494. }
  495. }
  496. return $size;
  497. }
  498. /**
  499. * check to see whether a file exists in trashbin
  500. * @param $filename path to the file
  501. * @param $timestamp of deletion time
  502. * @return true if file exists, otherwise false
  503. */
  504. public static function file_exists($filename, $timestamp = null) {
  505. $user = \OCP\User::getUser();
  506. $view = new \OC\Files\View('/' . $user);
  507. if ($timestamp) {
  508. $filename = $filename . '.d' . $timestamp;
  509. } else {
  510. $filename = $filename;
  511. }
  512. $target = \OC\Files\Filesystem::normalizePath('files_trashbin/files/' . $filename);
  513. return $view->file_exists($target);
  514. }
  515. /**
  516. * @brief deletes used space for trash bin in db if user was deleted
  517. *
  518. * @param type $uid id of deleted user
  519. * @return result of db delete operation
  520. */
  521. public static function deleteUser($uid) {
  522. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
  523. $result = $query->execute(array($uid));
  524. if ($result) {
  525. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trashsize` WHERE `user`=?');
  526. return $query->execute(array($uid));
  527. }
  528. return false;
  529. }
  530. /**
  531. * calculate remaining free space for trash bin
  532. *
  533. * @param $trashbinSize current size of the trash bin
  534. * @return available free space for trash bin
  535. */
  536. private static function calculateFreeSpace($trashbinSize) {
  537. $softQuota = true;
  538. $user = \OCP\User::getUser();
  539. $quota = \OC_Preferences::getValue($user, 'files', 'quota');
  540. $view = new \OC\Files\View('/' . $user);
  541. if ($quota === null || $quota === 'default') {
  542. $quota = \OC_Appconfig::getValue('files', 'default_quota');
  543. }
  544. if ($quota === null || $quota === 'none') {
  545. $quota = \OC\Files\Filesystem::free_space('/');
  546. $softQuota = false;
  547. } else {
  548. $quota = \OCP\Util::computerFileSize($quota);
  549. }
  550. // calculate available space for trash bin
  551. // subtract size of files and current trash bin size from quota
  552. if ($softQuota) {
  553. $rootInfo = $view->getFileInfo('/files/');
  554. $free = $quota - $rootInfo['size']; // remaining free space for user
  555. if ($free > 0) {
  556. $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
  557. } else {
  558. $availableSpace = $free - $trashbinSize;
  559. }
  560. } else {
  561. $availableSpace = $quota;
  562. }
  563. return $availableSpace;
  564. }
  565. /**
  566. * @brief resize trash bin if necessary after a new file was added to ownCloud
  567. * @param string $user user id
  568. */
  569. public static function resizeTrash($user) {
  570. $size = self::getTrashbinSize($user);
  571. if ($size === false || $size < 0) {
  572. $size = self::calculateSize(new \OC\Files\View('/' . $user . '/files_trashbin'));
  573. }
  574. $freeSpace = self::calculateFreeSpace($size);
  575. if ($freeSpace < 0) {
  576. $newSize = $size - self::expire($size);
  577. if ($newSize !== $size) {
  578. self::setTrashbinSize($user, $newSize);
  579. }
  580. }
  581. }
  582. /**
  583. * clean up the trash bin
  584. * @param current size of the trash bin
  585. * @return size of expired files
  586. */
  587. private static function expire($trashbinSize) {
  588. $user = \OCP\User::getUser();
  589. $view = new \OC\Files\View('/' . $user);
  590. $availableSpace = self::calculateFreeSpace($trashbinSize);
  591. $size = 0;
  592. $query = \OC_DB::prepare('SELECT `location`,`type`,`id`,`timestamp` FROM `*PREFIX*files_trash` WHERE `user`=?');
  593. $result = $query->execute(array($user))->fetchAll();
  594. $retention_obligation = \OC_Config::getValue('trashbin_retention_obligation', self::DEFAULT_RETENTION_OBLIGATION);
  595. $limit = time() - ($retention_obligation * 86400);
  596. foreach ($result as $r) {
  597. $timestamp = $r['timestamp'];
  598. $filename = $r['id'];
  599. if ($r['timestamp'] < $limit) {
  600. $size += self::delete($filename, $timestamp);
  601. \OC_Log::write('files_trashbin', 'remove "' . $filename . '" fom trash bin because it is older than ' . $retention_obligation, \OC_log::INFO);
  602. }
  603. }
  604. $availableSpace += $size;
  605. // if size limit for trash bin reached, delete oldest files in trash bin
  606. if ($availableSpace < 0) {
  607. $query = \OC_DB::prepare('SELECT `location`,`type`,`id`,`timestamp` FROM `*PREFIX*files_trash`'
  608. . ' WHERE `user`=? ORDER BY `timestamp` ASC');
  609. $result = $query->execute(array($user))->fetchAll();
  610. $length = count($result);
  611. $i = 0;
  612. while ($i < $length && $availableSpace < 0) {
  613. $tmp = self::delete($result[$i]['id'], $result[$i]['timestamp']);
  614. \OC_Log::write('files_trashbin', 'remove "' . $result[$i]['id'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', \OC_log::INFO);
  615. $availableSpace += $tmp;
  616. $size += $tmp;
  617. $i++;
  618. }
  619. }
  620. return $size;
  621. }
  622. /**
  623. * recursive copy to copy a whole directory
  624. *
  625. * @param $source source path, relative to the users files directory
  626. * @param $destination destination path relative to the users root directoy
  627. * @param $view file view for the users root directory
  628. */
  629. private static function copy_recursive($source, $destination, $view) {
  630. $size = 0;
  631. if ($view->is_dir('files' . $source)) {
  632. $view->mkdir($destination);
  633. $view->touch($destination, $view->filemtime('files' . $source));
  634. foreach (\OC_Files::getDirectoryContent($source) as $i) {
  635. $pathDir = $source . '/' . $i['name'];
  636. if ($view->is_dir('files' . $pathDir)) {
  637. $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
  638. } else {
  639. $size += $view->filesize('files' . $pathDir);
  640. $view->copy('files' . $pathDir, $destination . '/' . $i['name']);
  641. $view->touch($destination . '/' . $i['name'], $view->filemtime('files' . $pathDir));
  642. }
  643. }
  644. } else {
  645. $size += $view->filesize('files' . $source);
  646. $view->copy('files' . $source, $destination);
  647. $view->touch($destination, $view->filemtime('files' . $source));
  648. }
  649. return $size;
  650. }
  651. /**
  652. * find all versions which belong to the file we want to restore
  653. * @param $filename name of the file which should be restored
  654. * @param $timestamp timestamp when the file was deleted
  655. */
  656. private static function getVersionsFromTrash($filename, $timestamp) {
  657. $view = new \OC\Files\View('/' . \OCP\User::getUser() . '/files_trashbin/versions');
  658. $versionsName = $view->getLocalFile($filename) . '.v';
  659. $escapedVersionsName = preg_replace('/(\*|\?|\[)/', '[$1]', $versionsName);
  660. $versions = array();
  661. if ($timestamp) {
  662. // fetch for old versions
  663. $matches = glob($escapedVersionsName . '*.d' . $timestamp);
  664. $offset = -strlen($timestamp) - 2;
  665. } else {
  666. $matches = glob($escapedVersionsName . '*');
  667. }
  668. foreach ($matches as $ma) {
  669. if ($timestamp) {
  670. $parts = explode('.v', substr($ma, 0, $offset));
  671. $versions[] = ( end($parts) );
  672. } else {
  673. $parts = explode('.v', $ma);
  674. $versions[] = ( end($parts) );
  675. }
  676. }
  677. return $versions;
  678. }
  679. /**
  680. * find unique extension for restored file if a file with the same name already exists
  681. * @param $location where the file should be restored
  682. * @param $filename name of the file
  683. * @param $view filesystem view relative to users root directory
  684. * @return string with unique extension
  685. */
  686. private static function getUniqueFilename($location, $filename, $view) {
  687. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  688. $name = pathinfo($filename, PATHINFO_FILENAME);
  689. $l = \OC_L10N::get('files_trashbin');
  690. // if extension is not empty we set a dot in front of it
  691. if ($ext !== '') {
  692. $ext = '.' . $ext;
  693. }
  694. if ($view->file_exists('files' . $location . '/' . $filename)) {
  695. $i = 2;
  696. $uniqueName = $name . " (".$l->t("restored").")". $ext;
  697. while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
  698. $uniqueName = $name . " (".$l->t("restored") . " " . $i . ")" . $ext;
  699. $i++;
  700. }
  701. return $uniqueName;
  702. }
  703. return $filename;
  704. }
  705. /**
  706. * @brief get the size from a given root folder
  707. * @param $view file view on the root folder
  708. * @return size of the folder
  709. */
  710. private static function calculateSize($view) {
  711. $root = \OCP\Config::getSystemValue('datadirectory') . $view->getAbsolutePath('');
  712. if (!file_exists($root)) {
  713. return 0;
  714. }
  715. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
  716. $size = 0;
  717. foreach ($iterator as $path) {
  718. $relpath = substr($path, strlen($root) - 1);
  719. if (!$view->is_dir($relpath)) {
  720. $size += $view->filesize($relpath);
  721. }
  722. }
  723. return $size;
  724. }
  725. /**
  726. * get current size of trash bin from a given user
  727. *
  728. * @param $user user who owns the trash bin
  729. * @return mixed trash bin size or false if no trash bin size is stored
  730. */
  731. private static function getTrashbinSize($user) {
  732. $query = \OC_DB::prepare('SELECT `size` FROM `*PREFIX*files_trashsize` WHERE `user`=?');
  733. $result = $query->execute(array($user))->fetchAll();
  734. if ($result) {
  735. return (int)$result[0]['size'];
  736. }
  737. return false;
  738. }
  739. /**
  740. * write to the database how much space is in use for the trash bin
  741. *
  742. * @param $user owner of the trash bin
  743. * @param $size size of the trash bin
  744. */
  745. private static function setTrashbinSize($user, $size) {
  746. if (self::getTrashbinSize($user) === false) {
  747. $query = \OC_DB::prepare('INSERT INTO `*PREFIX*files_trashsize` (`size`, `user`) VALUES (?, ?)');
  748. } else {
  749. $query = \OC_DB::prepare('UPDATE `*PREFIX*files_trashsize` SET `size`=? WHERE `user`=?');
  750. }
  751. $query->execute(array($size, $user));
  752. }
  753. /**
  754. * register hooks
  755. */
  756. public static function registerHooks() {
  757. //Listen to delete file signal
  758. \OCP\Util::connectHook('OC_Filesystem', 'delete', "OCA\Files_Trashbin\Hooks", "remove_hook");
  759. //Listen to delete user signal
  760. \OCP\Util::connectHook('OC_User', 'pre_deleteUser', "OCA\Files_Trashbin\Hooks", "deleteUser_hook");
  761. //Listen to post write hook
  762. \OCP\Util::connectHook('OC_Filesystem', 'post_write', "OCA\Files_Trashbin\Hooks", "post_write_hook");
  763. }
  764. /**
  765. * @brief check if trash bin is empty for a given user
  766. * @param string $user
  767. */
  768. public static function isEmpty($user) {
  769. $view = new \OC\Files\View('/' . $user . '/files_trashbin');
  770. $content = $view->getDirectoryContent('/files');
  771. if ($content) {
  772. return false;
  773. }
  774. return true;
  775. }
  776. public static function preview_icon($path) {
  777. return \OC_Helper::linkToRoute( 'core_ajax_trashbin_preview', array('x' => 36, 'y' => 36, 'file' => urlencode($path) ));
  778. }
  779. }