You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

trashbin.php 32KB

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