PageRenderTime 72ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/apps/files_trashbin/lib/trash.php

https://github.com/sezuan/core
PHP | 860 lines | 547 code | 119 blank | 194 comment | 114 complexity | d45a1a898d640faf517092d83a047943 MD5 | raw file
Possible License(s): AGPL-3.0, AGPL-1.0, MPL-2.0-no-copyleft-exception
  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 = 180;
  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($view, $file_path, $filename, $timestamp);
  92. $trashbinSize += self::retainEncryptionKeys($view, $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 \OC\Files\View $view
  103. * @param $file_path path to original file
  104. * @param $filename of deleted file
  105. * @param $timestamp when the file was deleted
  106. *
  107. * @return size of stored versions
  108. */
  109. private static function retainVersions($view, $file_path, $filename, $timestamp) {
  110. $size = 0;
  111. if (\OCP\App::isEnabled('files_versions')) {
  112. // disable proxy to prevent recursive calls
  113. $proxyStatus = \OC_FileProxy::$enabled;
  114. \OC_FileProxy::$enabled = false;
  115. $user = \OCP\User::getUser();
  116. $rootView = new \OC\Files\View('/');
  117. list($owner, $ownerPath) = self::getUidAndFilename($file_path);
  118. if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
  119. $size += self::calculateSize(new \OC\Files\View('/' . $owner . '/files_versions/' . $ownerPath));
  120. $rootView->rename($owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
  121. } else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
  122. foreach ($versions as $v) {
  123. $size += $rootView->filesize($owner . '/files_versions' . $v['path'] . '.v' . $v['version']);
  124. $rootView->rename($owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
  125. }
  126. }
  127. // enable proxy
  128. \OC_FileProxy::$enabled = $proxyStatus;
  129. }
  130. return $size;
  131. }
  132. /**
  133. * Move encryption keys to trash so that they can be restored later
  134. *
  135. * @param \OC\Files\View $view
  136. * @param $file_path path to original file
  137. * @param $filename of deleted file
  138. * @param $timestamp when the file was deleted
  139. *
  140. * @return size of encryption keys
  141. */
  142. private static function retainEncryptionKeys($view, $file_path, $filename, $timestamp) {
  143. $size = 0;
  144. if (\OCP\App::isEnabled('files_encryption')) {
  145. $user = \OCP\User::getUser();
  146. $rootView = new \OC\Files\View('/');
  147. list($owner, $ownerPath) = self::getUidAndFilename($file_path);
  148. $util = new \OCA\Encryption\Util(new \OC_FilesystemView('/'), $user);
  149. // disable proxy to prevent recursive calls
  150. $proxyStatus = \OC_FileProxy::$enabled;
  151. \OC_FileProxy::$enabled = false;
  152. if ($util->isSystemWideMountPoint($ownerPath)) {
  153. $baseDir = '/files_encryption/';
  154. } else {
  155. $baseDir = $owner . '/files_encryption/';
  156. }
  157. $keyfile = \OC\Files\Filesystem::normalizePath($baseDir . '/keyfiles/' . $ownerPath);
  158. if ($rootView->is_dir($keyfile) || $rootView->file_exists($keyfile . '.key')) {
  159. // move keyfiles
  160. if ($rootView->is_dir($keyfile)) {
  161. $size += self::calculateSize(new \OC\Files\View($keyfile));
  162. $rootView->rename($keyfile, $user . '/files_trashbin/keyfiles/' . $filename . '.d' . $timestamp);
  163. } else {
  164. $size += $rootView->filesize($keyfile . '.key');
  165. $rootView->rename($keyfile . '.key', $user . '/files_trashbin/keyfiles/' . $filename . '.key.d' . $timestamp);
  166. }
  167. }
  168. // retain share keys
  169. $sharekeys = \OC\Files\Filesystem::normalizePath($baseDir . '/share-keys/' . $ownerPath);
  170. if ($rootView->is_dir($sharekeys)) {
  171. $size += self::calculateSize(new \OC\Files\View($sharekeys));
  172. $rootView->rename($sharekeys, $user . '/files_trashbin/share-keys/' . $filename . '.d' . $timestamp);
  173. } else {
  174. // get local path to share-keys
  175. $localShareKeysPath = $rootView->getLocalFile($sharekeys);
  176. $escapedLocalShareKeysPath = preg_replace('/(\*|\?|\[)/', '[$1]', $localShareKeysPath);
  177. // handle share-keys
  178. $matches = glob($escapedLocalShareKeysPath . '*.shareKey');
  179. foreach ($matches as $src) {
  180. // get source file parts
  181. $pathinfo = pathinfo($src);
  182. // we only want to keep the owners key so we can access the private key
  183. $ownerShareKey = $filename . '.' . $user . '.shareKey';
  184. // if we found the share-key for the owner, we need to move it to files_trashbin
  185. if ($pathinfo['basename'] == $ownerShareKey) {
  186. // calculate size
  187. $size += $rootView->filesize($sharekeys . '.' . $user . '.shareKey');
  188. // move file
  189. $rootView->rename($sharekeys . '.' . $user . '.shareKey', $user . '/files_trashbin/share-keys/' . $ownerShareKey . '.d' . $timestamp);
  190. } else {
  191. // calculate size
  192. $size += filesize($src);
  193. // don't keep other share-keys
  194. unlink($src);
  195. }
  196. }
  197. }
  198. // enable proxy
  199. \OC_FileProxy::$enabled = $proxyStatus;
  200. }
  201. return $size;
  202. }
  203. /**
  204. * restore files from trash bin
  205. * @param $file path to the deleted file
  206. * @param $filename name of the file
  207. * @param $timestamp time when the file was deleted
  208. *
  209. * @return bool
  210. */
  211. public static function restore($file, $filename, $timestamp) {
  212. $user = \OCP\User::getUser();
  213. $view = new \OC\Files\View('/' . $user);
  214. $trashbinSize = self::getTrashbinSize($user);
  215. if ($trashbinSize === false || $trashbinSize < 0) {
  216. $trashbinSize = self::calculateSize(new \OC\Files\View('/' . $user . '/files_trashbin'));
  217. }
  218. if ($timestamp) {
  219. $query = \OC_DB::prepare('SELECT `location`,`type` FROM `*PREFIX*files_trash`'
  220. . ' WHERE `user`=? AND `id`=? AND `timestamp`=?');
  221. $result = $query->execute(array($user, $filename, $timestamp))->fetchAll();
  222. if (count($result) != 1) {
  223. \OC_Log::write('files_trashbin', 'trash bin database inconsistent!', \OC_Log::ERROR);
  224. return false;
  225. }
  226. // if location no longer exists, restore file in the root directory
  227. $location = $result[0]['location'];
  228. if ($result[0]['location'] != '/' &&
  229. (!$view->is_dir('files' . $result[0]['location']) ||
  230. !$view->isUpdatable('files' . $result[0]['location']))) {
  231. $location = '';
  232. }
  233. } else {
  234. $path_parts = pathinfo($file);
  235. $result[] = array(
  236. 'location' => $path_parts['dirname'],
  237. 'type' => $view->is_dir('/files_trashbin/files/' . $file) ? 'dir' : 'files',
  238. );
  239. $location = '';
  240. }
  241. $source = \OC\Files\Filesystem::normalizePath('files_trashbin/files/' . $file);
  242. $target = \OC\Files\Filesystem::normalizePath('files/' . $location . '/' . $filename);
  243. // we need a extension in case a file/dir with the same name already exists
  244. $ext = self::getUniqueExtension($location, $filename, $view);
  245. $mtime = $view->filemtime($source);
  246. // disable proxy to prevent recursive calls
  247. $proxyStatus = \OC_FileProxy::$enabled;
  248. \OC_FileProxy::$enabled = false;
  249. // restore file
  250. $restoreResult = $view->rename($source, $target . $ext);
  251. // handle the restore result
  252. if ($restoreResult) {
  253. $fakeRoot = $view->getRoot();
  254. $view->chroot('/' . $user . '/files');
  255. $view->touch('/' . $location . '/' . $filename . $ext, $mtime);
  256. $view->chroot($fakeRoot);
  257. \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => \OC\Files\Filesystem::normalizePath('/' . $location . '/' . $filename . $ext),
  258. 'trashPath' => \OC\Files\Filesystem::normalizePath($file)));
  259. if ($view->is_dir($target . $ext)) {
  260. $trashbinSize -= self::calculateSize(new \OC\Files\View('/' . $user . '/' . $target . $ext));
  261. } else {
  262. $trashbinSize -= $view->filesize($target . $ext);
  263. }
  264. $trashbinSize -= self::restoreVersions($view, $file, $filename, $ext, $location, $timestamp);
  265. $trashbinSize -= self::restoreEncryptionKeys($view, $file, $filename, $ext, $location, $timestamp);
  266. if ($timestamp) {
  267. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
  268. $query->execute(array($user, $filename, $timestamp));
  269. }
  270. self::setTrashbinSize($user, $trashbinSize);
  271. // enable proxy
  272. \OC_FileProxy::$enabled = $proxyStatus;
  273. return true;
  274. }
  275. // enable proxy
  276. \OC_FileProxy::$enabled = $proxyStatus;
  277. return false;
  278. }
  279. /**
  280. * @brief restore versions from trash bin
  281. *
  282. * @param \OC\Files\View $view file view
  283. * @param $file complete path to file
  284. * @param $filename name of file
  285. * @param $ext file extension in case a file with the same $filename already exists
  286. * @param $location location if file
  287. * @param $timestamp deleteion time
  288. *
  289. * @return size of restored versions
  290. */
  291. private static function restoreVersions($view, $file, $filename, $ext, $location, $timestamp) {
  292. $size = 0;
  293. if (\OCP\App::isEnabled('files_versions')) {
  294. // disable proxy to prevent recursive calls
  295. $proxyStatus = \OC_FileProxy::$enabled;
  296. \OC_FileProxy::$enabled = false;
  297. $user = \OCP\User::getUser();
  298. $rootView = new \OC\Files\View('/');
  299. $target = \OC\Files\Filesystem::normalizePath('/' . $location . '/' . $filename . $ext);
  300. list($owner, $ownerPath) = self::getUidAndFilename($target);
  301. if ($timestamp) {
  302. $versionedFile = $filename;
  303. } else {
  304. $versionedFile = $file;
  305. }
  306. if ($view->is_dir('/files_trashbin/versions/' . $file)) {
  307. $size += self::calculateSize(new \OC\Files\View('/' . $user . '/' . 'files_trashbin/versions/' . $file));
  308. $rootView->rename(\OC\Files\Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), \OC\Files\Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
  309. } else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp)) {
  310. foreach ($versions as $v) {
  311. if ($timestamp) {
  312. $size += $view->filesize('files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp);
  313. $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
  314. } else {
  315. $size += $view->filesize('files_trashbin/versions/' . $versionedFile . '.v' . $v);
  316. $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
  317. }
  318. }
  319. }
  320. // enable proxy
  321. \OC_FileProxy::$enabled = $proxyStatus;
  322. }
  323. return $size;
  324. }
  325. /**
  326. * @brief restore encryption keys from trash bin
  327. *
  328. * @param \OC\Files\View $view
  329. * @param $file complete path to file
  330. * @param $filename name of file
  331. * @param $ext file extension in case a file with the same $filename already exists
  332. * @param $location location of file
  333. * @param $timestamp deleteion time
  334. *
  335. * @return size of restored encrypted file
  336. */
  337. private static function restoreEncryptionKeys($view, $file, $filename, $ext, $location, $timestamp) {
  338. // Take care of encryption keys TODO! Get '.key' in file between file name and delete date (also for permanent delete!)
  339. $size = 0;
  340. if (\OCP\App::isEnabled('files_encryption')) {
  341. $user = \OCP\User::getUser();
  342. $rootView = new \OC\Files\View('/');
  343. $target = \OC\Files\Filesystem::normalizePath('/' . $location . '/' . $filename . $ext);
  344. list($owner, $ownerPath) = self::getUidAndFilename($target);
  345. $util = new \OCA\Encryption\Util(new \OC_FilesystemView('/'), $user);
  346. if ($util->isSystemWideMountPoint($ownerPath)) {
  347. $baseDir = '/files_encryption/';
  348. } else {
  349. $baseDir = $owner . '/files_encryption/';
  350. }
  351. $path_parts = pathinfo($file);
  352. $source_location = $path_parts['dirname'];
  353. if ($view->is_dir('/files_trashbin/keyfiles/' . $file)) {
  354. if ($source_location != '.') {
  355. $keyfile = \OC\Files\Filesystem::normalizePath($user . '/files_trashbin/keyfiles/' . $source_location . '/' . $filename);
  356. $sharekey = \OC\Files\Filesystem::normalizePath($user . '/files_trashbin/share-keys/' . $source_location . '/' . $filename);
  357. } else {
  358. $keyfile = \OC\Files\Filesystem::normalizePath($user . '/files_trashbin/keyfiles/' . $filename);
  359. $sharekey = \OC\Files\Filesystem::normalizePath($user . '/files_trashbin/share-keys/' . $filename);
  360. }
  361. } else {
  362. $keyfile = \OC\Files\Filesystem::normalizePath($user . '/files_trashbin/keyfiles/' . $source_location . '/' . $filename . '.key');
  363. }
  364. if ($timestamp) {
  365. $keyfile .= '.d' . $timestamp;
  366. }
  367. // disable proxy to prevent recursive calls
  368. $proxyStatus = \OC_FileProxy::$enabled;
  369. \OC_FileProxy::$enabled = false;
  370. if ($rootView->file_exists($keyfile)) {
  371. // handle directory
  372. if ($rootView->is_dir($keyfile)) {
  373. // handle keyfiles
  374. $size += self::calculateSize(new \OC\Files\View($keyfile));
  375. $rootView->rename($keyfile, $baseDir . '/keyfiles/' . $ownerPath);
  376. // handle share-keys
  377. if ($timestamp) {
  378. $sharekey .= '.d' . $timestamp;
  379. }
  380. $size += self::calculateSize(new \OC\Files\View($sharekey));
  381. $rootView->rename($sharekey, $baseDir . '/share-keys/' . $ownerPath);
  382. } else {
  383. // handle keyfiles
  384. $size += $rootView->filesize($keyfile);
  385. $rootView->rename($keyfile, $baseDir . '/keyfiles/' . $ownerPath . '.key');
  386. // handle share-keys
  387. $ownerShareKey = \OC\Files\Filesystem::normalizePath($user . '/files_trashbin/share-keys/' . $source_location . '/' . $filename . '.' . $user . '.shareKey');
  388. if ($timestamp) {
  389. $ownerShareKey .= '.d' . $timestamp;
  390. }
  391. $size += $rootView->filesize($ownerShareKey);
  392. // move only owners key
  393. $rootView->rename($ownerShareKey, $baseDir . '/share-keys/' . $ownerPath . '.' . $user . '.shareKey');
  394. // try to re-share if file is shared
  395. $filesystemView = new \OC_FilesystemView('/');
  396. $session = new \OCA\Encryption\Session($filesystemView);
  397. $util = new \OCA\Encryption\Util($filesystemView, $user);
  398. // fix the file size
  399. $absolutePath = \OC\Files\Filesystem::normalizePath('/' . $owner . '/files/' . $ownerPath);
  400. $util->fixFileSize($absolutePath);
  401. // get current sharing state
  402. $sharingEnabled = \OCP\Share::isEnabled();
  403. // get the final filename
  404. $target = \OC\Files\Filesystem::normalizePath($location . '/' . $filename);
  405. // get users sharing this file
  406. $usersSharing = $util->getSharingUsersArray($sharingEnabled, $target . $ext, $user);
  407. // Attempt to set shareKey
  408. $util->setSharedFileKeyfiles($session, $usersSharing, $target . $ext);
  409. }
  410. }
  411. // enable proxy
  412. \OC_FileProxy::$enabled = $proxyStatus;
  413. }
  414. return $size;
  415. }
  416. /**
  417. * @brief delete file from trash bin permanently
  418. *
  419. * @param $filename path to the file
  420. * @param $timestamp of deletion time
  421. *
  422. * @return size of deleted files
  423. */
  424. public static function delete($filename, $timestamp = null) {
  425. $user = \OCP\User::getUser();
  426. $view = new \OC\Files\View('/' . $user);
  427. $size = 0;
  428. $trashbinSize = self::getTrashbinSize($user);
  429. if ($trashbinSize === false || $trashbinSize < 0) {
  430. $trashbinSize = self::calculateSize(new \OC\Files\View('/' . $user . '/files_trashbin'));
  431. }
  432. if ($timestamp) {
  433. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
  434. $query->execute(array($user, $filename, $timestamp));
  435. $file = $filename . '.d' . $timestamp;
  436. } else {
  437. $file = $filename;
  438. }
  439. $size += self::deleteVersions($view, $file, $filename, $timestamp);
  440. $size += self::deleteEncryptionKeys($view, $file, $filename, $timestamp);
  441. if ($view->is_dir('/files_trashbin/files/' . $file)) {
  442. $size += self::calculateSize(new \OC\Files\View('/' . $user . '/files_trashbin/files/' . $file));
  443. } else {
  444. $size += $view->filesize('/files_trashbin/files/' . $file);
  445. }
  446. $view->unlink('/files_trashbin/files/' . $file);
  447. $trashbinSize -= $size;
  448. self::setTrashbinSize($user, $trashbinSize);
  449. return $size;
  450. }
  451. private static function deleteVersions($view, $file, $filename, $timestamp) {
  452. $size = 0;
  453. if (\OCP\App::isEnabled('files_versions')) {
  454. $user = \OCP\User::getUser();
  455. if ($view->is_dir('files_trashbin/versions/' . $file)) {
  456. $size += self::calculateSize(new \OC\Files\view('/' . $user . '/files_trashbin/versions/' . $file));
  457. $view->unlink('files_trashbin/versions/' . $file);
  458. } else if ($versions = self::getVersionsFromTrash($filename, $timestamp)) {
  459. foreach ($versions as $v) {
  460. if ($timestamp) {
  461. $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
  462. $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
  463. } else {
  464. $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
  465. $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
  466. }
  467. }
  468. }
  469. }
  470. return $size;
  471. }
  472. private static function deleteEncryptionKeys($view, $file, $filename, $timestamp) {
  473. $size = 0;
  474. if (\OCP\App::isEnabled('files_encryption')) {
  475. $user = \OCP\User::getUser();
  476. if ($view->is_dir('/files_trashbin/files/' . $file)) {
  477. $keyfile = \OC\Files\Filesystem::normalizePath('files_trashbin/keyfiles/' . $filename);
  478. $sharekeys = \OC\Files\Filesystem::normalizePath('files_trashbin/share-keys/' . $filename);
  479. } else {
  480. $keyfile = \OC\Files\Filesystem::normalizePath('files_trashbin/keyfiles/' . $filename . '.key');
  481. $sharekeys = \OC\Files\Filesystem::normalizePath('files_trashbin/share-keys/' . $filename . '.' . $user . '.shareKey');
  482. }
  483. if ($timestamp) {
  484. $keyfile .= '.d' . $timestamp;
  485. $sharekeys .= '.d' . $timestamp;
  486. }
  487. if ($view->file_exists($keyfile)) {
  488. if ($view->is_dir($keyfile)) {
  489. $size += self::calculateSize(new \OC\Files\View('/' . $user . '/' . $keyfile));
  490. $size += self::calculateSize(new \OC\Files\View('/' . $user . '/' . $sharekeys));
  491. } else {
  492. $size += $view->filesize($keyfile);
  493. $size += $view->filesize($sharekeys);
  494. }
  495. $view->unlink($keyfile);
  496. $view->unlink($sharekeys);
  497. }
  498. }
  499. return $size;
  500. }
  501. /**
  502. * check to see whether a file exists in trashbin
  503. * @param $filename path to the file
  504. * @param $timestamp of deletion time
  505. * @return true if file exists, otherwise false
  506. */
  507. public static function file_exists($filename, $timestamp = null) {
  508. $user = \OCP\User::getUser();
  509. $view = new \OC\Files\View('/' . $user);
  510. if ($timestamp) {
  511. $filename = $filename . '.d' . $timestamp;
  512. } else {
  513. $filename = $filename;
  514. }
  515. $target = \OC\Files\Filesystem::normalizePath('files_trashbin/files/' . $filename);
  516. return $view->file_exists($target);
  517. }
  518. /**
  519. * @brief deletes used space for trash bin in db if user was deleted
  520. *
  521. * @param type $uid id of deleted user
  522. * @return result of db delete operation
  523. */
  524. public static function deleteUser($uid) {
  525. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
  526. $result = $query->execute(array($uid));
  527. if ($result) {
  528. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trashsize` WHERE `user`=?');
  529. return $query->execute(array($uid));
  530. }
  531. return false;
  532. }
  533. /**
  534. * calculate remaining free space for trash bin
  535. *
  536. * @param $trashbinSize current size of the trash bin
  537. * @return available free space for trash bin
  538. */
  539. private static function calculateFreeSpace($trashbinSize) {
  540. $softQuota = true;
  541. $user = \OCP\User::getUser();
  542. $quota = \OC_Preferences::getValue($user, 'files', 'quota');
  543. $view = new \OC\Files\View('/' . $user);
  544. if ($quota === null || $quota === 'default') {
  545. $quota = \OC_Appconfig::getValue('files', 'default_quota');
  546. }
  547. if ($quota === null || $quota === 'none') {
  548. $quota = \OC\Files\Filesystem::free_space('/');
  549. $softQuota = false;
  550. } else {
  551. $quota = \OCP\Util::computerFileSize($quota);
  552. }
  553. // calculate available space for trash bin
  554. // subtract size of files and current trash bin size from quota
  555. if ($softQuota) {
  556. $rootInfo = $view->getFileInfo('/files/');
  557. $free = $quota - $rootInfo['size']; // remaining free space for user
  558. if ($free > 0) {
  559. $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
  560. } else {
  561. $availableSpace = $free - $trashbinSize;
  562. }
  563. } else {
  564. $availableSpace = $quota;
  565. }
  566. return $availableSpace;
  567. }
  568. /**
  569. * clean up the trash bin
  570. * @param current size of the trash bin
  571. */
  572. private static function expire($trashbinSize) {
  573. $user = \OCP\User::getUser();
  574. $view = new \OC\Files\View('/' . $user);
  575. $availableSpace = self::calculateFreeSpace($trashbinSize);
  576. $size = 0;
  577. $query = \OC_DB::prepare('SELECT `location`,`type`,`id`,`timestamp` FROM `*PREFIX*files_trash` WHERE `user`=?');
  578. $result = $query->execute(array($user))->fetchAll();
  579. $retention_obligation = \OC_Config::getValue('trashbin_retention_obligation', self::DEFAULT_RETENTION_OBLIGATION);
  580. $limit = time() - ($retention_obligation * 86400);
  581. foreach ($result as $r) {
  582. $timestamp = $r['timestamp'];
  583. $filename = $r['id'];
  584. if ($r['timestamp'] < $limit) {
  585. $size += self::delete($filename, $timestamp);
  586. \OC_Log::write('files_trashbin', 'remove "' . $filename . '" fom trash bin because it is older than ' . $retention_obligation, \OC_log::INFO);
  587. }
  588. }
  589. $availableSpace = $availableSpace + $size;
  590. // if size limit for trash bin reached, delete oldest files in trash bin
  591. if ($availableSpace < 0) {
  592. $query = \OC_DB::prepare('SELECT `location`,`type`,`id`,`timestamp` FROM `*PREFIX*files_trash`'
  593. . ' WHERE `user`=? ORDER BY `timestamp` ASC');
  594. $result = $query->execute(array($user))->fetchAll();
  595. $length = count($result);
  596. $i = 0;
  597. while ($i < $length && $availableSpace < 0) {
  598. $tmp = self::delete($result[$i]['id'], $result[$i]['timestamp']);
  599. \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);
  600. $availableSpace += $tmp;
  601. $size += $tmp;
  602. $i++;
  603. }
  604. }
  605. return $size;
  606. }
  607. /**
  608. * recursive copy to copy a whole directory
  609. *
  610. * @param $source source path, relative to the users files directory
  611. * @param $destination destination path relative to the users root directoy
  612. * @param $view file view for the users root directory
  613. */
  614. private static function copy_recursive($source, $destination, $view) {
  615. $size = 0;
  616. if ($view->is_dir('files' . $source)) {
  617. $view->mkdir($destination);
  618. $view->touch($destination, $view->filemtime('files' . $source));
  619. foreach (\OC_Files::getDirectoryContent($source) as $i) {
  620. $pathDir = $source . '/' . $i['name'];
  621. if ($view->is_dir('files' . $pathDir)) {
  622. $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
  623. } else {
  624. $size += $view->filesize('files' . $pathDir);
  625. $view->copy('files' . $pathDir, $destination . '/' . $i['name']);
  626. $view->touch($destination . '/' . $i['name'], $view->filemtime('files' . $pathDir));
  627. }
  628. }
  629. } else {
  630. $size += $view->filesize('files' . $source);
  631. $view->copy('files' . $source, $destination);
  632. $view->touch($destination, $view->filemtime('files' . $source));
  633. }
  634. return $size;
  635. }
  636. /**
  637. * find all versions which belong to the file we want to restore
  638. * @param $filename name of the file which should be restored
  639. * @param $timestamp timestamp when the file was deleted
  640. */
  641. private static function getVersionsFromTrash($filename, $timestamp) {
  642. $view = new \OC\Files\View('/' . \OCP\User::getUser() . '/files_trashbin/versions');
  643. $versionsName = $view->getLocalFile($filename) . '.v';
  644. $escapedVersionsName = preg_replace('/(\*|\?|\[)/', '[$1]', $versionsName);
  645. $versions = array();
  646. if ($timestamp) {
  647. // fetch for old versions
  648. $matches = glob($escapedVersionsName . '*.d' . $timestamp);
  649. $offset = -strlen($timestamp) - 2;
  650. } else {
  651. $matches = glob($escapedVersionsName . '*');
  652. }
  653. foreach ($matches as $ma) {
  654. if ($timestamp) {
  655. $parts = explode('.v', substr($ma, 0, $offset));
  656. $versions[] = ( end($parts) );
  657. } else {
  658. $parts = explode('.v', $ma);
  659. $versions[] = ( end($parts) );
  660. }
  661. }
  662. return $versions;
  663. }
  664. /**
  665. * find unique extension for restored file if a file with the same name already exists
  666. * @param $location where the file should be restored
  667. * @param $filename name of the file
  668. * @param $view filesystem view relative to users root directory
  669. * @return string with unique extension
  670. */
  671. private static function getUniqueExtension($location, $filename, $view) {
  672. $ext = '';
  673. if ($view->file_exists('files' . $location . '/' . $filename)) {
  674. $tmpext = '.restored';
  675. $ext = $tmpext;
  676. $i = 1;
  677. while ($view->file_exists('files' . $location . '/' . $filename . $ext)) {
  678. $ext = $tmpext . $i;
  679. $i++;
  680. }
  681. }
  682. return $ext;
  683. }
  684. /**
  685. * @brief get the size from a given root folder
  686. * @param $view file view on the root folder
  687. * @return size of the folder
  688. */
  689. private static function calculateSize($view) {
  690. $root = \OCP\Config::getSystemValue('datadirectory') . $view->getAbsolutePath('');
  691. if (!file_exists($root)) {
  692. return 0;
  693. }
  694. $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
  695. $size = 0;
  696. foreach ($iterator as $path) {
  697. $relpath = substr($path, strlen($root) - 1);
  698. if (!$view->is_dir($relpath)) {
  699. $size += $view->filesize($relpath);
  700. }
  701. }
  702. return $size;
  703. }
  704. /**
  705. * get current size of trash bin from a given user
  706. *
  707. * @param $user user who owns the trash bin
  708. * @return mixed trash bin size or false if no trash bin size is stored
  709. */
  710. private static function getTrashbinSize($user) {
  711. $query = \OC_DB::prepare('SELECT `size` FROM `*PREFIX*files_trashsize` WHERE `user`=?');
  712. $result = $query->execute(array($user))->fetchAll();
  713. if ($result) {
  714. return $result[0]['size'];
  715. }
  716. return false;
  717. }
  718. /**
  719. * write to the database how much space is in use for the trash bin
  720. *
  721. * @param $user owner of the trash bin
  722. * @param $size size of the trash bin
  723. */
  724. private static function setTrashbinSize($user, $size) {
  725. if (self::getTrashbinSize($user) === false) {
  726. $query = \OC_DB::prepare('INSERT INTO `*PREFIX*files_trashsize` (`size`, `user`) VALUES (?, ?)');
  727. } else {
  728. $query = \OC_DB::prepare('UPDATE `*PREFIX*files_trashsize` SET `size`=? WHERE `user`=?');
  729. }
  730. $query->execute(array($size, $user));
  731. }
  732. /**
  733. * register hooks
  734. */
  735. public static function registerHooks() {
  736. //Listen to delete file signal
  737. \OCP\Util::connectHook('OC_Filesystem', 'delete', "OCA\Files_Trashbin\Hooks", "remove_hook");
  738. //Listen to delete user signal
  739. \OCP\Util::connectHook('OC_User', 'pre_deleteUser', "OCA\Files_Trashbin\Hooks", "deleteUser_hook");
  740. }
  741. }