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

storage.php 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. <?php
  2. /**
  3. * @author Bart Visscher <bartv@thisnet.nl>
  4. * @author Björn Schießle <schiessle@owncloud.com>
  5. * @author Felix Moeller <mail@felixmoeller.de>
  6. * @author Florin Peter <github@florin-peter.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@owncloud.com>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Robin Appelman <icewind@owncloud.com>
  13. * @author Robin McCorkell <rmccorkell@karoshi.org.uk>
  14. * @author Scrutinizer Auto-Fixer <auto-fixer@scrutinizer-ci.com>
  15. * @author Thomas Müller <thomas.mueller@tmit.eu>
  16. * @author Vincent Petry <pvince81@owncloud.com>
  17. *
  18. * @copyright Copyright (c) 2015, 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 OCA\Files_Versions\Command\Expire;
  41. class Storage {
  42. const DEFAULTENABLED=true;
  43. const DEFAULTMAXSIZE=50; // unit: percentage; 50% of available disk space/quota
  44. const VERSIONS_ROOT = 'files_versions/';
  45. // files for which we can remove the versions after the delete operation was successful
  46. private static $deletedFiles = array();
  47. private static $sourcePathAndUser = array();
  48. private static $max_versions_per_interval = array(
  49. //first 10sec, one version every 2sec
  50. 1 => array('intervalEndsAfter' => 10, 'step' => 2),
  51. //next minute, one version every 10sec
  52. 2 => array('intervalEndsAfter' => 60, 'step' => 10),
  53. //next hour, one version every minute
  54. 3 => array('intervalEndsAfter' => 3600, 'step' => 60),
  55. //next 24h, one version every hour
  56. 4 => array('intervalEndsAfter' => 86400, 'step' => 3600),
  57. //next 30days, one version per day
  58. 5 => array('intervalEndsAfter' => 2592000, 'step' => 86400),
  59. //until the end one version per week
  60. 6 => array('intervalEndsAfter' => -1, 'step' => 604800),
  61. );
  62. public static function getUidAndFilename($filename) {
  63. $uid = \OC\Files\Filesystem::getOwner($filename);
  64. \OC\Files\Filesystem::initMountPoints($uid);
  65. if ( $uid != \OCP\User::getUser() ) {
  66. $info = \OC\Files\Filesystem::getFileInfo($filename);
  67. $ownerView = new \OC\Files\View('/'.$uid.'/files');
  68. $filename = $ownerView->getPath($info['fileid']);
  69. }
  70. return array($uid, $filename);
  71. }
  72. /**
  73. * Remember the owner and the owner path of the source file
  74. *
  75. * @param string $source source path
  76. */
  77. public static function setSourcePathAndUser($source) {
  78. list($uid, $path) = self::getUidAndFilename($source);
  79. self::$sourcePathAndUser[$source] = array('uid' => $uid, 'path' => $path);
  80. }
  81. /**
  82. * Gets the owner and the owner path from the source path
  83. *
  84. * @param string $source source path
  85. * @return array with user id and path
  86. */
  87. public static function getSourcePathAndUser($source) {
  88. if (isset(self::$sourcePathAndUser[$source])) {
  89. $uid = self::$sourcePathAndUser[$source]['uid'];
  90. $path = self::$sourcePathAndUser[$source]['path'];
  91. unset(self::$sourcePathAndUser[$source]);
  92. } else {
  93. $uid = $path = false;
  94. }
  95. return array($uid, $path);
  96. }
  97. /**
  98. * get current size of all versions from a given user
  99. *
  100. * @param string $user user who owns the versions
  101. * @return int versions size
  102. */
  103. private static function getVersionsSize($user) {
  104. $view = new \OC\Files\View('/' . $user);
  105. $fileInfo = $view->getFileInfo('/files_versions');
  106. return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
  107. }
  108. /**
  109. * store a new version of a file.
  110. */
  111. public static function store($filename) {
  112. if(\OCP\Config::getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true') {
  113. // if the file gets streamed we need to remove the .part extension
  114. // to get the right target
  115. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  116. if ($ext === 'part') {
  117. $filename = substr($filename, 0, strlen($filename)-5);
  118. }
  119. list($uid, $filename) = self::getUidAndFilename($filename);
  120. $files_view = new \OC\Files\View('/'.$uid .'/files');
  121. $users_view = new \OC\Files\View('/'.$uid);
  122. // check if filename is a directory
  123. if($files_view->is_dir($filename)) {
  124. return false;
  125. }
  126. // we should have a source file to work with, and the file shouldn't
  127. // be empty
  128. $fileExists = $files_view->file_exists($filename);
  129. if (!($fileExists && $files_view->filesize($filename) > 0)) {
  130. return false;
  131. }
  132. // create all parent folders
  133. self::createMissingDirectories($filename, $users_view);
  134. $versionsSize = self::getVersionsSize($uid);
  135. // assumption: we need filesize($filename) for the new version +
  136. // some more free space for the modified file which might be
  137. // 1.5 times as large as the current version -> 2.5
  138. $neededSpace = $files_view->filesize($filename) * 2.5;
  139. self::scheduleExpire($uid, $filename, $versionsSize, $neededSpace);
  140. // store a new version of a file
  141. $mtime = $users_view->filemtime('files/' . $filename);
  142. $users_view->copy('files/' . $filename, 'files_versions/' . $filename . '.v' . $mtime);
  143. // call getFileInfo to enforce a file cache entry for the new version
  144. $users_view->getFileInfo('files_versions/' . $filename . '.v' . $mtime);
  145. }
  146. }
  147. /**
  148. * mark file as deleted so that we can remove the versions if the file is gone
  149. * @param string $path
  150. */
  151. public static function markDeletedFile($path) {
  152. list($uid, $filename) = self::getUidAndFilename($path);
  153. self::$deletedFiles[$path] = array(
  154. 'uid' => $uid,
  155. 'filename' => $filename);
  156. }
  157. /**
  158. * delete the version from the storage and cache
  159. *
  160. * @param \OC\Files\View $view
  161. * @param string $path
  162. */
  163. protected static function deleteVersion($view, $path) {
  164. $view->unlink($path);
  165. /**
  166. * @var \OC\Files\Storage\Storage $storage
  167. * @var string $internalPath
  168. */
  169. list($storage, $internalPath) = $view->resolvePath($path);
  170. $cache = $storage->getCache($internalPath);
  171. $cache->remove($internalPath);
  172. }
  173. /**
  174. * Delete versions of a file
  175. */
  176. public static function delete($path) {
  177. $deletedFile = self::$deletedFiles[$path];
  178. $uid = $deletedFile['uid'];
  179. $filename = $deletedFile['filename'];
  180. if (!\OC\Files\Filesystem::file_exists($path)) {
  181. $view = new \OC\Files\View('/' . $uid . '/files_versions');
  182. $versions = self::getVersions($uid, $filename);
  183. if (!empty($versions)) {
  184. foreach ($versions as $v) {
  185. \OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $path . $v['version']));
  186. self::deleteVersion($view, $filename . '.v' . $v['version']);
  187. \OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $path . $v['version']));
  188. }
  189. }
  190. }
  191. unset(self::$deletedFiles[$path]);
  192. }
  193. /**
  194. * Rename or copy versions of a file of the given paths
  195. *
  196. * @param string $sourcePath source path of the file to move, relative to
  197. * the currently logged in user's "files" folder
  198. * @param string $targetPath target path of the file to move, relative to
  199. * the currently logged in user's "files" folder
  200. * @param string $operation can be 'copy' or 'rename'
  201. */
  202. public static function renameOrCopy($sourcePath, $targetPath, $operation) {
  203. list($sourceOwner, $sourcePath) = self::getSourcePathAndUser($sourcePath);
  204. // it was a upload of a existing file if no old path exists
  205. // in this case the pre-hook already called the store method and we can
  206. // stop here
  207. if ($sourcePath === false) {
  208. return true;
  209. }
  210. list($targetOwner, $targetPath) = self::getUidAndFilename($targetPath);
  211. $sourcePath = ltrim($sourcePath, '/');
  212. $targetPath = ltrim($targetPath, '/');
  213. $rootView = new \OC\Files\View('');
  214. // did we move a directory ?
  215. if ($rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
  216. // does the directory exists for versions too ?
  217. if ($rootView->is_dir('/' . $sourceOwner . '/files_versions/' . $sourcePath)) {
  218. // create missing dirs if necessary
  219. self::createMissingDirectories($targetPath, new \OC\Files\View('/'. $targetOwner));
  220. // move the directory containing the versions
  221. $rootView->$operation(
  222. '/' . $sourceOwner . '/files_versions/' . $sourcePath,
  223. '/' . $targetOwner . '/files_versions/' . $targetPath
  224. );
  225. }
  226. } else if ($versions = Storage::getVersions($sourceOwner, '/' . $sourcePath)) {
  227. // create missing dirs if necessary
  228. self::createMissingDirectories($targetPath, new \OC\Files\View('/'. $targetOwner));
  229. foreach ($versions as $v) {
  230. // move each version one by one to the target directory
  231. $rootView->$operation(
  232. '/' . $sourceOwner . '/files_versions/' . $sourcePath.'.v' . $v['version'],
  233. '/' . $targetOwner . '/files_versions/' . $targetPath.'.v'.$v['version']
  234. );
  235. }
  236. }
  237. // if we moved versions directly for a file, schedule expiration check for that file
  238. if (!$rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
  239. self::scheduleExpire($targetOwner, $targetPath);
  240. }
  241. }
  242. /**
  243. * Rollback to an old version of a file.
  244. *
  245. * @param string $file file name
  246. * @param int $revision revision timestamp
  247. */
  248. public static function rollback($file, $revision) {
  249. if(\OCP\Config::getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true') {
  250. // add expected leading slash
  251. $file = '/' . ltrim($file, '/');
  252. list($uid, $filename) = self::getUidAndFilename($file);
  253. $users_view = new \OC\Files\View('/'.$uid);
  254. $files_view = new \OC\Files\View('/'.\OCP\User::getUser().'/files');
  255. $versionCreated = false;
  256. //first create a new version
  257. $version = 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename);
  258. if ( !$users_view->file_exists($version)) {
  259. $users_view->copy('files'.$filename, 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename));
  260. $versionCreated = true;
  261. }
  262. // rollback
  263. if (self::copyFileContents($users_view, 'files_versions' . $filename . '.v' . $revision, 'files' . $filename)) {
  264. $files_view->touch($file, $revision);
  265. Storage::scheduleExpire($uid, $file);
  266. return true;
  267. } else if ($versionCreated) {
  268. self::deleteVersion($users_view, $version);
  269. }
  270. }
  271. return false;
  272. }
  273. /**
  274. * Stream copy file contents from $path1 to $path2
  275. *
  276. * @param \OC\Files\View $view view to use for copying
  277. * @param string $path1 source file to copy
  278. * @param string $path2 target file
  279. *
  280. * @return bool true for success, false otherwise
  281. */
  282. private static function copyFileContents($view, $path1, $path2) {
  283. list($storage1, $internalPath1) = $view->resolvePath($path1);
  284. list($storage2, $internalPath2) = $view->resolvePath($path2);
  285. $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
  286. return ($result !== false);
  287. }
  288. /**
  289. * get a list of all available versions of a file in descending chronological order
  290. * @param string $uid user id from the owner of the file
  291. * @param string $filename file to find versions of, relative to the user files dir
  292. * @param string $userFullPath
  293. * @return array versions newest version first
  294. */
  295. public static function getVersions($uid, $filename, $userFullPath = '') {
  296. $versions = array();
  297. if (empty($filename)) {
  298. return $versions;
  299. }
  300. // fetch for old versions
  301. $view = new \OC\Files\View('/' . $uid . '/');
  302. $pathinfo = pathinfo($filename);
  303. $versionedFile = $pathinfo['basename'];
  304. $dir = \OC\Files\Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
  305. $dirContent = false;
  306. if ($view->is_dir($dir)) {
  307. $dirContent = $view->opendir($dir);
  308. }
  309. if ($dirContent === false) {
  310. return $versions;
  311. }
  312. if (is_resource($dirContent)) {
  313. while (($entryName = readdir($dirContent)) !== false) {
  314. if (!\OC\Files\Filesystem::isIgnoredDir($entryName)) {
  315. $pathparts = pathinfo($entryName);
  316. $filename = $pathparts['filename'];
  317. if ($filename === $versionedFile) {
  318. $pathparts = pathinfo($entryName);
  319. $timestamp = substr($pathparts['extension'], 1);
  320. $filename = $pathparts['filename'];
  321. $key = $timestamp . '#' . $filename;
  322. $versions[$key]['version'] = $timestamp;
  323. $versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp($timestamp);
  324. if (empty($userFullPath)) {
  325. $versions[$key]['preview'] = '';
  326. } else {
  327. $versions[$key]['preview'] = \OCP\Util::linkToRoute('core_ajax_versions_preview', array('file' => $userFullPath, 'version' => $timestamp));
  328. }
  329. $versions[$key]['path'] = \OC\Files\Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
  330. $versions[$key]['name'] = $versionedFile;
  331. $versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
  332. }
  333. }
  334. }
  335. closedir($dirContent);
  336. }
  337. // sort with newest version first
  338. krsort($versions);
  339. return $versions;
  340. }
  341. /**
  342. * translate a timestamp into a string like "5 days ago"
  343. * @param int $timestamp
  344. * @return string for example "5 days ago"
  345. */
  346. private static function getHumanReadableTimestamp($timestamp) {
  347. $diff = time() - $timestamp;
  348. if ($diff < 60) { // first minute
  349. return $diff . " seconds ago";
  350. } elseif ($diff < 3600) { //first hour
  351. return round($diff / 60) . " minutes ago";
  352. } elseif ($diff < 86400) { // first day
  353. return round($diff / 3600) . " hours ago";
  354. } elseif ($diff < 604800) { //first week
  355. return round($diff / 86400) . " days ago";
  356. } elseif ($diff < 2419200) { //first month
  357. return round($diff / 604800) . " weeks ago";
  358. } elseif ($diff < 29030400) { // first year
  359. return round($diff / 2419200) . " months ago";
  360. } else {
  361. return round($diff / 29030400) . " years ago";
  362. }
  363. }
  364. /**
  365. * returns all stored file versions from a given user
  366. * @param string $uid id of the user
  367. * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
  368. */
  369. private static function getAllVersions($uid) {
  370. $view = new \OC\Files\View('/' . $uid . '/');
  371. $dirs = array(self::VERSIONS_ROOT);
  372. $versions = array();
  373. while (!empty($dirs)) {
  374. $dir = array_pop($dirs);
  375. $files = $view->getDirectoryContent($dir);
  376. foreach ($files as $file) {
  377. if ($file['type'] === 'dir') {
  378. array_push($dirs, $file['path']);
  379. } else {
  380. $versionsBegin = strrpos($file['path'], '.v');
  381. $relPathStart = strlen(self::VERSIONS_ROOT);
  382. $version = substr($file['path'], $versionsBegin + 2);
  383. $relpath = substr($file['path'], $relPathStart, $versionsBegin - $relPathStart);
  384. $key = $version . '#' . $relpath;
  385. $versions[$key] = array('path' => $relpath, 'timestamp' => $version);
  386. }
  387. }
  388. }
  389. // newest version first
  390. krsort($versions);
  391. $result = array();
  392. foreach ($versions as $key => $value) {
  393. $size = $view->filesize(self::VERSIONS_ROOT.'/'.$value['path'].'.v'.$value['timestamp']);
  394. $filename = $value['path'];
  395. $result['all'][$key]['version'] = $value['timestamp'];
  396. $result['all'][$key]['path'] = $filename;
  397. $result['all'][$key]['size'] = $size;
  398. $result['by_file'][$filename][$key]['version'] = $value['timestamp'];
  399. $result['by_file'][$filename][$key]['path'] = $filename;
  400. $result['by_file'][$filename][$key]['size'] = $size;
  401. }
  402. return $result;
  403. }
  404. /**
  405. * get list of files we want to expire
  406. * @param array $versions list of versions
  407. * @param integer $time
  408. * @return array containing the list of to deleted versions and the size of them
  409. */
  410. protected static function getExpireList($time, $versions) {
  411. $size = 0;
  412. $toDelete = array(); // versions we want to delete
  413. $interval = 1;
  414. $step = Storage::$max_versions_per_interval[$interval]['step'];
  415. if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] == -1) {
  416. $nextInterval = -1;
  417. } else {
  418. $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
  419. }
  420. $firstVersion = reset($versions);
  421. $firstKey = key($versions);
  422. $prevTimestamp = $firstVersion['version'];
  423. $nextVersion = $firstVersion['version'] - $step;
  424. unset($versions[$firstKey]);
  425. foreach ($versions as $key => $version) {
  426. $newInterval = true;
  427. while ($newInterval) {
  428. if ($nextInterval == -1 || $prevTimestamp > $nextInterval) {
  429. if ($version['version'] > $nextVersion) {
  430. //distance between two version too small, mark to delete
  431. $toDelete[$key] = $version['path'] . '.v' . $version['version'];
  432. $size += $version['size'];
  433. \OCP\Util::writeLog('files_versions', 'Mark to expire '. $version['path'] .' next version should be ' . $nextVersion . " or smaller. (prevTimestamp: " . $prevTimestamp . "; step: " . $step, \OCP\Util::DEBUG);
  434. } else {
  435. $nextVersion = $version['version'] - $step;
  436. $prevTimestamp = $version['version'];
  437. }
  438. $newInterval = false; // version checked so we can move to the next one
  439. } else { // time to move on to the next interval
  440. $interval++;
  441. $step = Storage::$max_versions_per_interval[$interval]['step'];
  442. $nextVersion = $prevTimestamp - $step;
  443. if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] == -1) {
  444. $nextInterval = -1;
  445. } else {
  446. $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
  447. }
  448. $newInterval = true; // we changed the interval -> check same version with new interval
  449. }
  450. }
  451. }
  452. return array($toDelete, $size);
  453. }
  454. /**
  455. * Schedule versions expiration for the given file
  456. *
  457. * @param string $uid owner of the file
  458. * @param string $fileName file/folder for which to schedule expiration
  459. * @param int|null $versionsSize current versions size
  460. * @param int $neededSpace requested versions size
  461. */
  462. private static function scheduleExpire($uid, $fileName, $versionsSize = null, $neededSpace = 0) {
  463. $command = new Expire($uid, $fileName, $versionsSize, $neededSpace);
  464. \OC::$server->getCommandBus()->push($command);
  465. }
  466. /**
  467. * Expire versions which exceed the quota
  468. *
  469. * @param $filename
  470. * @param int|null $versionsSize
  471. * @param int $offset
  472. * @return bool|int|null
  473. */
  474. public static function expire($filename, $versionsSize = null, $offset = 0) {
  475. $config = \OC::$server->getConfig();
  476. if($config->getSystemValue('files_versions', Storage::DEFAULTENABLED)=='true') {
  477. list($uid, $filename) = self::getUidAndFilename($filename);
  478. if (empty($filename)) {
  479. // file maybe renamed or deleted
  480. return false;
  481. }
  482. $versionsFileview = new \OC\Files\View('/'.$uid.'/files_versions');
  483. // get available disk space for user
  484. $softQuota = true;
  485. $quota = $config->getUserValue($uid, 'files', 'quota', null);
  486. if ( $quota === null || $quota === 'default') {
  487. $quota = $config->getAppValue('files', 'default_quota', null);
  488. }
  489. if ( $quota === null || $quota === 'none' ) {
  490. $quota = \OC\Files\Filesystem::free_space('/');
  491. $softQuota = false;
  492. } else {
  493. $quota = \OCP\Util::computerFileSize($quota);
  494. }
  495. // make sure that we have the current size of the version history
  496. if ( $versionsSize === null ) {
  497. $versionsSize = self::getVersionsSize($uid);
  498. }
  499. // calculate available space for version history
  500. // subtract size of files and current versions size from quota
  501. if ($softQuota) {
  502. $files_view = new \OC\Files\View('/'.$uid.'/files');
  503. $rootInfo = $files_view->getFileInfo('/', false);
  504. $free = $quota-$rootInfo['size']; // remaining free space for user
  505. if ( $free > 0 ) {
  506. $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - ($versionsSize + $offset); // how much space can be used for versions
  507. } else {
  508. $availableSpace = $free - $versionsSize - $offset;
  509. }
  510. } else {
  511. $availableSpace = $quota - $offset;
  512. }
  513. $allVersions = Storage::getVersions($uid, $filename);
  514. $time = time();
  515. list($toDelete, $sizeOfDeletedVersions) = self::getExpireList($time, $allVersions);
  516. $availableSpace = $availableSpace + $sizeOfDeletedVersions;
  517. $versionsSize = $versionsSize - $sizeOfDeletedVersions;
  518. // if still not enough free space we rearrange the versions from all files
  519. if ($availableSpace <= 0) {
  520. $result = Storage::getAllVersions($uid);
  521. $allVersions = $result['all'];
  522. foreach ($result['by_file'] as $versions) {
  523. list($toDeleteNew, $size) = self::getExpireList($time, $versions);
  524. $toDelete = array_merge($toDelete, $toDeleteNew);
  525. $sizeOfDeletedVersions += $size;
  526. }
  527. $availableSpace = $availableSpace + $sizeOfDeletedVersions;
  528. $versionsSize = $versionsSize - $sizeOfDeletedVersions;
  529. }
  530. foreach($toDelete as $key => $path) {
  531. \OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $path));
  532. self::deleteVersion($versionsFileview, $path);
  533. \OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $path));
  534. unset($allVersions[$key]); // update array with the versions we keep
  535. \OCP\Util::writeLog('files_versions', "Expire: " . $path, \OCP\Util::DEBUG);
  536. }
  537. // Check if enough space is available after versions are rearranged.
  538. // If not we delete the oldest versions until we meet the size limit for versions,
  539. // but always keep the two latest versions
  540. $numOfVersions = count($allVersions) -2 ;
  541. $i = 0;
  542. // sort oldest first and make sure that we start at the first element
  543. ksort($allVersions);
  544. reset($allVersions);
  545. while ($availableSpace < 0 && $i < $numOfVersions) {
  546. $version = current($allVersions);
  547. \OC_Hook::emit('\OCP\Versions', 'preDelete', array('path' => $version['path'].'.v'.$version['version']));
  548. self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
  549. \OC_Hook::emit('\OCP\Versions', 'delete', array('path' => $version['path'].'.v'.$version['version']));
  550. \OCP\Util::writeLog('files_versions', 'running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'] , \OCP\Util::DEBUG);
  551. $versionsSize -= $version['size'];
  552. $availableSpace += $version['size'];
  553. next($allVersions);
  554. $i++;
  555. }
  556. return $versionsSize; // finally return the new size of the version history
  557. }
  558. return false;
  559. }
  560. /**
  561. * Create recursively missing directories inside of files_versions
  562. * that match the given path to a file.
  563. *
  564. * @param string $filename $path to a file, relative to the user's
  565. * "files" folder
  566. * @param \OC\Files\View $view view on data/user/
  567. */
  568. private static function createMissingDirectories($filename, $view) {
  569. $dirname = \OC\Files\Filesystem::normalizePath(dirname($filename));
  570. $dirParts = explode('/', $dirname);
  571. $dir = "/files_versions";
  572. foreach ($dirParts as $part) {
  573. $dir = $dir . '/' . $part;
  574. if (!$view->file_exists($dir)) {
  575. $view->mkdir($dir);
  576. }
  577. }
  578. }
  579. }