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