1
0

Storage.php 34 KB

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