1
0

Storage.php 32 KB

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