Storage.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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. return true;
  357. } elseif ($versionCreated) {
  358. self::deleteVersion($users_view, $version);
  359. }
  360. return false;
  361. }
  362. /**
  363. * Stream copy file contents from $path1 to $path2
  364. *
  365. * @param View $view view to use for copying
  366. * @param string $path1 source file to copy
  367. * @param string $path2 target file
  368. *
  369. * @return bool true for success, false otherwise
  370. */
  371. private static function copyFileContents($view, $path1, $path2) {
  372. /** @var \OC\Files\Storage\Storage $storage1 */
  373. [$storage1, $internalPath1] = $view->resolvePath($path1);
  374. /** @var \OC\Files\Storage\Storage $storage2 */
  375. [$storage2, $internalPath2] = $view->resolvePath($path2);
  376. $view->lockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
  377. $view->lockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
  378. try {
  379. // TODO add a proper way of overwriting a file while maintaining file ids
  380. if ($storage1->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage') || $storage2->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage')) {
  381. $source = $storage1->fopen($internalPath1, 'r');
  382. $target = $storage2->fopen($internalPath2, 'w');
  383. [, $result] = \OC_Helper::streamCopy($source, $target);
  384. fclose($source);
  385. fclose($target);
  386. if ($result !== false) {
  387. $storage1->unlink($internalPath1);
  388. }
  389. } else {
  390. $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
  391. }
  392. } finally {
  393. $view->unlockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
  394. $view->unlockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
  395. }
  396. return ($result !== false);
  397. }
  398. /**
  399. * get a list of all available versions of a file in descending chronological order
  400. * @param string $uid user id from the owner of the file
  401. * @param string $filename file to find versions of, relative to the user files dir
  402. * @param string $userFullPath
  403. * @return array versions newest version first
  404. */
  405. public static function getVersions($uid, $filename, $userFullPath = '') {
  406. $versions = [];
  407. if (empty($filename)) {
  408. return $versions;
  409. }
  410. // fetch for old versions
  411. $view = new View('/' . $uid . '/');
  412. $pathinfo = pathinfo($filename);
  413. $versionedFile = $pathinfo['basename'];
  414. $dir = Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
  415. $dirContent = false;
  416. if ($view->is_dir($dir)) {
  417. $dirContent = $view->opendir($dir);
  418. }
  419. if ($dirContent === false) {
  420. return $versions;
  421. }
  422. if (is_resource($dirContent)) {
  423. while (($entryName = readdir($dirContent)) !== false) {
  424. if (!Filesystem::isIgnoredDir($entryName)) {
  425. $pathparts = pathinfo($entryName);
  426. $filename = $pathparts['filename'];
  427. if ($filename === $versionedFile) {
  428. $pathparts = pathinfo($entryName);
  429. $timestamp = substr($pathparts['extension'] ?? '', 1);
  430. if (!is_numeric($timestamp)) {
  431. \OC::$server->get(LoggerInterface::class)->error(
  432. 'Version file {path} has incorrect name format',
  433. [
  434. 'path' => $entryName,
  435. 'app' => 'files_versions',
  436. ]
  437. );
  438. continue;
  439. }
  440. $filename = $pathparts['filename'];
  441. $key = $timestamp . '#' . $filename;
  442. $versions[$key]['version'] = $timestamp;
  443. $versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp((int)$timestamp);
  444. if (empty($userFullPath)) {
  445. $versions[$key]['preview'] = '';
  446. } else {
  447. /** @var IURLGenerator $urlGenerator */
  448. $urlGenerator = \OC::$server->get(IURLGenerator::class);
  449. $versions[$key]['preview'] = $urlGenerator->linkToRoute('files_version.Preview.getPreview',
  450. ['file' => $userFullPath, 'version' => $timestamp]);
  451. }
  452. $versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
  453. $versions[$key]['name'] = $versionedFile;
  454. $versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
  455. $versions[$key]['mimetype'] = \OC::$server->get(IMimeTypeDetector::class)->detectPath($versionedFile);
  456. }
  457. }
  458. }
  459. closedir($dirContent);
  460. }
  461. // sort with newest version first
  462. krsort($versions);
  463. return $versions;
  464. }
  465. /**
  466. * Expire versions that older than max version retention time
  467. *
  468. * @param string $uid
  469. */
  470. public static function expireOlderThanMaxForUser($uid) {
  471. /** @var IRootFolder $root */
  472. $root = \OC::$server->get(IRootFolder::class);
  473. try {
  474. /** @var Folder $versionsRoot */
  475. $versionsRoot = $root->get('/' . $uid . '/files_versions');
  476. } catch (NotFoundException $e) {
  477. return;
  478. }
  479. $expiration = self::getExpiration();
  480. $threshold = $expiration->getMaxAgeAsTimestamp();
  481. if (!$threshold) {
  482. return;
  483. }
  484. $allVersions = $versionsRoot->search(new SearchQuery(
  485. new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
  486. new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', FileInfo::MIMETYPE_FOLDER),
  487. ]),
  488. 0,
  489. 0,
  490. []
  491. ));
  492. /** @var Node[] $versions */
  493. $versions = array_filter($allVersions, function (Node $info) use ($threshold) {
  494. $versionsBegin = strrpos($info->getName(), '.v');
  495. if ($versionsBegin === false) {
  496. return false;
  497. }
  498. $version = (int)substr($info->getName(), $versionsBegin + 2);
  499. return $version < $threshold;
  500. });
  501. foreach ($versions as $version) {
  502. $internalPath = $version->getInternalPath();
  503. \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
  504. $version->delete();
  505. \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
  506. }
  507. }
  508. /**
  509. * translate a timestamp into a string like "5 days ago"
  510. *
  511. * @param int $timestamp
  512. * @return string for example "5 days ago"
  513. */
  514. private static function getHumanReadableTimestamp(int $timestamp): string {
  515. $diff = time() - $timestamp;
  516. if ($diff < 60) { // first minute
  517. return $diff . " seconds ago";
  518. } elseif ($diff < 3600) { //first hour
  519. return round($diff / 60) . " minutes ago";
  520. } elseif ($diff < 86400) { // first day
  521. return round($diff / 3600) . " hours ago";
  522. } elseif ($diff < 604800) { //first week
  523. return round($diff / 86400) . " days ago";
  524. } elseif ($diff < 2419200) { //first month
  525. return round($diff / 604800) . " weeks ago";
  526. } elseif ($diff < 29030400) { // first year
  527. return round($diff / 2419200) . " months ago";
  528. } else {
  529. return round($diff / 29030400) . " years ago";
  530. }
  531. }
  532. /**
  533. * returns all stored file versions from a given user
  534. * @param string $uid id of the user
  535. * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
  536. */
  537. private static function getAllVersions($uid) {
  538. $view = new View('/' . $uid . '/');
  539. $dirs = [self::VERSIONS_ROOT];
  540. $versions = [];
  541. while (!empty($dirs)) {
  542. $dir = array_pop($dirs);
  543. $files = $view->getDirectoryContent($dir);
  544. foreach ($files as $file) {
  545. $fileData = $file->getData();
  546. $filePath = $dir . '/' . $fileData['name'];
  547. if ($file['type'] === 'dir') {
  548. $dirs[] = $filePath;
  549. } else {
  550. $versionsBegin = strrpos($filePath, '.v');
  551. $relPathStart = strlen(self::VERSIONS_ROOT);
  552. $version = substr($filePath, $versionsBegin + 2);
  553. $relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
  554. $key = $version . '#' . $relpath;
  555. $versions[$key] = ['path' => $relpath, 'timestamp' => $version];
  556. }
  557. }
  558. }
  559. // newest version first
  560. krsort($versions);
  561. $result = [
  562. 'all' => [],
  563. 'by_file' => [],
  564. ];
  565. foreach ($versions as $key => $value) {
  566. $size = $view->filesize(self::VERSIONS_ROOT.'/'.$value['path'].'.v'.$value['timestamp']);
  567. $filename = $value['path'];
  568. $result['all'][$key]['version'] = $value['timestamp'];
  569. $result['all'][$key]['path'] = $filename;
  570. $result['all'][$key]['size'] = $size;
  571. $result['by_file'][$filename][$key]['version'] = $value['timestamp'];
  572. $result['by_file'][$filename][$key]['path'] = $filename;
  573. $result['by_file'][$filename][$key]['size'] = $size;
  574. }
  575. return $result;
  576. }
  577. /**
  578. * get list of files we want to expire
  579. * @param array $versions list of versions
  580. * @param integer $time
  581. * @param bool $quotaExceeded is versions storage limit reached
  582. * @return array containing the list of to deleted versions and the size of them
  583. */
  584. protected static function getExpireList($time, $versions, $quotaExceeded = false) {
  585. $expiration = self::getExpiration();
  586. if ($expiration->shouldAutoExpire()) {
  587. [$toDelete, $size] = self::getAutoExpireList($time, $versions);
  588. } else {
  589. $size = 0;
  590. $toDelete = []; // versions we want to delete
  591. }
  592. foreach ($versions as $key => $version) {
  593. if ($expiration->isExpired($version['version'], $quotaExceeded) && !isset($toDelete[$key])) {
  594. $size += $version['size'];
  595. $toDelete[$key] = $version['path'] . '.v' . $version['version'];
  596. }
  597. }
  598. return [$toDelete, $size];
  599. }
  600. /**
  601. * get list of files we want to expire
  602. * @param array $versions list of versions
  603. * @param integer $time
  604. * @return array containing the list of to deleted versions and the size of them
  605. */
  606. protected static function getAutoExpireList($time, $versions) {
  607. $size = 0;
  608. $toDelete = []; // versions we want to delete
  609. $interval = 1;
  610. $step = Storage::$max_versions_per_interval[$interval]['step'];
  611. if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
  612. $nextInterval = -1;
  613. } else {
  614. $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
  615. }
  616. $firstVersion = reset($versions);
  617. if ($firstVersion === false) {
  618. return [$toDelete, $size];
  619. }
  620. $firstKey = key($versions);
  621. $prevTimestamp = $firstVersion['version'];
  622. $nextVersion = $firstVersion['version'] - $step;
  623. unset($versions[$firstKey]);
  624. foreach ($versions as $key => $version) {
  625. $newInterval = true;
  626. while ($newInterval) {
  627. if ($nextInterval === -1 || $prevTimestamp > $nextInterval) {
  628. if ($version['version'] > $nextVersion) {
  629. //distance between two version too small, mark to delete
  630. $toDelete[$key] = $version['path'] . '.v' . $version['version'];
  631. $size += $version['size'];
  632. \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']);
  633. } else {
  634. $nextVersion = $version['version'] - $step;
  635. $prevTimestamp = $version['version'];
  636. }
  637. $newInterval = false; // version checked so we can move to the next one
  638. } else { // time to move on to the next interval
  639. $interval++;
  640. $step = Storage::$max_versions_per_interval[$interval]['step'];
  641. $nextVersion = $prevTimestamp - $step;
  642. if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
  643. $nextInterval = -1;
  644. } else {
  645. $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
  646. }
  647. $newInterval = true; // we changed the interval -> check same version with new interval
  648. }
  649. }
  650. }
  651. return [$toDelete, $size];
  652. }
  653. /**
  654. * Schedule versions expiration for the given file
  655. *
  656. * @param string $uid owner of the file
  657. * @param string $fileName file/folder for which to schedule expiration
  658. */
  659. public static function scheduleExpire($uid, $fileName) {
  660. // let the admin disable auto expire
  661. $expiration = self::getExpiration();
  662. if ($expiration->isEnabled()) {
  663. $command = new Expire($uid, $fileName);
  664. /** @var IBus $bus */
  665. $bus = \OC::$server->get(IBus::class);
  666. $bus->push($command);
  667. }
  668. }
  669. /**
  670. * Expire versions which exceed the quota.
  671. *
  672. * This will setup the filesystem for the given user but will not
  673. * tear it down afterwards.
  674. *
  675. * @param string $filename path to file to expire
  676. * @param string $uid user for which to expire the version
  677. * @return bool|int|null
  678. */
  679. public static function expire($filename, $uid) {
  680. $expiration = self::getExpiration();
  681. /** @var LoggerInterface $logger */
  682. $logger = \OC::$server->get(LoggerInterface::class);
  683. if ($expiration->isEnabled()) {
  684. // get available disk space for user
  685. $user = \OC::$server->get(IUserManager::class)->get($uid);
  686. if (is_null($user)) {
  687. $logger->error('Backends provided no user object for ' . $uid, ['app' => 'files_versions']);
  688. throw new \OC\User\NoUserException('Backends provided no user object for ' . $uid);
  689. }
  690. \OC_Util::setupFS($uid);
  691. try {
  692. if (!Filesystem::file_exists($filename)) {
  693. return false;
  694. }
  695. } catch (StorageNotAvailableException $e) {
  696. // if we can't check that the file hasn't been deleted we can only assume that it hasn't
  697. // note that this `StorageNotAvailableException` is about the file the versions originate from,
  698. // not the storage that the versions are stored on
  699. }
  700. if (empty($filename)) {
  701. // file maybe renamed or deleted
  702. return false;
  703. }
  704. $versionsFileview = new View('/'.$uid.'/files_versions');
  705. $softQuota = true;
  706. $quota = $user->getQuota();
  707. if ($quota === null || $quota === 'none') {
  708. $quota = Filesystem::free_space('/');
  709. $softQuota = false;
  710. } else {
  711. $quota = \OCP\Util::computerFileSize($quota);
  712. }
  713. // make sure that we have the current size of the version history
  714. $versionsSize = self::getVersionsSize($uid);
  715. // calculate available space for version history
  716. // subtract size of files and current versions size from quota
  717. if ($quota >= 0) {
  718. if ($softQuota) {
  719. $root = \OC::$server->get(IRootFolder::class);
  720. $userFolder = $root->getUserFolder($uid);
  721. if (is_null($userFolder)) {
  722. $availableSpace = 0;
  723. } else {
  724. $free = $quota - $userFolder->getSize(false); // remaining free space for user
  725. if ($free > 0) {
  726. $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
  727. } else {
  728. $availableSpace = $free - $versionsSize;
  729. }
  730. }
  731. } else {
  732. $availableSpace = $quota;
  733. }
  734. } else {
  735. $availableSpace = PHP_INT_MAX;
  736. }
  737. $allVersions = Storage::getVersions($uid, $filename);
  738. $time = time();
  739. [$toDelete, $sizeOfDeletedVersions] = self::getExpireList($time, $allVersions, $availableSpace <= 0);
  740. $availableSpace = $availableSpace + $sizeOfDeletedVersions;
  741. $versionsSize = $versionsSize - $sizeOfDeletedVersions;
  742. // if still not enough free space we rearrange the versions from all files
  743. if ($availableSpace <= 0) {
  744. $result = self::getAllVersions($uid);
  745. $allVersions = $result['all'];
  746. foreach ($result['by_file'] as $versions) {
  747. [$toDeleteNew, $size] = self::getExpireList($time, $versions, $availableSpace <= 0);
  748. $toDelete = array_merge($toDelete, $toDeleteNew);
  749. $sizeOfDeletedVersions += $size;
  750. }
  751. $availableSpace = $availableSpace + $sizeOfDeletedVersions;
  752. $versionsSize = $versionsSize - $sizeOfDeletedVersions;
  753. }
  754. foreach ($toDelete as $key => $path) {
  755. \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
  756. self::deleteVersion($versionsFileview, $path);
  757. \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
  758. unset($allVersions[$key]); // update array with the versions we keep
  759. $logger->info('Expire: ' . $path, ['app' => 'files_versions']);
  760. }
  761. // Check if enough space is available after versions are rearranged.
  762. // If not we delete the oldest versions until we meet the size limit for versions,
  763. // but always keep the two latest versions
  764. $numOfVersions = count($allVersions) - 2 ;
  765. $i = 0;
  766. // sort oldest first and make sure that we start at the first element
  767. ksort($allVersions);
  768. reset($allVersions);
  769. while ($availableSpace < 0 && $i < $numOfVersions) {
  770. $version = current($allVersions);
  771. \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
  772. self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
  773. \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
  774. $logger->info('running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'], ['app' => 'files_versions']);
  775. $versionsSize -= $version['size'];
  776. $availableSpace += $version['size'];
  777. next($allVersions);
  778. $i++;
  779. }
  780. return $versionsSize; // finally return the new size of the version history
  781. }
  782. return false;
  783. }
  784. /**
  785. * Create recursively missing directories inside of files_versions
  786. * that match the given path to a file.
  787. *
  788. * @param string $filename $path to a file, relative to the user's
  789. * "files" folder
  790. * @param View $view view on data/user/
  791. */
  792. public static function createMissingDirectories($filename, $view) {
  793. $dirname = Filesystem::normalizePath(dirname($filename));
  794. $dirParts = explode('/', $dirname);
  795. $dir = "/files_versions";
  796. foreach ($dirParts as $part) {
  797. $dir = $dir . '/' . $part;
  798. if (!$view->file_exists($dir)) {
  799. $view->mkdir($dir);
  800. }
  801. }
  802. }
  803. /**
  804. * Static workaround
  805. * @return Expiration
  806. */
  807. protected static function getExpiration() {
  808. if (self::$application === null) {
  809. self::$application = \OC::$server->get(Application::class);
  810. }
  811. return self::$application->getContainer()->get(Expiration::class);
  812. }
  813. }