1
0

Storage.php 33 KB

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