trashbin.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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. $trashbinSize -= $size;
  444. self::setTrashbinSize($user, $trashbinSize);
  445. return $size;
  446. }
  447. private static function deleteVersions($view, $file, $filename, $timestamp) {
  448. $size = 0;
  449. if (\OCP\App::isEnabled('files_versions')) {
  450. $user = \OCP\User::getUser();
  451. if ($view->is_dir('files_trashbin/versions/' . $file)) {
  452. $size += self::calculateSize(new \OC\Files\view('/' . $user . '/files_trashbin/versions/' . $file));
  453. $view->unlink('files_trashbin/versions/' . $file);
  454. } else if ($versions = self::getVersionsFromTrash($filename, $timestamp)) {
  455. foreach ($versions as $v) {
  456. if ($timestamp) {
  457. $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
  458. $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
  459. } else {
  460. $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
  461. $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
  462. }
  463. }
  464. }
  465. }
  466. return $size;
  467. }
  468. private static function deleteEncryptionKeys($view, $file, $filename, $timestamp) {
  469. $size = 0;
  470. if (\OCP\App::isEnabled('files_encryption')) {
  471. $user = \OCP\User::getUser();
  472. if ($view->is_dir('/files_trashbin/files/' . $file)) {
  473. $keyfile = \OC\Files\Filesystem::normalizePath('files_trashbin/keyfiles/' . $filename);
  474. $sharekeys = \OC\Files\Filesystem::normalizePath('files_trashbin/share-keys/' . $filename);
  475. } else {
  476. $keyfile = \OC\Files\Filesystem::normalizePath('files_trashbin/keyfiles/' . $filename . '.key');
  477. $sharekeys = \OC\Files\Filesystem::normalizePath('files_trashbin/share-keys/' . $filename . '.' . $user . '.shareKey');
  478. }
  479. if ($timestamp) {
  480. $keyfile .= '.d' . $timestamp;
  481. $sharekeys .= '.d' . $timestamp;
  482. }
  483. if ($view->file_exists($keyfile)) {
  484. if ($view->is_dir($keyfile)) {
  485. $size += self::calculateSize(new \OC\Files\View('/' . $user . '/' . $keyfile));
  486. $size += self::calculateSize(new \OC\Files\View('/' . $user . '/' . $sharekeys));
  487. } else {
  488. $size += $view->filesize($keyfile);
  489. $size += $view->filesize($sharekeys);
  490. }
  491. $view->unlink($keyfile);
  492. $view->unlink($sharekeys);
  493. }
  494. }
  495. return $size;
  496. }
  497. /**
  498. * check to see whether a file exists in trashbin
  499. * @param $filename path to the file
  500. * @param $timestamp of deletion time
  501. * @return true if file exists, otherwise false
  502. */
  503. public static function file_exists($filename, $timestamp = null) {
  504. $user = \OCP\User::getUser();
  505. $view = new \OC\Files\View('/' . $user);
  506. if ($timestamp) {
  507. $filename = $filename . '.d' . $timestamp;
  508. } else {
  509. $filename = $filename;
  510. }
  511. $target = \OC\Files\Filesystem::normalizePath('files_trashbin/files/' . $filename);
  512. return $view->file_exists($target);
  513. }
  514. /**
  515. * @brief deletes used space for trash bin in db if user was deleted
  516. *
  517. * @param type $uid id of deleted user
  518. * @return result of db delete operation
  519. */
  520. public static function deleteUser($uid) {
  521. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
  522. $result = $query->execute(array($uid));
  523. if ($result) {
  524. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trashsize` WHERE `user`=?');
  525. return $query->execute(array($uid));
  526. }
  527. return false;
  528. }
  529. /**
  530. * calculate remaining free space for trash bin
  531. *
  532. * @param $trashbinSize current size of the trash bin
  533. * @return available free space for trash bin
  534. */
  535. private static function calculateFreeSpace($trashbinSize) {
  536. $softQuota = true;
  537. $user = \OCP\User::getUser();
  538. $quota = \OC_Preferences::getValue($user, 'files', 'quota');
  539. $view = new \OC\Files\View('/' . $user);
  540. if ($quota === null || $quota === 'default') {
  541. $quota = \OC_Appconfig::getValue('files', 'default_quota');
  542. }
  543. if ($quota === null || $quota === 'none') {
  544. $quota = \OC\Files\Filesystem::free_space('/');
  545. $softQuota = false;
  546. } else {
  547. $quota = \OCP\Util::computerFileSize($quota);
  548. }
  549. // calculate available space for trash bin
  550. // subtract size of files and current trash bin size from quota
  551. if ($softQuota) {
  552. $rootInfo = $view->getFileInfo('/files/');
  553. $free = $quota - $rootInfo['size']; // remaining free space for user
  554. if ($free > 0) {
  555. $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
  556. } else {
  557. $availableSpace = $free - $trashbinSize;
  558. }
  559. } else {
  560. $availableSpace = $quota;
  561. }
  562. return $availableSpace;
  563. }
  564. /**
  565. * @brief resize trash bin if necessary after a new file was added to ownCloud
  566. * @param string $user user id
  567. */
  568. public static function resizeTrash($user) {
  569. $size = self::getTrashbinSize($user);
  570. if ($size === false || $size < 0) {
  571. $size = self::calculateSize(new \OC\Files\View('/' . $user . '/files_trashbin'));
  572. }
  573. $freeSpace = self::calculateFreeSpace($size);
  574. if ($freeSpace < 0) {
  575. $newSize = $size - self::expire($size);
  576. if ($newSize !== $size) {
  577. self::setTrashbinSize($user, $newSize);
  578. }
  579. }
  580. }
  581. /**
  582. * clean up the trash bin
  583. * @param current size of the trash bin
  584. * @return size of expired files
  585. */
  586. private static function expire($trashbinSize) {
  587. $user = \OCP\User::getUser();
  588. $view = new \OC\Files\View('/' . $user);
  589. $availableSpace = self::calculateFreeSpace($trashbinSize);
  590. $size = 0;
  591. $query = \OC_DB::prepare('SELECT `location`,`type`,`id`,`timestamp` FROM `*PREFIX*files_trash` WHERE `user`=?');
  592. $result = $query->execute(array($user))->fetchAll();
  593. $retention_obligation = \OC_Config::getValue('trashbin_retention_obligation', self::DEFAULT_RETENTION_OBLIGATION);
  594. $limit = time() - ($retention_obligation * 86400);
  595. foreach ($result as $r) {
  596. $timestamp = $r['timestamp'];
  597. $filename = $r['id'];
  598. if ($r['timestamp'] < $limit) {
  599. $size += self::delete($filename, $timestamp);
  600. \OC_Log::write('files_trashbin', 'remove "' . $filename . '" fom trash bin because it is older than ' . $retention_obligation, \OC_log::INFO);
  601. }
  602. }
  603. $availableSpace += $size;
  604. // if size limit for trash bin reached, delete oldest files in trash bin
  605. if ($availableSpace < 0) {
  606. $query = \OC_DB::prepare('SELECT `location`,`type`,`id`,`timestamp` FROM `*PREFIX*files_trash`'
  607. . ' WHERE `user`=? ORDER BY `timestamp` ASC');
  608. $result = $query->execute(array($user))->fetchAll();
  609. $length = count($result);
  610. $i = 0;
  611. while ($i < $length && $availableSpace < 0) {
  612. $tmp = self::delete($result[$i]['id'], $result[$i]['timestamp']);
  613. \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);
  614. $availableSpace += $tmp;
  615. $size += $tmp;
  616. $i++;
  617. }
  618. }
  619. return $size;
  620. }
  621. /**
  622. * recursive copy to copy a whole directory
  623. *
  624. * @param $source source path, relative to the users files directory
  625. * @param $destination destination path relative to the users root directoy
  626. * @param $view file view for the users root directory
  627. */
  628. private static function copy_recursive($source, $destination, $view) {
  629. $size = 0;
  630. if ($view->is_dir('files' . $source)) {
  631. $view->mkdir($destination);
  632. $view->touch($destination, $view->filemtime('files' . $source));
  633. foreach (\OC_Files::getDirectoryContent($source) as $i) {
  634. $pathDir = $source . '/' . $i['name'];
  635. if ($view->is_dir('files' . $pathDir)) {
  636. $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
  637. } else {
  638. $size += $view->filesize('files' . $pathDir);
  639. $view->copy('files' . $pathDir, $destination . '/' . $i['name']);
  640. $view->touch($destination . '/' . $i['name'], $view->filemtime('files' . $pathDir));
  641. }
  642. }
  643. } else {
  644. $size += $view->filesize('files' . $source);
  645. $view->copy('files' . $source, $destination);
  646. $view->touch($destination, $view->filemtime('files' . $source));
  647. }
  648. return $size;
  649. }
  650. /**
  651. * find all versions which belong to the file we want to restore
  652. * @param $filename name of the file which should be restored
  653. * @param $timestamp timestamp when the file was deleted
  654. */
  655. private static function getVersionsFromTrash($filename, $timestamp) {
  656. $view = new \OC\Files\View('/' . \OCP\User::getUser() . '/files_trashbin/versions');
  657. $versionsName = $view->getLocalFile($filename) . '.v';
  658. $escapedVersionsName = preg_replace('/(\*|\?|\[)/', '[$1]', $versionsName);
  659. $versions = array();
  660. if ($timestamp) {
  661. // fetch for old versions
  662. $matches = glob($escapedVersionsName . '*.d' . $timestamp);
  663. $offset = -strlen($timestamp) - 2;
  664. } else {
  665. $matches = glob($escapedVersionsName . '*');
  666. }
  667. foreach ($matches as $ma) {
  668. if ($timestamp) {
  669. $parts = explode('.v', substr($ma, 0, $offset));
  670. $versions[] = ( end($parts) );
  671. } else {
  672. $parts = explode('.v', $ma);
  673. $versions[] = ( end($parts) );
  674. }
  675. }
  676. return $versions;
  677. }
  678. /**
  679. * find unique extension for restored file if a file with the same name already exists
  680. * @param $location where the file should be restored
  681. * @param $filename name of the file
  682. * @param $view filesystem view relative to users root directory
  683. * @return string with unique extension
  684. */
  685. private static function getUniqueFilename($location, $filename, $view) {
  686. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  687. $name = pathinfo($filename, PATHINFO_FILENAME);
  688. $l = \OC_L10N::get('files_trashbin');
  689. // if extension is not empty we set a dot in front of it
  690. if ($ext !== '') {
  691. $ext = '.' . $ext;
  692. }
  693. if ($view->file_exists('files' . $location . '/' . $filename)) {
  694. $i = 2;
  695. $uniqueName = $name . " (".$l->t("restored").")". $ext;
  696. while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
  697. $uniqueName = $name . " (".$l->t("restored") . " " . $i . ")" . $ext;
  698. $i++;
  699. }
  700. return $uniqueName;
  701. }
  702. return $filename;
  703. }
  704. /**
  705. * @brief get the size from a given root folder
  706. * @param $view file view on the root folder
  707. * @return size of the folder
  708. */
  709. private static function calculateSize($view) {
  710. $root = \OCP\Config::getSystemValue('datadirectory') . $view->getAbsolutePath('');
  711. if (!file_exists($root)) {
  712. return 0;
  713. }
  714. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
  715. $size = 0;
  716. foreach ($iterator as $path) {
  717. $relpath = substr($path, strlen($root) - 1);
  718. if (!$view->is_dir($relpath)) {
  719. $size += $view->filesize($relpath);
  720. }
  721. }
  722. return $size;
  723. }
  724. /**
  725. * get current size of trash bin from a given user
  726. *
  727. * @param $user user who owns the trash bin
  728. * @return mixed trash bin size or false if no trash bin size is stored
  729. */
  730. private static function getTrashbinSize($user) {
  731. $query = \OC_DB::prepare('SELECT `size` FROM `*PREFIX*files_trashsize` WHERE `user`=?');
  732. $result = $query->execute(array($user))->fetchAll();
  733. if ($result) {
  734. return (int)$result[0]['size'];
  735. }
  736. return false;
  737. }
  738. /**
  739. * write to the database how much space is in use for the trash bin
  740. *
  741. * @param $user owner of the trash bin
  742. * @param $size size of the trash bin
  743. */
  744. private static function setTrashbinSize($user, $size) {
  745. if (self::getTrashbinSize($user) === false) {
  746. $query = \OC_DB::prepare('INSERT INTO `*PREFIX*files_trashsize` (`size`, `user`) VALUES (?, ?)');
  747. } else {
  748. $query = \OC_DB::prepare('UPDATE `*PREFIX*files_trashsize` SET `size`=? WHERE `user`=?');
  749. }
  750. $query->execute(array($size, $user));
  751. }
  752. /**
  753. * register hooks
  754. */
  755. public static function registerHooks() {
  756. //Listen to delete file signal
  757. \OCP\Util::connectHook('OC_Filesystem', 'delete', "OCA\Files_Trashbin\Hooks", "remove_hook");
  758. //Listen to delete user signal
  759. \OCP\Util::connectHook('OC_User', 'pre_deleteUser', "OCA\Files_Trashbin\Hooks", "deleteUser_hook");
  760. //Listen to post write hook
  761. \OCP\Util::connectHook('OC_Filesystem', 'post_write', "OCA\Files_Trashbin\Hooks", "post_write_hook");
  762. }
  763. /**
  764. * @brief check if trash bin is empty for a given user
  765. * @param string $user
  766. */
  767. public static function isEmpty($user) {
  768. $view = new \OC\Files\View('/' . $user . '/files_trashbin');
  769. $content = $view->getDirectoryContent('/files');
  770. if ($content) {
  771. return false;
  772. }
  773. return true;
  774. }
  775. public static function preview_icon($path) {
  776. return \OC_Helper::linkToRoute( 'core_ajax_trashbin_preview', array('x' => 36, 'y' => 36, 'file' => urlencode($path) ));
  777. }
  778. }