1
0

Storage.php 30 KB

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