trashbin.php 35 KB

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