Storage.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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 Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Felix Moeller <mail@felixmoeller.de>
  11. * @author Felix Nieuwenhuizen <felix@tdlrali.com>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  14. * @author Julius Härtl <jus@bitgrid.net>
  15. * @author Liam JACK <liamjack@users.noreply.github.com>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Morris Jobke <hey@morrisjobke.de>
  18. * @author Robin Appelman <robin@icewind.nl>
  19. * @author Robin McCorkell <robin@mccorkell.me.uk>
  20. * @author Roeland Jago Douma <roeland@famdouma.nl>
  21. * @author Thomas Müller <thomas.mueller@tmit.eu>
  22. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  23. * @author Vincent Petry <vincent@nextcloud.com>
  24. *
  25. * @license AGPL-3.0
  26. *
  27. * This code is free software: you can redistribute it and/or modify
  28. * it under the terms of the GNU Affero General Public License, version 3,
  29. * as published by the Free Software Foundation.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU Affero General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU Affero General Public License, version 3,
  37. * along with this program. If not, see <http://www.gnu.org/licenses/>
  38. *
  39. */
  40. /**
  41. * Versions
  42. *
  43. * A class to handle the versioning of files.
  44. */
  45. namespace OCA\Files_Versions;
  46. use OC\Files\Filesystem;
  47. use OC\Files\View;
  48. use OCA\Files_Versions\AppInfo\Application;
  49. use OCA\Files_Versions\Command\Expire;
  50. use OCA\Files_Versions\Events\CreateVersionEvent;
  51. use OCA\Files_Versions\Versions\IVersionManager;
  52. use OCP\Files\NotFoundException;
  53. use OCP\IUser;
  54. use OCP\Lock\ILockingProvider;
  55. use OCP\User;
  56. class Storage {
  57. public const DEFAULTENABLED = true;
  58. public const DEFAULTMAXSIZE = 50; // unit: percentage; 50% of available disk space/quota
  59. public const VERSIONS_ROOT = 'files_versions/';
  60. public const DELETE_TRIGGER_MASTER_REMOVED = 0;
  61. public const DELETE_TRIGGER_RETENTION_CONSTRAINT = 1;
  62. public const DELETE_TRIGGER_QUOTA_EXCEEDED = 2;
  63. // files for which we can remove the versions after the delete operation was successful
  64. private static $deletedFiles = [];
  65. private static $sourcePathAndUser = [];
  66. private static $max_versions_per_interval = [
  67. //first 10sec, one version every 2sec
  68. 1 => ['intervalEndsAfter' => 10, 'step' => 2],
  69. //next minute, one version every 10sec
  70. 2 => ['intervalEndsAfter' => 60, 'step' => 10],
  71. //next hour, one version every minute
  72. 3 => ['intervalEndsAfter' => 3600, 'step' => 60],
  73. //next 24h, one version every hour
  74. 4 => ['intervalEndsAfter' => 86400, 'step' => 3600],
  75. //next 30days, one version per day
  76. 5 => ['intervalEndsAfter' => 2592000, 'step' => 86400],
  77. //until the end one version per week
  78. 6 => ['intervalEndsAfter' => -1, 'step' => 604800],
  79. ];
  80. /** @var \OCA\Files_Versions\AppInfo\Application */
  81. private static $application;
  82. /**
  83. * get the UID of the owner of the file and the path to the file relative to
  84. * owners files folder
  85. *
  86. * @param string $filename
  87. * @return array
  88. * @throws \OC\User\NoUserException
  89. */
  90. public static function getUidAndFilename($filename) {
  91. $uid = Filesystem::getOwner($filename);
  92. $userManager = \OC::$server->getUserManager();
  93. // if the user with the UID doesn't exists, e.g. because the UID points
  94. // to a remote user with a federated cloud ID we use the current logged-in
  95. // user. We need a valid local user to create the versions
  96. if (!$userManager->userExists($uid)) {
  97. $uid = User::getUser();
  98. }
  99. Filesystem::initMountPoints($uid);
  100. if ($uid !== User::getUser()) {
  101. $info = Filesystem::getFileInfo($filename);
  102. $ownerView = new View('/'.$uid.'/files');
  103. try {
  104. $filename = $ownerView->getPath($info['fileid']);
  105. // make sure that the file name doesn't end with a trailing slash
  106. // can for example happen single files shared across servers
  107. $filename = rtrim($filename, '/');
  108. } catch (NotFoundException $e) {
  109. $filename = null;
  110. }
  111. }
  112. return [$uid, $filename];
  113. }
  114. /**
  115. * Remember the owner and the owner path of the source file
  116. *
  117. * @param string $source source path
  118. */
  119. public static function setSourcePathAndUser($source) {
  120. list($uid, $path) = self::getUidAndFilename($source);
  121. self::$sourcePathAndUser[$source] = ['uid' => $uid, 'path' => $path];
  122. }
  123. /**
  124. * Gets the owner and the owner path from the source path
  125. *
  126. * @param string $source source path
  127. * @return array with user id and path
  128. */
  129. public static function getSourcePathAndUser($source) {
  130. if (isset(self::$sourcePathAndUser[$source])) {
  131. $uid = self::$sourcePathAndUser[$source]['uid'];
  132. $path = self::$sourcePathAndUser[$source]['path'];
  133. unset(self::$sourcePathAndUser[$source]);
  134. } else {
  135. $uid = $path = false;
  136. }
  137. return [$uid, $path];
  138. }
  139. /**
  140. * get current size of all versions from a given user
  141. *
  142. * @param string $user user who owns the versions
  143. * @return int versions size
  144. */
  145. private static function getVersionsSize($user) {
  146. $view = new View('/' . $user);
  147. $fileInfo = $view->getFileInfo('/files_versions');
  148. return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
  149. }
  150. /**
  151. * store a new version of a file.
  152. */
  153. public static function store($filename) {
  154. // if the file gets streamed we need to remove the .part extension
  155. // to get the right target
  156. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  157. if ($ext === 'part') {
  158. $filename = substr($filename, 0, -5);
  159. }
  160. // we only handle existing files
  161. if (! Filesystem::file_exists($filename) || Filesystem::is_dir($filename)) {
  162. return false;
  163. }
  164. list($uid, $filename) = self::getUidAndFilename($filename);
  165. $files_view = new View('/'.$uid .'/files');
  166. $eventDispatcher = \OC::$server->getEventDispatcher();
  167. $fileInfo = $files_view->getFileInfo($filename);
  168. $id = $fileInfo->getId();
  169. $nodes = \OC::$server->getRootFolder()->getUserFolder($uid)->getById($id);
  170. foreach ($nodes as $node) {
  171. $event = new CreateVersionEvent($node);
  172. $eventDispatcher->dispatch('OCA\Files_Versions::createVersion', $event);
  173. if ($event->shouldCreateVersion() === false) {
  174. return false;
  175. }
  176. }
  177. // no use making versions for empty files
  178. if ($fileInfo->getSize() === 0) {
  179. return false;
  180. }
  181. /** @var IVersionManager $versionManager */
  182. $versionManager = \OC::$server->query(IVersionManager::class);
  183. $userManager = \OC::$server->getUserManager();
  184. $user = $userManager->get($uid);
  185. $versionManager->createVersion($user, $fileInfo);
  186. }
  187. /**
  188. * mark file as deleted so that we can remove the versions if the file is gone
  189. * @param string $path
  190. */
  191. public static function markDeletedFile($path) {
  192. list($uid, $filename) = self::getUidAndFilename($path);
  193. self::$deletedFiles[$path] = [
  194. 'uid' => $uid,
  195. 'filename' => $filename];
  196. }
  197. /**
  198. * delete the version from the storage and cache
  199. *
  200. * @param View $view
  201. * @param string $path
  202. */
  203. protected static function deleteVersion($view, $path) {
  204. $view->unlink($path);
  205. /**
  206. * @var \OC\Files\Storage\Storage $storage
  207. * @var string $internalPath
  208. */
  209. list($storage, $internalPath) = $view->resolvePath($path);
  210. $cache = $storage->getCache($internalPath);
  211. $cache->remove($internalPath);
  212. }
  213. /**
  214. * Delete versions of a file
  215. */
  216. public static function delete($path) {
  217. $deletedFile = self::$deletedFiles[$path];
  218. $uid = $deletedFile['uid'];
  219. $filename = $deletedFile['filename'];
  220. if (!Filesystem::file_exists($path)) {
  221. $view = new View('/' . $uid . '/files_versions');
  222. $versions = self::getVersions($uid, $filename);
  223. if (!empty($versions)) {
  224. foreach ($versions as $v) {
  225. \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
  226. self::deleteVersion($view, $filename . '.v' . $v['version']);
  227. \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
  228. }
  229. }
  230. }
  231. unset(self::$deletedFiles[$path]);
  232. }
  233. /**
  234. * Rename or copy versions of a file of the given paths
  235. *
  236. * @param string $sourcePath source path of the file to move, relative to
  237. * the currently logged in user's "files" folder
  238. * @param string $targetPath target path of the file to move, relative to
  239. * the currently logged in user's "files" folder
  240. * @param string $operation can be 'copy' or 'rename'
  241. */
  242. public static function renameOrCopy($sourcePath, $targetPath, $operation) {
  243. list($sourceOwner, $sourcePath) = self::getSourcePathAndUser($sourcePath);
  244. // it was a upload of a existing file if no old path exists
  245. // in this case the pre-hook already called the store method and we can
  246. // stop here
  247. if ($sourcePath === false) {
  248. return true;
  249. }
  250. list($targetOwner, $targetPath) = self::getUidAndFilename($targetPath);
  251. $sourcePath = ltrim($sourcePath, '/');
  252. $targetPath = ltrim($targetPath, '/');
  253. $rootView = new View('');
  254. // did we move a directory ?
  255. if ($rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
  256. // does the directory exists for versions too ?
  257. if ($rootView->is_dir('/' . $sourceOwner . '/files_versions/' . $sourcePath)) {
  258. // create missing dirs if necessary
  259. self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
  260. // move the directory containing the versions
  261. $rootView->$operation(
  262. '/' . $sourceOwner . '/files_versions/' . $sourcePath,
  263. '/' . $targetOwner . '/files_versions/' . $targetPath
  264. );
  265. }
  266. } elseif ($versions = Storage::getVersions($sourceOwner, '/' . $sourcePath)) {
  267. // create missing dirs if necessary
  268. self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
  269. foreach ($versions as $v) {
  270. // move each version one by one to the target directory
  271. $rootView->$operation(
  272. '/' . $sourceOwner . '/files_versions/' . $sourcePath.'.v' . $v['version'],
  273. '/' . $targetOwner . '/files_versions/' . $targetPath.'.v'.$v['version']
  274. );
  275. }
  276. }
  277. // if we moved versions directly for a file, schedule expiration check for that file
  278. if (!$rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
  279. self::scheduleExpire($targetOwner, $targetPath);
  280. }
  281. }
  282. /**
  283. * Rollback to an old version of a file.
  284. *
  285. * @param string $file file name
  286. * @param int $revision revision timestamp
  287. * @return bool
  288. */
  289. public static function rollback(string $file, int $revision, IUser $user) {
  290. // add expected leading slash
  291. $filename = '/' . ltrim($file, '/');
  292. // Fetch the userfolder to trigger view hooks
  293. $userFolder = \OC::$server->getUserFolder($user->getUID());
  294. $users_view = new View('/'.$user->getUID());
  295. $files_view = new View('/'. $user->getUID().'/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($user->getUID(), $file);
  325. $node = $userFolder->get($file);
  326. // TODO: move away from those legacy hooks!
  327. \OC_Hook::emit('\OCP\Versions', 'rollback', [
  328. 'path' => $filename,
  329. 'revision' => $revision,
  330. 'node' => $node,
  331. ]);
  332. return true;
  333. } elseif ($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 = [];
  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 || empty($versions['all'])) {
  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', ['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', ['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 = [self::VERSIONS_ROOT];
  485. $versions = [];
  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] = ['path' => $relpath, 'timestamp' => $version];
  501. }
  502. }
  503. }
  504. // newest version first
  505. krsort($versions);
  506. $result = [
  507. 'all' => [],
  508. 'by_file' => [],
  509. ];
  510. foreach ($versions as $key => $value) {
  511. $size = $view->filesize(self::VERSIONS_ROOT.'/'.$value['path'].'.v'.$value['timestamp']);
  512. $filename = $value['path'];
  513. $result['all'][$key]['version'] = $value['timestamp'];
  514. $result['all'][$key]['path'] = $filename;
  515. $result['all'][$key]['size'] = $size;
  516. $result['by_file'][$filename][$key]['version'] = $value['timestamp'];
  517. $result['by_file'][$filename][$key]['path'] = $filename;
  518. $result['by_file'][$filename][$key]['size'] = $size;
  519. }
  520. return $result;
  521. }
  522. /**
  523. * get list of files we want to expire
  524. * @param array $versions list of versions
  525. * @param integer $time
  526. * @param bool $quotaExceeded is versions storage limit reached
  527. * @return array containing the list of to deleted versions and the size of them
  528. */
  529. protected static function getExpireList($time, $versions, $quotaExceeded = false) {
  530. $expiration = self::getExpiration();
  531. if ($expiration->shouldAutoExpire()) {
  532. list($toDelete, $size) = self::getAutoExpireList($time, $versions);
  533. } else {
  534. $size = 0;
  535. $toDelete = []; // versions we want to delete
  536. }
  537. foreach ($versions as $key => $version) {
  538. if ($expiration->isExpired($version['version'], $quotaExceeded) && !isset($toDelete[$key])) {
  539. $size += $version['size'];
  540. $toDelete[$key] = $version['path'] . '.v' . $version['version'];
  541. }
  542. }
  543. return [$toDelete, $size];
  544. }
  545. /**
  546. * get list of files we want to expire
  547. * @param array $versions list of versions
  548. * @param integer $time
  549. * @return array containing the list of to deleted versions and the size of them
  550. */
  551. protected static function getAutoExpireList($time, $versions) {
  552. $size = 0;
  553. $toDelete = []; // versions we want to delete
  554. $interval = 1;
  555. $step = Storage::$max_versions_per_interval[$interval]['step'];
  556. if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
  557. $nextInterval = -1;
  558. } else {
  559. $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
  560. }
  561. $firstVersion = reset($versions);
  562. if ($firstVersion === false) {
  563. return [$toDelete, $size];
  564. }
  565. $firstKey = key($versions);
  566. $prevTimestamp = $firstVersion['version'];
  567. $nextVersion = $firstVersion['version'] - $step;
  568. unset($versions[$firstKey]);
  569. foreach ($versions as $key => $version) {
  570. $newInterval = true;
  571. while ($newInterval) {
  572. if ($nextInterval === -1 || $prevTimestamp > $nextInterval) {
  573. if ($version['version'] > $nextVersion) {
  574. //distance between two version too small, mark to delete
  575. $toDelete[$key] = $version['path'] . '.v' . $version['version'];
  576. $size += $version['size'];
  577. \OC::$server->getLogger()->info('Mark to expire '. $version['path'] .' next version should be ' . $nextVersion . " or smaller. (prevTimestamp: " . $prevTimestamp . "; step: " . $step, ['app' => 'files_versions']);
  578. } else {
  579. $nextVersion = $version['version'] - $step;
  580. $prevTimestamp = $version['version'];
  581. }
  582. $newInterval = false; // version checked so we can move to the next one
  583. } else { // time to move on to the next interval
  584. $interval++;
  585. $step = Storage::$max_versions_per_interval[$interval]['step'];
  586. $nextVersion = $prevTimestamp - $step;
  587. if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
  588. $nextInterval = -1;
  589. } else {
  590. $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
  591. }
  592. $newInterval = true; // we changed the interval -> check same version with new interval
  593. }
  594. }
  595. }
  596. return [$toDelete, $size];
  597. }
  598. /**
  599. * Schedule versions expiration for the given file
  600. *
  601. * @param string $uid owner of the file
  602. * @param string $fileName file/folder for which to schedule expiration
  603. */
  604. public static function scheduleExpire($uid, $fileName) {
  605. // let the admin disable auto expire
  606. $expiration = self::getExpiration();
  607. if ($expiration->isEnabled()) {
  608. $command = new Expire($uid, $fileName);
  609. \OC::$server->getCommandBus()->push($command);
  610. }
  611. }
  612. /**
  613. * Expire versions which exceed the quota.
  614. *
  615. * This will setup the filesystem for the given user but will not
  616. * tear it down afterwards.
  617. *
  618. * @param string $filename path to file to expire
  619. * @param string $uid user for which to expire the version
  620. * @return bool|int|null
  621. */
  622. public static function expire($filename, $uid) {
  623. $expiration = self::getExpiration();
  624. if ($expiration->isEnabled()) {
  625. // get available disk space for user
  626. $user = \OC::$server->getUserManager()->get($uid);
  627. if (is_null($user)) {
  628. \OC::$server->getLogger()->error('Backends provided no user object for ' . $uid, ['app' => 'files_versions']);
  629. throw new \OC\User\NoUserException('Backends provided no user object for ' . $uid);
  630. }
  631. \OC_Util::setupFS($uid);
  632. if (!Filesystem::file_exists($filename)) {
  633. return false;
  634. }
  635. if (empty($filename)) {
  636. // file maybe renamed or deleted
  637. return false;
  638. }
  639. $versionsFileview = new View('/'.$uid.'/files_versions');
  640. $softQuota = true;
  641. $quota = $user->getQuota();
  642. if ($quota === null || $quota === 'none') {
  643. $quota = Filesystem::free_space('/');
  644. $softQuota = false;
  645. } else {
  646. $quota = \OCP\Util::computerFileSize($quota);
  647. }
  648. // make sure that we have the current size of the version history
  649. $versionsSize = self::getVersionsSize($uid);
  650. // calculate available space for version history
  651. // subtract size of files and current versions size from quota
  652. if ($quota >= 0) {
  653. if ($softQuota) {
  654. $userFolder = \OC::$server->getUserFolder($uid);
  655. if (is_null($userFolder)) {
  656. $availableSpace = 0;
  657. } else {
  658. $free = $quota - $userFolder->getSize(false); // remaining free space for user
  659. if ($free > 0) {
  660. $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
  661. } else {
  662. $availableSpace = $free - $versionsSize;
  663. }
  664. }
  665. } else {
  666. $availableSpace = $quota;
  667. }
  668. } else {
  669. $availableSpace = PHP_INT_MAX;
  670. }
  671. $allVersions = Storage::getVersions($uid, $filename);
  672. $time = time();
  673. list($toDelete, $sizeOfDeletedVersions) = self::getExpireList($time, $allVersions, $availableSpace <= 0);
  674. $availableSpace = $availableSpace + $sizeOfDeletedVersions;
  675. $versionsSize = $versionsSize - $sizeOfDeletedVersions;
  676. // if still not enough free space we rearrange the versions from all files
  677. if ($availableSpace <= 0) {
  678. $result = self::getAllVersions($uid);
  679. $allVersions = $result['all'];
  680. foreach ($result['by_file'] as $versions) {
  681. list($toDeleteNew, $size) = self::getExpireList($time, $versions, $availableSpace <= 0);
  682. $toDelete = array_merge($toDelete, $toDeleteNew);
  683. $sizeOfDeletedVersions += $size;
  684. }
  685. $availableSpace = $availableSpace + $sizeOfDeletedVersions;
  686. $versionsSize = $versionsSize - $sizeOfDeletedVersions;
  687. }
  688. $logger = \OC::$server->getLogger();
  689. foreach ($toDelete as $key => $path) {
  690. \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
  691. self::deleteVersion($versionsFileview, $path);
  692. \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
  693. unset($allVersions[$key]); // update array with the versions we keep
  694. $logger->info('Expire: ' . $path, ['app' => 'files_versions']);
  695. }
  696. // Check if enough space is available after versions are rearranged.
  697. // If not we delete the oldest versions until we meet the size limit for versions,
  698. // but always keep the two latest versions
  699. $numOfVersions = count($allVersions) - 2 ;
  700. $i = 0;
  701. // sort oldest first and make sure that we start at the first element
  702. ksort($allVersions);
  703. reset($allVersions);
  704. while ($availableSpace < 0 && $i < $numOfVersions) {
  705. $version = current($allVersions);
  706. \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
  707. self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
  708. \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
  709. \OC::$server->getLogger()->info('running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'], ['app' => 'files_versions']);
  710. $versionsSize -= $version['size'];
  711. $availableSpace += $version['size'];
  712. next($allVersions);
  713. $i++;
  714. }
  715. return $versionsSize; // finally return the new size of the version history
  716. }
  717. return false;
  718. }
  719. /**
  720. * Create recursively missing directories inside of files_versions
  721. * that match the given path to a file.
  722. *
  723. * @param string $filename $path to a file, relative to the user's
  724. * "files" folder
  725. * @param View $view view on data/user/
  726. */
  727. public static function createMissingDirectories($filename, $view) {
  728. $dirname = Filesystem::normalizePath(dirname($filename));
  729. $dirParts = explode('/', $dirname);
  730. $dir = "/files_versions";
  731. foreach ($dirParts as $part) {
  732. $dir = $dir . '/' . $part;
  733. if (!$view->file_exists($dir)) {
  734. $view->mkdir($dir);
  735. }
  736. }
  737. }
  738. /**
  739. * Static workaround
  740. * @return Expiration
  741. */
  742. protected static function getExpiration() {
  743. if (self::$application === null) {
  744. self::$application = \OC::$server->query(Application::class);
  745. }
  746. return self::$application->getContainer()->query(Expiration::class);
  747. }
  748. }