Storage.php 34 KB

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