Storage.php 33 KB

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