Storage.php 27 KB

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