Storage.php 31 KB

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