Storage.php 33 KB

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