Storage.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Bjoern Schiessle <bjoern@schiessle.org>
  8. * @author Björn Schießle <bjoern@schiessle.org>
  9. * @author Carlos Damken <carlos@damken.com>
  10. * @author Felix Moeller <mail@felixmoeller.de>
  11. * @author Georg Ehrke <georg@owncloud.com>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  14. * @author Lukas Reschke <lukas@statuscode.ch>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Robin Appelman <robin@icewind.nl>
  17. * @author Robin McCorkell <robin@mccorkell.me.uk>
  18. * @author Thomas Müller <thomas.mueller@tmit.eu>
  19. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  20. * @author Vincent Petry <pvince81@owncloud.com>
  21. *
  22. * @license AGPL-3.0
  23. *
  24. * This code is free software: you can redistribute it and/or modify
  25. * it under the terms of the GNU Affero General Public License, version 3,
  26. * as published by the Free Software Foundation.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU Affero General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Affero General Public License, version 3,
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>
  35. *
  36. */
  37. /**
  38. * Versions
  39. *
  40. * A class to handle the versioning of files.
  41. */
  42. namespace OCA\Files_Versions;
  43. use OC\Files\Filesystem;
  44. use OC\Files\View;
  45. use OCA\Files_Versions\AppInfo\Application;
  46. use OCA\Files_Versions\Command\Expire;
  47. use OCP\Files\NotFoundException;
  48. use OCP\Lock\ILockingProvider;
  49. use OCP\User;
  50. class Storage {
  51. const DEFAULTENABLED=true;
  52. const DEFAULTMAXSIZE=50; // unit: percentage; 50% of available disk space/quota
  53. const VERSIONS_ROOT = 'files_versions/';
  54. const DELETE_TRIGGER_MASTER_REMOVED = 0;
  55. const DELETE_TRIGGER_RETENTION_CONSTRAINT = 1;
  56. const DELETE_TRIGGER_QUOTA_EXCEEDED = 2;
  57. // files for which we can remove the versions after the delete operation was successful
  58. private static $deletedFiles = array();
  59. private static $sourcePathAndUser = array();
  60. private static $max_versions_per_interval = array(
  61. //first 10sec, one version every 2sec
  62. 1 => array('intervalEndsAfter' => 10, 'step' => 2),
  63. //next minute, one version every 10sec
  64. 2 => array('intervalEndsAfter' => 60, 'step' => 10),
  65. //next hour, one version every minute
  66. 3 => array('intervalEndsAfter' => 3600, 'step' => 60),
  67. //next 24h, one version every hour
  68. 4 => array('intervalEndsAfter' => 86400, 'step' => 3600),
  69. //next 30days, one version per day
  70. 5 => array('intervalEndsAfter' => 2592000, 'step' => 86400),
  71. //until the end one version per week
  72. 6 => array('intervalEndsAfter' => -1, 'step' => 604800),
  73. );
  74. /** @var \OCA\Files_Versions\AppInfo\Application */
  75. private static $application;
  76. /**
  77. * get the UID of the owner of the file and the path to the file relative to
  78. * owners files folder
  79. *
  80. * @param string $filename
  81. * @return array
  82. * @throws \OC\User\NoUserException
  83. */
  84. public static function getUidAndFilename($filename) {
  85. $uid = Filesystem::getOwner($filename);
  86. $userManager = \OC::$server->getUserManager();
  87. // if the user with the UID doesn't exists, e.g. because the UID points
  88. // to a remote user with a federated cloud ID we use the current logged-in
  89. // user. We need a valid local user to create the versions
  90. if (!$userManager->userExists($uid)) {
  91. $uid = User::getUser();
  92. }
  93. Filesystem::initMountPoints($uid);
  94. if ( $uid != User::getUser() ) {
  95. $info = Filesystem::getFileInfo($filename);
  96. $ownerView = new View('/'.$uid.'/files');
  97. try {
  98. $filename = $ownerView->getPath($info['fileid']);
  99. // make sure that the file name doesn't end with a trailing slash
  100. // can for example happen single files shared across servers
  101. $filename = rtrim($filename, '/');
  102. } catch (NotFoundException $e) {
  103. $filename = null;
  104. }
  105. }
  106. return [$uid, $filename];
  107. }
  108. /**
  109. * Remember the owner and the owner path of the source file
  110. *
  111. * @param string $source source path
  112. */
  113. public static function setSourcePathAndUser($source) {
  114. list($uid, $path) = self::getUidAndFilename($source);
  115. self::$sourcePathAndUser[$source] = array('uid' => $uid, 'path' => $path);
  116. }
  117. /**
  118. * Gets the owner and the owner path from the source path
  119. *
  120. * @param string $source source path
  121. * @return array with user id and path
  122. */
  123. public static function getSourcePathAndUser($source) {
  124. if (isset(self::$sourcePathAndUser[$source])) {
  125. $uid = self::$sourcePathAndUser[$source]['uid'];
  126. $path = self::$sourcePathAndUser[$source]['path'];
  127. unset(self::$sourcePathAndUser[$source]);
  128. } else {
  129. $uid = $path = false;
  130. }
  131. return array($uid, $path);
  132. }
  133. /**
  134. * get current size of all versions from a given user
  135. *
  136. * @param string $user user who owns the versions
  137. * @return int versions size
  138. */
  139. private static function getVersionsSize($user) {
  140. $view = new View('/' . $user);
  141. $fileInfo = $view->getFileInfo('/files_versions');
  142. return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
  143. }
  144. /**
  145. * store a new version of a file.
  146. */
  147. public static function store($filename) {
  148. if(\OCP\Config::getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true') {
  149. // if the file gets streamed we need to remove the .part extension
  150. // to get the right target
  151. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  152. if ($ext === 'part') {
  153. $filename = substr($filename, 0, strlen($filename) - 5);
  154. }
  155. // we only handle existing files
  156. if (! Filesystem::file_exists($filename) || Filesystem::is_dir($filename)) {
  157. return false;
  158. }
  159. list($uid, $filename) = self::getUidAndFilename($filename);
  160. $files_view = new View('/'.$uid .'/files');
  161. $users_view = new View('/'.$uid);
  162. // no use making versions for empty files
  163. if ($files_view->filesize($filename) === 0) {
  164. return false;
  165. }
  166. // create all parent folders
  167. self::createMissingDirectories($filename, $users_view);
  168. self::scheduleExpire($uid, $filename);
  169. // store a new version of a file
  170. $mtime = $users_view->filemtime('files/' . $filename);
  171. $users_view->copy('files/' . $filename, 'files_versions/' . $filename . '.v' . $mtime);
  172. // call getFileInfo to enforce a file cache entry for the new version
  173. $users_view->getFileInfo('files_versions/' . $filename . '.v' . $mtime);
  174. }
  175. }
  176. /**
  177. * mark file as deleted so that we can remove the versions if the file is gone
  178. * @param string $path
  179. */
  180. public static function markDeletedFile($path) {
  181. list($uid, $filename) = self::getUidAndFilename($path);
  182. self::$deletedFiles[$path] = array(
  183. 'uid' => $uid,
  184. 'filename' => $filename);
  185. }
  186. /**
  187. * delete the version from the storage and cache
  188. *
  189. * @param View $view
  190. * @param string $path
  191. */
  192. protected static function deleteVersion($view, $path) {
  193. $view->unlink($path);
  194. /**
  195. * @var \OC\Files\Storage\Storage $storage
  196. * @var string $internalPath
  197. */
  198. list($storage, $internalPath) = $view->resolvePath($path);
  199. $cache = $storage->getCache($internalPath);
  200. $cache->remove($internalPath);
  201. }
  202. /**
  203. * Delete versions of a file
  204. */
  205. public static function delete($path) {
  206. $deletedFile = self::$deletedFiles[$path];
  207. $uid = $deletedFile['uid'];
  208. $filename = $deletedFile['filename'];
  209. if (!Filesystem::file_exists($path)) {
  210. $view = new View('/' . $uid . '/files_versions');
  211. $versions = self::getVersions($uid, $filename);
  212. if (!empty($versions)) {
  213. foreach ($versions as $v) {
  214. \OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED));
  215. self::deleteVersion($view, $filename . '.v' . $v['version']);
  216. \OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED));
  217. }
  218. }
  219. }
  220. unset(self::$deletedFiles[$path]);
  221. }
  222. /**
  223. * Rename or copy versions of a file of the given paths
  224. *
  225. * @param string $sourcePath source path of the file to move, relative to
  226. * the currently logged in user's "files" folder
  227. * @param string $targetPath target path of the file to move, relative to
  228. * the currently logged in user's "files" folder
  229. * @param string $operation can be 'copy' or 'rename'
  230. */
  231. public static function renameOrCopy($sourcePath, $targetPath, $operation) {
  232. list($sourceOwner, $sourcePath) = self::getSourcePathAndUser($sourcePath);
  233. // it was a upload of a existing file if no old path exists
  234. // in this case the pre-hook already called the store method and we can
  235. // stop here
  236. if ($sourcePath === false) {
  237. return true;
  238. }
  239. list($targetOwner, $targetPath) = self::getUidAndFilename($targetPath);
  240. $sourcePath = ltrim($sourcePath, '/');
  241. $targetPath = ltrim($targetPath, '/');
  242. $rootView = new View('');
  243. // did we move a directory ?
  244. if ($rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
  245. // does the directory exists for versions too ?
  246. if ($rootView->is_dir('/' . $sourceOwner . '/files_versions/' . $sourcePath)) {
  247. // create missing dirs if necessary
  248. self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
  249. // move the directory containing the versions
  250. $rootView->$operation(
  251. '/' . $sourceOwner . '/files_versions/' . $sourcePath,
  252. '/' . $targetOwner . '/files_versions/' . $targetPath
  253. );
  254. }
  255. } else if ($versions = Storage::getVersions($sourceOwner, '/' . $sourcePath)) {
  256. // create missing dirs if necessary
  257. self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
  258. foreach ($versions as $v) {
  259. // move each version one by one to the target directory
  260. $rootView->$operation(
  261. '/' . $sourceOwner . '/files_versions/' . $sourcePath.'.v' . $v['version'],
  262. '/' . $targetOwner . '/files_versions/' . $targetPath.'.v'.$v['version']
  263. );
  264. }
  265. }
  266. // if we moved versions directly for a file, schedule expiration check for that file
  267. if (!$rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
  268. self::scheduleExpire($targetOwner, $targetPath);
  269. }
  270. }
  271. /**
  272. * Rollback to an old version of a file.
  273. *
  274. * @param string $file file name
  275. * @param int $revision revision timestamp
  276. * @return bool
  277. */
  278. public static function rollback($file, $revision) {
  279. if(\OCP\Config::getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true') {
  280. // add expected leading slash
  281. $file = '/' . ltrim($file, '/');
  282. list($uid, $filename) = self::getUidAndFilename($file);
  283. if ($uid === null || trim($filename, '/') === '') {
  284. return false;
  285. }
  286. $users_view = new View('/'.$uid);
  287. $files_view = new View('/'. User::getUser().'/files');
  288. $versionCreated = false;
  289. $fileInfo = $files_view->getFileInfo($file);
  290. // check if user has the permissions to revert a version
  291. if (!$fileInfo->isUpdateable()) {
  292. return false;
  293. }
  294. //first create a new version
  295. $version = 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename);
  296. if (!$users_view->file_exists($version)) {
  297. $users_view->copy('files'.$filename, 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename));
  298. $versionCreated = true;
  299. }
  300. $fileToRestore = 'files_versions' . $filename . '.v' . $revision;
  301. // Restore encrypted version of the old file for the newly restored file
  302. // This has to happen manually here since the file is manually copied below
  303. $oldVersion = $users_view->getFileInfo($fileToRestore)->getEncryptedVersion();
  304. $oldFileInfo = $users_view->getFileInfo($fileToRestore);
  305. $cache = $fileInfo->getStorage()->getCache();
  306. $cache->update(
  307. $fileInfo->getId(), [
  308. 'encrypted' => $oldVersion,
  309. 'encryptedVersion' => $oldVersion,
  310. 'size' => $oldFileInfo->getSize()
  311. ]
  312. );
  313. // rollback
  314. if (self::copyFileContents($users_view, $fileToRestore, 'files' . $filename)) {
  315. $files_view->touch($file, $revision);
  316. Storage::scheduleExpire($uid, $file);
  317. \OC_Hook::emit('\OCP\Versions', 'rollback', array(
  318. 'path' => $filename,
  319. 'revision' => $revision,
  320. ));
  321. return true;
  322. } else if ($versionCreated) {
  323. self::deleteVersion($users_view, $version);
  324. }
  325. }
  326. return false;
  327. }
  328. /**
  329. * Stream copy file contents from $path1 to $path2
  330. *
  331. * @param View $view view to use for copying
  332. * @param string $path1 source file to copy
  333. * @param string $path2 target file
  334. *
  335. * @return bool true for success, false otherwise
  336. */
  337. private static function copyFileContents($view, $path1, $path2) {
  338. /** @var \OC\Files\Storage\Storage $storage1 */
  339. list($storage1, $internalPath1) = $view->resolvePath($path1);
  340. /** @var \OC\Files\Storage\Storage $storage2 */
  341. list($storage2, $internalPath2) = $view->resolvePath($path2);
  342. $view->lockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
  343. $view->lockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
  344. // TODO add a proper way of overwriting a file while maintaining file ids
  345. if ($storage1->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage') || $storage2->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage')) {
  346. $source = $storage1->fopen($internalPath1, 'r');
  347. $target = $storage2->fopen($internalPath2, 'w');
  348. list(, $result) = \OC_Helper::streamCopy($source, $target);
  349. fclose($source);
  350. fclose($target);
  351. if ($result !== false) {
  352. $storage1->unlink($internalPath1);
  353. }
  354. } else {
  355. $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
  356. }
  357. $view->unlockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
  358. $view->unlockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
  359. return ($result !== false);
  360. }
  361. /**
  362. * get a list of all available versions of a file in descending chronological order
  363. * @param string $uid user id from the owner of the file
  364. * @param string $filename file to find versions of, relative to the user files dir
  365. * @param string $userFullPath
  366. * @return array versions newest version first
  367. */
  368. public static function getVersions($uid, $filename, $userFullPath = '') {
  369. $versions = array();
  370. if (empty($filename)) {
  371. return $versions;
  372. }
  373. // fetch for old versions
  374. $view = new View('/' . $uid . '/');
  375. $pathinfo = pathinfo($filename);
  376. $versionedFile = $pathinfo['basename'];
  377. $dir = Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
  378. $dirContent = false;
  379. if ($view->is_dir($dir)) {
  380. $dirContent = $view->opendir($dir);
  381. }
  382. if ($dirContent === false) {
  383. return $versions;
  384. }
  385. if (is_resource($dirContent)) {
  386. while (($entryName = readdir($dirContent)) !== false) {
  387. if (!Filesystem::isIgnoredDir($entryName)) {
  388. $pathparts = pathinfo($entryName);
  389. $filename = $pathparts['filename'];
  390. if ($filename === $versionedFile) {
  391. $pathparts = pathinfo($entryName);
  392. $timestamp = substr($pathparts['extension'], 1);
  393. $filename = $pathparts['filename'];
  394. $key = $timestamp . '#' . $filename;
  395. $versions[$key]['version'] = $timestamp;
  396. $versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp($timestamp);
  397. if (empty($userFullPath)) {
  398. $versions[$key]['preview'] = '';
  399. } else {
  400. $versions[$key]['preview'] = \OC::$server->getURLGenerator('files_version.Preview.getPreview', ['file' => $userFullPath, 'version' => $timestamp]);
  401. }
  402. $versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
  403. $versions[$key]['name'] = $versionedFile;
  404. $versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
  405. $versions[$key]['mimetype'] = \OC::$server->getMimeTypeDetector()->detectPath($versionedFile);
  406. }
  407. }
  408. }
  409. closedir($dirContent);
  410. }
  411. // sort with newest version first
  412. krsort($versions);
  413. return $versions;
  414. }
  415. /**
  416. * Expire versions that older than max version retention time
  417. * @param string $uid
  418. */
  419. public static function expireOlderThanMaxForUser($uid){
  420. $expiration = self::getExpiration();
  421. $threshold = $expiration->getMaxAgeAsTimestamp();
  422. $versions = self::getAllVersions($uid);
  423. if (!$threshold || !array_key_exists('all', $versions)) {
  424. return;
  425. }
  426. $toDelete = [];
  427. foreach (array_reverse($versions['all']) as $key => $version) {
  428. if (intval($version['version'])<$threshold) {
  429. $toDelete[$key] = $version;
  430. } else {
  431. //Versions are sorted by time - nothing mo to iterate.
  432. break;
  433. }
  434. }
  435. $view = new View('/' . $uid . '/files_versions');
  436. if (!empty($toDelete)) {
  437. foreach ($toDelete as $version) {
  438. \OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT));
  439. self::deleteVersion($view, $version['path'] . '.v' . $version['version']);
  440. \OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT));
  441. }
  442. }
  443. }
  444. /**
  445. * translate a timestamp into a string like "5 days ago"
  446. * @param int $timestamp
  447. * @return string for example "5 days ago"
  448. */
  449. private static function getHumanReadableTimestamp($timestamp) {
  450. $diff = time() - $timestamp;
  451. if ($diff < 60) { // first minute
  452. return $diff . " seconds ago";
  453. } elseif ($diff < 3600) { //first hour
  454. return round($diff / 60) . " minutes ago";
  455. } elseif ($diff < 86400) { // first day
  456. return round($diff / 3600) . " hours ago";
  457. } elseif ($diff < 604800) { //first week
  458. return round($diff / 86400) . " days ago";
  459. } elseif ($diff < 2419200) { //first month
  460. return round($diff / 604800) . " weeks ago";
  461. } elseif ($diff < 29030400) { // first year
  462. return round($diff / 2419200) . " months ago";
  463. } else {
  464. return round($diff / 29030400) . " years ago";
  465. }
  466. }
  467. /**
  468. * returns all stored file versions from a given user
  469. * @param string $uid id of the user
  470. * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
  471. */
  472. private static function getAllVersions($uid) {
  473. $view = new View('/' . $uid . '/');
  474. $dirs = array(self::VERSIONS_ROOT);
  475. $versions = array();
  476. while (!empty($dirs)) {
  477. $dir = array_pop($dirs);
  478. $files = $view->getDirectoryContent($dir);
  479. foreach ($files as $file) {
  480. $fileData = $file->getData();
  481. $filePath = $dir . '/' . $fileData['name'];
  482. if ($file['type'] === 'dir') {
  483. array_push($dirs, $filePath);
  484. } else {
  485. $versionsBegin = strrpos($filePath, '.v');
  486. $relPathStart = strlen(self::VERSIONS_ROOT);
  487. $version = substr($filePath, $versionsBegin + 2);
  488. $relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
  489. $key = $version . '#' . $relpath;
  490. $versions[$key] = array('path' => $relpath, 'timestamp' => $version);
  491. }
  492. }
  493. }
  494. // newest version first
  495. krsort($versions);
  496. $result = array();
  497. foreach ($versions as $key => $value) {
  498. $size = $view->filesize(self::VERSIONS_ROOT.'/'.$value['path'].'.v'.$value['timestamp']);
  499. $filename = $value['path'];
  500. $result['all'][$key]['version'] = $value['timestamp'];
  501. $result['all'][$key]['path'] = $filename;
  502. $result['all'][$key]['size'] = $size;
  503. $result['by_file'][$filename][$key]['version'] = $value['timestamp'];
  504. $result['by_file'][$filename][$key]['path'] = $filename;
  505. $result['by_file'][$filename][$key]['size'] = $size;
  506. }
  507. return $result;
  508. }
  509. /**
  510. * get list of files we want to expire
  511. * @param array $versions list of versions
  512. * @param integer $time
  513. * @param bool $quotaExceeded is versions storage limit reached
  514. * @return array containing the list of to deleted versions and the size of them
  515. */
  516. protected static function getExpireList($time, $versions, $quotaExceeded = false) {
  517. $expiration = self::getExpiration();
  518. if ($expiration->shouldAutoExpire()) {
  519. list($toDelete, $size) = self::getAutoExpireList($time, $versions);
  520. } else {
  521. $size = 0;
  522. $toDelete = []; // versions we want to delete
  523. }
  524. foreach ($versions as $key => $version) {
  525. if ($expiration->isExpired($version['version'], $quotaExceeded) && !isset($toDelete[$key])) {
  526. $size += $version['size'];
  527. $toDelete[$key] = $version['path'] . '.v' . $version['version'];
  528. }
  529. }
  530. return [$toDelete, $size];
  531. }
  532. /**
  533. * get list of files we want to expire
  534. * @param array $versions list of versions
  535. * @param integer $time
  536. * @return array containing the list of to deleted versions and the size of them
  537. */
  538. protected static function getAutoExpireList($time, $versions) {
  539. $size = 0;
  540. $toDelete = array(); // versions we want to delete
  541. $interval = 1;
  542. $step = Storage::$max_versions_per_interval[$interval]['step'];
  543. if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] == -1) {
  544. $nextInterval = -1;
  545. } else {
  546. $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
  547. }
  548. $firstVersion = reset($versions);
  549. $firstKey = key($versions);
  550. $prevTimestamp = $firstVersion['version'];
  551. $nextVersion = $firstVersion['version'] - $step;
  552. unset($versions[$firstKey]);
  553. foreach ($versions as $key => $version) {
  554. $newInterval = true;
  555. while ($newInterval) {
  556. if ($nextInterval == -1 || $prevTimestamp > $nextInterval) {
  557. if ($version['version'] > $nextVersion) {
  558. //distance between two version too small, mark to delete
  559. $toDelete[$key] = $version['path'] . '.v' . $version['version'];
  560. $size += $version['size'];
  561. \OCP\Util::writeLog('files_versions', 'Mark to expire '. $version['path'] .' next version should be ' . $nextVersion . " or smaller. (prevTimestamp: " . $prevTimestamp . "; step: " . $step, \OCP\Util::INFO);
  562. } else {
  563. $nextVersion = $version['version'] - $step;
  564. $prevTimestamp = $version['version'];
  565. }
  566. $newInterval = false; // version checked so we can move to the next one
  567. } else { // time to move on to the next interval
  568. $interval++;
  569. $step = Storage::$max_versions_per_interval[$interval]['step'];
  570. $nextVersion = $prevTimestamp - $step;
  571. if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] == -1) {
  572. $nextInterval = -1;
  573. } else {
  574. $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
  575. }
  576. $newInterval = true; // we changed the interval -> check same version with new interval
  577. }
  578. }
  579. }
  580. return array($toDelete, $size);
  581. }
  582. /**
  583. * Schedule versions expiration for the given file
  584. *
  585. * @param string $uid owner of the file
  586. * @param string $fileName file/folder for which to schedule expiration
  587. */
  588. private static function scheduleExpire($uid, $fileName) {
  589. // let the admin disable auto expire
  590. $expiration = self::getExpiration();
  591. if ($expiration->isEnabled()) {
  592. $command = new Expire($uid, $fileName);
  593. \OC::$server->getCommandBus()->push($command);
  594. }
  595. }
  596. /**
  597. * Expire versions which exceed the quota
  598. *
  599. * @param string $filename
  600. * @return bool|int|null
  601. */
  602. public static function expire($filename) {
  603. $config = \OC::$server->getConfig();
  604. $expiration = self::getExpiration();
  605. if($config->getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true' && $expiration->isEnabled()) {
  606. if (!Filesystem::file_exists($filename)) {
  607. return false;
  608. }
  609. list($uid, $filename) = self::getUidAndFilename($filename);
  610. if (empty($filename)) {
  611. // file maybe renamed or deleted
  612. return false;
  613. }
  614. $versionsFileview = new View('/'.$uid.'/files_versions');
  615. // get available disk space for user
  616. $user = \OC::$server->getUserManager()->get($uid);
  617. $softQuota = true;
  618. $quota = $user->getQuota();
  619. if ( $quota === null || $quota === 'none' ) {
  620. $quota = Filesystem::free_space('/');
  621. $softQuota = false;
  622. } else {
  623. $quota = \OCP\Util::computerFileSize($quota);
  624. }
  625. // make sure that we have the current size of the version history
  626. $versionsSize = self::getVersionsSize($uid);
  627. // calculate available space for version history
  628. // subtract size of files and current versions size from quota
  629. if ($quota >= 0) {
  630. if ($softQuota) {
  631. $files_view = new View('/' . $uid . '/files');
  632. $rootInfo = $files_view->getFileInfo('/', false);
  633. $free = $quota - $rootInfo['size']; // remaining free space for user
  634. if ($free > 0) {
  635. $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
  636. } else {
  637. $availableSpace = $free - $versionsSize;
  638. }
  639. } else {
  640. $availableSpace = $quota;
  641. }
  642. } else {
  643. $availableSpace = PHP_INT_MAX;
  644. }
  645. $allVersions = Storage::getVersions($uid, $filename);
  646. $time = time();
  647. list($toDelete, $sizeOfDeletedVersions) = self::getExpireList($time, $allVersions, $availableSpace <= 0);
  648. $availableSpace = $availableSpace + $sizeOfDeletedVersions;
  649. $versionsSize = $versionsSize - $sizeOfDeletedVersions;
  650. // if still not enough free space we rearrange the versions from all files
  651. if ($availableSpace <= 0) {
  652. $result = Storage::getAllVersions($uid);
  653. $allVersions = $result['all'];
  654. foreach ($result['by_file'] as $versions) {
  655. list($toDeleteNew, $size) = self::getExpireList($time, $versions, $availableSpace <= 0);
  656. $toDelete = array_merge($toDelete, $toDeleteNew);
  657. $sizeOfDeletedVersions += $size;
  658. }
  659. $availableSpace = $availableSpace + $sizeOfDeletedVersions;
  660. $versionsSize = $versionsSize - $sizeOfDeletedVersions;
  661. }
  662. foreach($toDelete as $key => $path) {
  663. \OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
  664. self::deleteVersion($versionsFileview, $path);
  665. \OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
  666. unset($allVersions[$key]); // update array with the versions we keep
  667. \OCP\Util::writeLog('files_versions', "Expire: " . $path, \OCP\Util::INFO);
  668. }
  669. // Check if enough space is available after versions are rearranged.
  670. // If not we delete the oldest versions until we meet the size limit for versions,
  671. // but always keep the two latest versions
  672. $numOfVersions = count($allVersions) -2 ;
  673. $i = 0;
  674. // sort oldest first and make sure that we start at the first element
  675. ksort($allVersions);
  676. reset($allVersions);
  677. while ($availableSpace < 0 && $i < $numOfVersions) {
  678. $version = current($allVersions);
  679. \OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
  680. self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
  681. \OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED));
  682. \OCP\Util::writeLog('files_versions', 'running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'] , \OCP\Util::INFO);
  683. $versionsSize -= $version['size'];
  684. $availableSpace += $version['size'];
  685. next($allVersions);
  686. $i++;
  687. }
  688. return $versionsSize; // finally return the new size of the version history
  689. }
  690. return false;
  691. }
  692. /**
  693. * Create recursively missing directories inside of files_versions
  694. * that match the given path to a file.
  695. *
  696. * @param string $filename $path to a file, relative to the user's
  697. * "files" folder
  698. * @param View $view view on data/user/
  699. */
  700. private static function createMissingDirectories($filename, $view) {
  701. $dirname = Filesystem::normalizePath(dirname($filename));
  702. $dirParts = explode('/', $dirname);
  703. $dir = "/files_versions";
  704. foreach ($dirParts as $part) {
  705. $dir = $dir . '/' . $part;
  706. if (!$view->file_exists($dir)) {
  707. $view->mkdir($dir);
  708. }
  709. }
  710. }
  711. /**
  712. * Static workaround
  713. * @return Expiration
  714. */
  715. protected static function getExpiration(){
  716. if (is_null(self::$application)) {
  717. self::$application = new Application();
  718. }
  719. return self::$application->getContainer()->query('Expiration');
  720. }
  721. }