Storage.php 28 KB

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