Storage.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Files_Versions;
  8. use OC\Files\Filesystem;
  9. use OC\Files\Search\SearchBinaryOperator;
  10. use OC\Files\Search\SearchComparison;
  11. use OC\Files\Search\SearchQuery;
  12. use OC\Files\View;
  13. use OC_User;
  14. use OCA\Files_Sharing\SharedMount;
  15. use OCA\Files_Versions\AppInfo\Application;
  16. use OCA\Files_Versions\Command\Expire;
  17. use OCA\Files_Versions\Db\VersionsMapper;
  18. use OCA\Files_Versions\Events\CreateVersionEvent;
  19. use OCA\Files_Versions\Versions\IVersionManager;
  20. use OCP\AppFramework\Db\DoesNotExistException;
  21. use OCP\Command\IBus;
  22. use OCP\EventDispatcher\IEventDispatcher;
  23. use OCP\Files\FileInfo;
  24. use OCP\Files\Folder;
  25. use OCP\Files\IMimeTypeDetector;
  26. use OCP\Files\IRootFolder;
  27. use OCP\Files\Node;
  28. use OCP\Files\NotFoundException;
  29. use OCP\Files\Search\ISearchBinaryOperator;
  30. use OCP\Files\Search\ISearchComparison;
  31. use OCP\Files\StorageInvalidException;
  32. use OCP\Files\StorageNotAvailableException;
  33. use OCP\IURLGenerator;
  34. use OCP\IUser;
  35. use OCP\IUserManager;
  36. use OCP\Lock\ILockingProvider;
  37. use Psr\Log\LoggerInterface;
  38. class Storage {
  39. public const DEFAULTENABLED = true;
  40. public const DEFAULTMAXSIZE = 50; // unit: percentage; 50% of available disk space/quota
  41. public const VERSIONS_ROOT = 'files_versions/';
  42. public const DELETE_TRIGGER_MASTER_REMOVED = 0;
  43. public const DELETE_TRIGGER_RETENTION_CONSTRAINT = 1;
  44. public const DELETE_TRIGGER_QUOTA_EXCEEDED = 2;
  45. // files for which we can remove the versions after the delete operation was successful
  46. private static $deletedFiles = [];
  47. private static $sourcePathAndUser = [];
  48. private static $max_versions_per_interval = [
  49. //first 10sec, one version every 2sec
  50. 1 => ['intervalEndsAfter' => 10, 'step' => 2],
  51. //next minute, one version every 10sec
  52. 2 => ['intervalEndsAfter' => 60, 'step' => 10],
  53. //next hour, one version every minute
  54. 3 => ['intervalEndsAfter' => 3600, 'step' => 60],
  55. //next 24h, one version every hour
  56. 4 => ['intervalEndsAfter' => 86400, 'step' => 3600],
  57. //next 30days, one version per day
  58. 5 => ['intervalEndsAfter' => 2592000, 'step' => 86400],
  59. //until the end one version per week
  60. 6 => ['intervalEndsAfter' => -1, 'step' => 604800],
  61. ];
  62. /** @var \OCA\Files_Versions\AppInfo\Application */
  63. private static $application;
  64. /**
  65. * get the UID of the owner of the file and the path to the file relative to
  66. * owners files folder
  67. *
  68. * @param string $filename
  69. * @return array
  70. * @throws \OC\User\NoUserException
  71. */
  72. public static function getUidAndFilename($filename) {
  73. $uid = Filesystem::getOwner($filename);
  74. $userManager = \OC::$server->get(IUserManager::class);
  75. // if the user with the UID doesn't exists, e.g. because the UID points
  76. // to a remote user with a federated cloud ID we use the current logged-in
  77. // user. We need a valid local user to create the versions
  78. if (!$userManager->userExists($uid)) {
  79. $uid = OC_User::getUser();
  80. }
  81. Filesystem::initMountPoints($uid);
  82. if ($uid !== OC_User::getUser()) {
  83. $info = Filesystem::getFileInfo($filename);
  84. $ownerView = new View('/'.$uid.'/files');
  85. try {
  86. $filename = $ownerView->getPath($info['fileid']);
  87. // make sure that the file name doesn't end with a trailing slash
  88. // can for example happen single files shared across servers
  89. $filename = rtrim($filename, '/');
  90. } catch (NotFoundException $e) {
  91. $filename = null;
  92. }
  93. }
  94. return [$uid, $filename];
  95. }
  96. /**
  97. * Remember the owner and the owner path of the source file
  98. *
  99. * @param string $source source path
  100. */
  101. public static function setSourcePathAndUser($source) {
  102. [$uid, $path] = self::getUidAndFilename($source);
  103. self::$sourcePathAndUser[$source] = ['uid' => $uid, 'path' => $path];
  104. }
  105. /**
  106. * Gets the owner and the owner path from the source path
  107. *
  108. * @param string $source source path
  109. * @return array with user id and path
  110. */
  111. public static function getSourcePathAndUser($source) {
  112. if (isset(self::$sourcePathAndUser[$source])) {
  113. $uid = self::$sourcePathAndUser[$source]['uid'];
  114. $path = self::$sourcePathAndUser[$source]['path'];
  115. unset(self::$sourcePathAndUser[$source]);
  116. } else {
  117. $uid = $path = false;
  118. }
  119. return [$uid, $path];
  120. }
  121. /**
  122. * get current size of all versions from a given user
  123. *
  124. * @param string $user user who owns the versions
  125. * @return int versions size
  126. */
  127. private static function getVersionsSize($user) {
  128. $view = new View('/' . $user);
  129. $fileInfo = $view->getFileInfo('/files_versions');
  130. return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
  131. }
  132. /**
  133. * store a new version of a file.
  134. */
  135. public static function store($filename) {
  136. // if the file gets streamed we need to remove the .part extension
  137. // to get the right target
  138. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  139. if ($ext === 'part') {
  140. $filename = substr($filename, 0, -5);
  141. }
  142. // we only handle existing files
  143. if (! Filesystem::file_exists($filename) || Filesystem::is_dir($filename)) {
  144. return false;
  145. }
  146. // since hook paths are always relative to the "default filesystem view"
  147. // we always use the owner from there to get the full node
  148. $uid = Filesystem::getView()->getOwner('');
  149. /** @var IRootFolder $rootFolder */
  150. $rootFolder = \OC::$server->get(IRootFolder::class);
  151. $userFolder = $rootFolder->getUserFolder($uid);
  152. $eventDispatcher = \OC::$server->get(IEventDispatcher::class);
  153. try {
  154. $file = $userFolder->get($filename);
  155. } catch (NotFoundException $e) {
  156. return false;
  157. }
  158. $mount = $file->getMountPoint();
  159. if ($mount instanceof SharedMount) {
  160. $ownerFolder = $rootFolder->getUserFolder($mount->getShare()->getShareOwner());
  161. $ownerNode = $ownerFolder->getFirstNodeById($file->getId());
  162. if ($ownerNode) {
  163. $file = $ownerNode;
  164. $uid = $mount->getShare()->getShareOwner();
  165. }
  166. }
  167. /** @var IUserManager $userManager */
  168. $userManager = \OC::$server->get(IUserManager::class);
  169. $user = $userManager->get($uid);
  170. if (!$user) {
  171. return false;
  172. }
  173. // no use making versions for empty files
  174. if ($file->getSize() === 0) {
  175. return false;
  176. }
  177. $event = new CreateVersionEvent($file);
  178. $eventDispatcher->dispatch('OCA\Files_Versions::createVersion', $event);
  179. if ($event->shouldCreateVersion() === false) {
  180. return false;
  181. }
  182. /** @var IVersionManager $versionManager */
  183. $versionManager = \OC::$server->get(IVersionManager::class);
  184. $versionManager->createVersion($user, $file);
  185. }
  186. /**
  187. * mark file as deleted so that we can remove the versions if the file is gone
  188. * @param string $path
  189. */
  190. public static function markDeletedFile($path) {
  191. [$uid, $filename] = self::getUidAndFilename($path);
  192. self::$deletedFiles[$path] = [
  193. 'uid' => $uid,
  194. 'filename' => $filename];
  195. }
  196. /**
  197. * delete the version from the storage and cache
  198. *
  199. * @param View $view
  200. * @param string $path
  201. */
  202. protected static function deleteVersion($view, $path) {
  203. $view->unlink($path);
  204. /**
  205. * @var \OC\Files\Storage\Storage $storage
  206. * @var string $internalPath
  207. */
  208. [$storage, $internalPath] = $view->resolvePath($path);
  209. $cache = $storage->getCache($internalPath);
  210. $cache->remove($internalPath);
  211. }
  212. /**
  213. * Delete versions of a file
  214. */
  215. public static function delete($path) {
  216. $deletedFile = self::$deletedFiles[$path];
  217. $uid = $deletedFile['uid'];
  218. $filename = $deletedFile['filename'];
  219. if (!Filesystem::file_exists($path)) {
  220. $view = new View('/' . $uid . '/files_versions');
  221. $versions = self::getVersions($uid, $filename);
  222. if (!empty($versions)) {
  223. foreach ($versions as $v) {
  224. \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
  225. self::deleteVersion($view, $filename . '.v' . $v['version']);
  226. \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
  227. }
  228. }
  229. }
  230. unset(self::$deletedFiles[$path]);
  231. }
  232. /**
  233. * Delete a version of a file
  234. */
  235. public static function deleteRevision(string $path, int $revision): void {
  236. [$uid, $filename] = self::getUidAndFilename($path);
  237. $view = new View('/' . $uid . '/files_versions');
  238. \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path . $revision, 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
  239. self::deleteVersion($view, $filename . '.v' . $revision);
  240. \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path . $revision, 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
  241. }
  242. /**
  243. * Rename or copy versions of a file of the given paths
  244. *
  245. * @param string $sourcePath source path of the file to move, relative to
  246. * the currently logged in user's "files" folder
  247. * @param string $targetPath target path of the file to move, relative to
  248. * the currently logged in user's "files" folder
  249. * @param string $operation can be 'copy' or 'rename'
  250. */
  251. public static function renameOrCopy($sourcePath, $targetPath, $operation) {
  252. [$sourceOwner, $sourcePath] = self::getSourcePathAndUser($sourcePath);
  253. // it was a upload of a existing file if no old path exists
  254. // in this case the pre-hook already called the store method and we can
  255. // stop here
  256. if ($sourcePath === false) {
  257. return true;
  258. }
  259. [$targetOwner, $targetPath] = self::getUidAndFilename($targetPath);
  260. $sourcePath = ltrim($sourcePath, '/');
  261. $targetPath = ltrim($targetPath, '/');
  262. $rootView = new View('');
  263. // did we move a directory ?
  264. if ($rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
  265. // does the directory exists for versions too ?
  266. if ($rootView->is_dir('/' . $sourceOwner . '/files_versions/' . $sourcePath)) {
  267. // create missing dirs if necessary
  268. self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
  269. // move the directory containing the versions
  270. $rootView->$operation(
  271. '/' . $sourceOwner . '/files_versions/' . $sourcePath,
  272. '/' . $targetOwner . '/files_versions/' . $targetPath
  273. );
  274. }
  275. } elseif ($versions = Storage::getVersions($sourceOwner, '/' . $sourcePath)) {
  276. // create missing dirs if necessary
  277. self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
  278. foreach ($versions as $v) {
  279. // move each version one by one to the target directory
  280. $rootView->$operation(
  281. '/' . $sourceOwner . '/files_versions/' . $sourcePath.'.v' . $v['version'],
  282. '/' . $targetOwner . '/files_versions/' . $targetPath.'.v' . $v['version']
  283. );
  284. }
  285. }
  286. // if we moved versions directly for a file, schedule expiration check for that file
  287. if (!$rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
  288. self::scheduleExpire($targetOwner, $targetPath);
  289. }
  290. }
  291. /**
  292. * Rollback to an old version of a file.
  293. *
  294. * @param string $file file name
  295. * @param int $revision revision timestamp
  296. * @return bool
  297. */
  298. public static function rollback(string $file, int $revision, IUser $user) {
  299. // add expected leading slash
  300. $filename = '/' . ltrim($file, '/');
  301. // Fetch the userfolder to trigger view hooks
  302. $root = \OC::$server->get(IRootFolder::class);
  303. $userFolder = $root->getUserFolder($user->getUID());
  304. $users_view = new View('/'.$user->getUID());
  305. $files_view = new View('/'. $user->getUID().'/files');
  306. $versionCreated = false;
  307. $fileInfo = $files_view->getFileInfo($file);
  308. // check if user has the permissions to revert a version
  309. if (!$fileInfo->isUpdateable()) {
  310. return false;
  311. }
  312. //first create a new version
  313. $version = 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename);
  314. if (!$users_view->file_exists($version)) {
  315. $users_view->copy('files'.$filename, 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename));
  316. $versionCreated = true;
  317. }
  318. $fileToRestore = 'files_versions' . $filename . '.v' . $revision;
  319. // Restore encrypted version of the old file for the newly restored file
  320. // This has to happen manually here since the file is manually copied below
  321. $oldVersion = $users_view->getFileInfo($fileToRestore)->getEncryptedVersion();
  322. $oldFileInfo = $users_view->getFileInfo($fileToRestore);
  323. $cache = $fileInfo->getStorage()->getCache();
  324. $cache->update(
  325. $fileInfo->getId(), [
  326. 'encrypted' => $oldVersion,
  327. 'encryptedVersion' => $oldVersion,
  328. 'size' => $oldFileInfo->getSize()
  329. ]
  330. );
  331. // rollback
  332. if (self::copyFileContents($users_view, $fileToRestore, 'files' . $filename)) {
  333. $files_view->touch($file, $revision);
  334. Storage::scheduleExpire($user->getUID(), $file);
  335. $node = $userFolder->get($file);
  336. return true;
  337. } elseif ($versionCreated) {
  338. self::deleteVersion($users_view, $version);
  339. }
  340. return false;
  341. }
  342. /**
  343. * Stream copy file contents from $path1 to $path2
  344. *
  345. * @param View $view view to use for copying
  346. * @param string $path1 source file to copy
  347. * @param string $path2 target file
  348. *
  349. * @return bool true for success, false otherwise
  350. */
  351. private static function copyFileContents($view, $path1, $path2) {
  352. /** @var \OC\Files\Storage\Storage $storage1 */
  353. [$storage1, $internalPath1] = $view->resolvePath($path1);
  354. /** @var \OC\Files\Storage\Storage $storage2 */
  355. [$storage2, $internalPath2] = $view->resolvePath($path2);
  356. $view->lockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
  357. $view->lockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
  358. try {
  359. // TODO add a proper way of overwriting a file while maintaining file ids
  360. if ($storage1->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage') || $storage2->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage')) {
  361. $source = $storage1->fopen($internalPath1, 'r');
  362. $target = $storage2->fopen($internalPath2, 'w');
  363. [, $result] = \OC_Helper::streamCopy($source, $target);
  364. fclose($source);
  365. fclose($target);
  366. if ($result !== false) {
  367. $storage1->unlink($internalPath1);
  368. }
  369. } else {
  370. $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
  371. }
  372. } finally {
  373. $view->unlockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
  374. $view->unlockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
  375. }
  376. return ($result !== false);
  377. }
  378. /**
  379. * get a list of all available versions of a file in descending chronological order
  380. * @param string $uid user id from the owner of the file
  381. * @param string $filename file to find versions of, relative to the user files dir
  382. * @param string $userFullPath
  383. * @return array versions newest version first
  384. */
  385. public static function getVersions($uid, $filename, $userFullPath = '') {
  386. $versions = [];
  387. if (empty($filename)) {
  388. return $versions;
  389. }
  390. // fetch for old versions
  391. $view = new View('/' . $uid . '/');
  392. $pathinfo = pathinfo($filename);
  393. $versionedFile = $pathinfo['basename'];
  394. $dir = Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
  395. $dirContent = false;
  396. if ($view->is_dir($dir)) {
  397. $dirContent = $view->opendir($dir);
  398. }
  399. if ($dirContent === false) {
  400. return $versions;
  401. }
  402. if (is_resource($dirContent)) {
  403. while (($entryName = readdir($dirContent)) !== false) {
  404. if (!Filesystem::isIgnoredDir($entryName)) {
  405. $pathparts = pathinfo($entryName);
  406. $filename = $pathparts['filename'];
  407. if ($filename === $versionedFile) {
  408. $pathparts = pathinfo($entryName);
  409. $timestamp = substr($pathparts['extension'] ?? '', 1);
  410. if (!is_numeric($timestamp)) {
  411. \OC::$server->get(LoggerInterface::class)->error(
  412. 'Version file {path} has incorrect name format',
  413. [
  414. 'path' => $entryName,
  415. 'app' => 'files_versions',
  416. ]
  417. );
  418. continue;
  419. }
  420. $filename = $pathparts['filename'];
  421. $key = $timestamp . '#' . $filename;
  422. $versions[$key]['version'] = $timestamp;
  423. $versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp((int)$timestamp);
  424. if (empty($userFullPath)) {
  425. $versions[$key]['preview'] = '';
  426. } else {
  427. /** @var IURLGenerator $urlGenerator */
  428. $urlGenerator = \OC::$server->get(IURLGenerator::class);
  429. $versions[$key]['preview'] = $urlGenerator->linkToRoute('files_version.Preview.getPreview',
  430. ['file' => $userFullPath, 'version' => $timestamp]);
  431. }
  432. $versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
  433. $versions[$key]['name'] = $versionedFile;
  434. $versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
  435. $versions[$key]['mimetype'] = \OC::$server->get(IMimeTypeDetector::class)->detectPath($versionedFile);
  436. }
  437. }
  438. }
  439. closedir($dirContent);
  440. }
  441. // sort with newest version first
  442. krsort($versions);
  443. return $versions;
  444. }
  445. /**
  446. * Expire versions that older than max version retention time
  447. *
  448. * @param string $uid
  449. */
  450. public static function expireOlderThanMaxForUser($uid) {
  451. /** @var IRootFolder $root */
  452. $root = \OC::$server->get(IRootFolder::class);
  453. try {
  454. /** @var Folder $versionsRoot */
  455. $versionsRoot = $root->get('/' . $uid . '/files_versions');
  456. } catch (NotFoundException $e) {
  457. return;
  458. }
  459. $expiration = self::getExpiration();
  460. $threshold = $expiration->getMaxAgeAsTimestamp();
  461. if (!$threshold) {
  462. return;
  463. }
  464. $allVersions = $versionsRoot->search(new SearchQuery(
  465. new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
  466. new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', FileInfo::MIMETYPE_FOLDER),
  467. ]),
  468. 0,
  469. 0,
  470. []
  471. ));
  472. /** @var VersionsMapper $versionsMapper */
  473. $versionsMapper = \OC::$server->get(VersionsMapper::class);
  474. $userFolder = $root->getUserFolder($uid);
  475. $versionEntities = [];
  476. /** @var Node[] $versions */
  477. $versions = array_filter($allVersions, function (Node $info) use ($threshold, $userFolder, $versionsMapper, $versionsRoot, &$versionEntities) {
  478. // Check that the file match '*.v*'
  479. $versionsBegin = strrpos($info->getName(), '.v');
  480. if ($versionsBegin === false) {
  481. return false;
  482. }
  483. $version = (int)substr($info->getName(), $versionsBegin + 2);
  484. // Check that the version does not have a label.
  485. $path = $versionsRoot->getRelativePath($info->getPath());
  486. if ($path === null) {
  487. throw new DoesNotExistException('Could not find relative path of (' . $info->getPath() . ')');
  488. }
  489. try {
  490. $node = $userFolder->get(substr($path, 0, -strlen('.v'.$version)));
  491. $versionEntity = $versionsMapper->findVersionForFileId($node->getId(), $version);
  492. $versionEntities[$info->getId()] = $versionEntity;
  493. if ($versionEntity->getMetadataValue('label') !== null && $versionEntity->getMetadataValue('label') !== '') {
  494. return false;
  495. }
  496. } catch (NotFoundException $e) {
  497. // Original node not found, delete the version
  498. return true;
  499. } catch (StorageNotAvailableException | StorageInvalidException $e) {
  500. // Storage can't be used, but it might only be temporary so we can't always delete the version
  501. // since we can't determine if the version is named we take the safe route and don't expire
  502. return false;
  503. } catch (DoesNotExistException $ex) {
  504. // Version on FS can have no equivalent in the DB if they were created before the version naming feature.
  505. // So we ignore DoesNotExistException.
  506. }
  507. // Check that the version's timestamp is lower than $threshold
  508. return $version < $threshold;
  509. });
  510. foreach ($versions as $version) {
  511. $internalPath = $version->getInternalPath();
  512. \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
  513. $versionEntity = isset($versionEntities[$version->getId()]) ? $versionEntities[$version->getId()] : null;
  514. if (!is_null($versionEntity)) {
  515. $versionsMapper->delete($versionEntity);
  516. }
  517. $version->delete();
  518. \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
  519. }
  520. }
  521. /**
  522. * translate a timestamp into a string like "5 days ago"
  523. *
  524. * @param int $timestamp
  525. * @return string for example "5 days ago"
  526. */
  527. private static function getHumanReadableTimestamp(int $timestamp): string {
  528. $diff = time() - $timestamp;
  529. if ($diff < 60) { // first minute
  530. return $diff . " seconds ago";
  531. } elseif ($diff < 3600) { //first hour
  532. return round($diff / 60) . " minutes ago";
  533. } elseif ($diff < 86400) { // first day
  534. return round($diff / 3600) . " hours ago";
  535. } elseif ($diff < 604800) { //first week
  536. return round($diff / 86400) . " days ago";
  537. } elseif ($diff < 2419200) { //first month
  538. return round($diff / 604800) . " weeks ago";
  539. } elseif ($diff < 29030400) { // first year
  540. return round($diff / 2419200) . " months ago";
  541. } else {
  542. return round($diff / 29030400) . " years ago";
  543. }
  544. }
  545. /**
  546. * returns all stored file versions from a given user
  547. * @param string $uid id of the user
  548. * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
  549. */
  550. private static function getAllVersions($uid) {
  551. $view = new View('/' . $uid . '/');
  552. $dirs = [self::VERSIONS_ROOT];
  553. $versions = [];
  554. while (!empty($dirs)) {
  555. $dir = array_pop($dirs);
  556. $files = $view->getDirectoryContent($dir);
  557. foreach ($files as $file) {
  558. $fileData = $file->getData();
  559. $filePath = $dir . '/' . $fileData['name'];
  560. if ($file['type'] === 'dir') {
  561. $dirs[] = $filePath;
  562. } else {
  563. $versionsBegin = strrpos($filePath, '.v');
  564. $relPathStart = strlen(self::VERSIONS_ROOT);
  565. $version = substr($filePath, $versionsBegin + 2);
  566. $relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
  567. $key = $version . '#' . $relpath;
  568. $versions[$key] = ['path' => $relpath, 'timestamp' => $version];
  569. }
  570. }
  571. }
  572. // newest version first
  573. krsort($versions);
  574. $result = [
  575. 'all' => [],
  576. 'by_file' => [],
  577. ];
  578. foreach ($versions as $key => $value) {
  579. $size = $view->filesize(self::VERSIONS_ROOT.'/'.$value['path'].'.v'.$value['timestamp']);
  580. $filename = $value['path'];
  581. $result['all'][$key]['version'] = $value['timestamp'];
  582. $result['all'][$key]['path'] = $filename;
  583. $result['all'][$key]['size'] = $size;
  584. $result['by_file'][$filename][$key]['version'] = $value['timestamp'];
  585. $result['by_file'][$filename][$key]['path'] = $filename;
  586. $result['by_file'][$filename][$key]['size'] = $size;
  587. }
  588. return $result;
  589. }
  590. /**
  591. * get list of files we want to expire
  592. * @param array $versions list of versions
  593. * @param integer $time
  594. * @param bool $quotaExceeded is versions storage limit reached
  595. * @return array containing the list of to deleted versions and the size of them
  596. */
  597. protected static function getExpireList($time, $versions, $quotaExceeded = false) {
  598. $expiration = self::getExpiration();
  599. if ($expiration->shouldAutoExpire()) {
  600. [$toDelete, $size] = self::getAutoExpireList($time, $versions);
  601. } else {
  602. $size = 0;
  603. $toDelete = []; // versions we want to delete
  604. }
  605. foreach ($versions as $key => $version) {
  606. if (!is_numeric($version['version'])) {
  607. \OC::$server->get(LoggerInterface::class)->error(
  608. 'Found a non-numeric timestamp version: '. json_encode($version),
  609. ['app' => 'files_versions']);
  610. continue;
  611. }
  612. if ($expiration->isExpired((int)($version['version']), $quotaExceeded) && !isset($toDelete[$key])) {
  613. $size += $version['size'];
  614. $toDelete[$key] = $version['path'] . '.v' . $version['version'];
  615. }
  616. }
  617. return [$toDelete, $size];
  618. }
  619. /**
  620. * get list of files we want to expire
  621. * @param array $versions list of versions
  622. * @param integer $time
  623. * @return array containing the list of to deleted versions and the size of them
  624. */
  625. protected static function getAutoExpireList($time, $versions) {
  626. $size = 0;
  627. $toDelete = []; // versions we want to delete
  628. $interval = 1;
  629. $step = Storage::$max_versions_per_interval[$interval]['step'];
  630. if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
  631. $nextInterval = -1;
  632. } else {
  633. $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
  634. }
  635. $firstVersion = reset($versions);
  636. if ($firstVersion === false) {
  637. return [$toDelete, $size];
  638. }
  639. $firstKey = key($versions);
  640. $prevTimestamp = $firstVersion['version'];
  641. $nextVersion = $firstVersion['version'] - $step;
  642. unset($versions[$firstKey]);
  643. foreach ($versions as $key => $version) {
  644. $newInterval = true;
  645. while ($newInterval) {
  646. if ($nextInterval === -1 || $prevTimestamp > $nextInterval) {
  647. if ($version['version'] > $nextVersion) {
  648. //distance between two version too small, mark to delete
  649. $toDelete[$key] = $version['path'] . '.v' . $version['version'];
  650. $size += $version['size'];
  651. \OC::$server->get(LoggerInterface::class)->info('Mark to expire '. $version['path'] .' next version should be ' . $nextVersion . " or smaller. (prevTimestamp: " . $prevTimestamp . "; step: " . $step, ['app' => 'files_versions']);
  652. } else {
  653. $nextVersion = $version['version'] - $step;
  654. $prevTimestamp = $version['version'];
  655. }
  656. $newInterval = false; // version checked so we can move to the next one
  657. } else { // time to move on to the next interval
  658. $interval++;
  659. $step = Storage::$max_versions_per_interval[$interval]['step'];
  660. $nextVersion = $prevTimestamp - $step;
  661. if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
  662. $nextInterval = -1;
  663. } else {
  664. $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
  665. }
  666. $newInterval = true; // we changed the interval -> check same version with new interval
  667. }
  668. }
  669. }
  670. return [$toDelete, $size];
  671. }
  672. /**
  673. * Schedule versions expiration for the given file
  674. *
  675. * @param string $uid owner of the file
  676. * @param string $fileName file/folder for which to schedule expiration
  677. */
  678. public static function scheduleExpire($uid, $fileName) {
  679. // let the admin disable auto expire
  680. $expiration = self::getExpiration();
  681. if ($expiration->isEnabled()) {
  682. $command = new Expire($uid, $fileName);
  683. /** @var IBus $bus */
  684. $bus = \OC::$server->get(IBus::class);
  685. $bus->push($command);
  686. }
  687. }
  688. /**
  689. * Expire versions which exceed the quota.
  690. *
  691. * This will setup the filesystem for the given user but will not
  692. * tear it down afterwards.
  693. *
  694. * @param string $filename path to file to expire
  695. * @param string $uid user for which to expire the version
  696. * @return bool|int|null
  697. */
  698. public static function expire($filename, $uid) {
  699. $expiration = self::getExpiration();
  700. /** @var LoggerInterface $logger */
  701. $logger = \OC::$server->get(LoggerInterface::class);
  702. if ($expiration->isEnabled()) {
  703. // get available disk space for user
  704. $user = \OC::$server->get(IUserManager::class)->get($uid);
  705. if (is_null($user)) {
  706. $logger->error('Backends provided no user object for ' . $uid, ['app' => 'files_versions']);
  707. throw new \OC\User\NoUserException('Backends provided no user object for ' . $uid);
  708. }
  709. \OC_Util::setupFS($uid);
  710. try {
  711. if (!Filesystem::file_exists($filename)) {
  712. return false;
  713. }
  714. } catch (StorageNotAvailableException $e) {
  715. // if we can't check that the file hasn't been deleted we can only assume that it hasn't
  716. // note that this `StorageNotAvailableException` is about the file the versions originate from,
  717. // not the storage that the versions are stored on
  718. }
  719. if (empty($filename)) {
  720. // file maybe renamed or deleted
  721. return false;
  722. }
  723. $versionsFileview = new View('/'.$uid.'/files_versions');
  724. $softQuota = true;
  725. $quota = $user->getQuota();
  726. if ($quota === null || $quota === 'none') {
  727. $quota = Filesystem::free_space('/');
  728. $softQuota = false;
  729. } else {
  730. $quota = \OCP\Util::computerFileSize($quota);
  731. }
  732. // make sure that we have the current size of the version history
  733. $versionsSize = self::getVersionsSize($uid);
  734. // calculate available space for version history
  735. // subtract size of files and current versions size from quota
  736. if ($quota >= 0) {
  737. if ($softQuota) {
  738. $root = \OC::$server->get(IRootFolder::class);
  739. $userFolder = $root->getUserFolder($uid);
  740. if (is_null($userFolder)) {
  741. $availableSpace = 0;
  742. } else {
  743. $free = $quota - $userFolder->getSize(false); // remaining free space for user
  744. if ($free > 0) {
  745. $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
  746. } else {
  747. $availableSpace = $free - $versionsSize;
  748. }
  749. }
  750. } else {
  751. $availableSpace = $quota;
  752. }
  753. } else {
  754. $availableSpace = PHP_INT_MAX;
  755. }
  756. $allVersions = Storage::getVersions($uid, $filename);
  757. $time = time();
  758. [$toDelete, $sizeOfDeletedVersions] = self::getExpireList($time, $allVersions, $availableSpace <= 0);
  759. $availableSpace = $availableSpace + $sizeOfDeletedVersions;
  760. $versionsSize = $versionsSize - $sizeOfDeletedVersions;
  761. // if still not enough free space we rearrange the versions from all files
  762. if ($availableSpace <= 0) {
  763. $result = self::getAllVersions($uid);
  764. $allVersions = $result['all'];
  765. foreach ($result['by_file'] as $versions) {
  766. [$toDeleteNew, $size] = self::getExpireList($time, $versions, $availableSpace <= 0);
  767. $toDelete = array_merge($toDelete, $toDeleteNew);
  768. $sizeOfDeletedVersions += $size;
  769. }
  770. $availableSpace = $availableSpace + $sizeOfDeletedVersions;
  771. $versionsSize = $versionsSize - $sizeOfDeletedVersions;
  772. }
  773. foreach ($toDelete as $key => $path) {
  774. // Make sure to cleanup version table relations as expire does not pass deleteVersion
  775. try {
  776. /** @var VersionsMapper $versionsMapper */
  777. $versionsMapper = \OC::$server->get(VersionsMapper::class);
  778. $file = \OC::$server->get(IRootFolder::class)->getUserFolder($uid)->get($filename);
  779. $pathparts = pathinfo($path);
  780. $timestamp = (int)substr($pathparts['extension'] ?? '', 1);
  781. $versionEntity = $versionsMapper->findVersionForFileId($file->getId(), $timestamp);
  782. if ($versionEntity->getMetadataValue('label') !== '') {
  783. continue;
  784. }
  785. $versionsMapper->delete($versionEntity);
  786. } catch (DoesNotExistException $e) {
  787. }
  788. \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
  789. self::deleteVersion($versionsFileview, $path);
  790. \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
  791. unset($allVersions[$key]); // update array with the versions we keep
  792. $logger->info('Expire: ' . $path, ['app' => 'files_versions']);
  793. }
  794. // Check if enough space is available after versions are rearranged.
  795. // If not we delete the oldest versions until we meet the size limit for versions,
  796. // but always keep the two latest versions
  797. $numOfVersions = count($allVersions) - 2 ;
  798. $i = 0;
  799. // sort oldest first and make sure that we start at the first element
  800. ksort($allVersions);
  801. reset($allVersions);
  802. while ($availableSpace < 0 && $i < $numOfVersions) {
  803. $version = current($allVersions);
  804. \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
  805. self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
  806. \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
  807. $logger->info('running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'], ['app' => 'files_versions']);
  808. $versionsSize -= $version['size'];
  809. $availableSpace += $version['size'];
  810. next($allVersions);
  811. $i++;
  812. }
  813. return $versionsSize; // finally return the new size of the version history
  814. }
  815. return false;
  816. }
  817. /**
  818. * Create recursively missing directories inside of files_versions
  819. * that match the given path to a file.
  820. *
  821. * @param string $filename $path to a file, relative to the user's
  822. * "files" folder
  823. * @param View $view view on data/user/
  824. */
  825. public static function createMissingDirectories($filename, $view) {
  826. $dirname = Filesystem::normalizePath(dirname($filename));
  827. $dirParts = explode('/', $dirname);
  828. $dir = "/files_versions";
  829. foreach ($dirParts as $part) {
  830. $dir = $dir . '/' . $part;
  831. if (!$view->file_exists($dir)) {
  832. $view->mkdir($dir);
  833. }
  834. }
  835. }
  836. /**
  837. * Static workaround
  838. * @return Expiration
  839. */
  840. protected static function getExpiration() {
  841. if (self::$application === null) {
  842. self::$application = \OC::$server->get(Application::class);
  843. }
  844. return self::$application->getContainer()->get(Expiration::class);
  845. }
  846. }