Passed
Push — master ( 98b998...fdc64b )
by Blizzz
25:21 queued 08:43
created
apps/files_versions/lib/Storage.php 1 patch
Indentation   +894 added lines, -894 removed lines patch added patch discarded remove patch
@@ -71,898 +71,898 @@
 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
-			// TODO: move away from those legacy hooks!
421
-			\OC_Hook::emit('\OCP\Versions', 'rollback', [
422
-				'path' => $filename,
423
-				'revision' => $revision,
424
-				'node' => $node,
425
-			]);
426
-			return true;
427
-		} elseif ($versionCreated) {
428
-			self::deleteVersion($users_view, $version);
429
-		}
430
-
431
-		return false;
432
-	}
433
-
434
-	/**
435
-	 * Stream copy file contents from $path1 to $path2
436
-	 *
437
-	 * @param View $view view to use for copying
438
-	 * @param string $path1 source file to copy
439
-	 * @param string $path2 target file
440
-	 *
441
-	 * @return bool true for success, false otherwise
442
-	 */
443
-	private static function copyFileContents($view, $path1, $path2) {
444
-		/** @var \OC\Files\Storage\Storage $storage1 */
445
-		[$storage1, $internalPath1] = $view->resolvePath($path1);
446
-		/** @var \OC\Files\Storage\Storage $storage2 */
447
-		[$storage2, $internalPath2] = $view->resolvePath($path2);
448
-
449
-		$view->lockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
450
-		$view->lockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
451
-
452
-		// TODO add a proper way of overwriting a file while maintaining file ids
453
-		if ($storage1->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage') || $storage2->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage')) {
454
-			$source = $storage1->fopen($internalPath1, 'r');
455
-			$target = $storage2->fopen($internalPath2, 'w');
456
-			[, $result] = \OC_Helper::streamCopy($source, $target);
457
-			fclose($source);
458
-			fclose($target);
459
-
460
-			if ($result !== false) {
461
-				$storage1->unlink($internalPath1);
462
-			}
463
-		} else {
464
-			$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
465
-		}
466
-
467
-		$view->unlockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
468
-		$view->unlockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
469
-
470
-		return ($result !== false);
471
-	}
472
-
473
-	/**
474
-	 * get a list of all available versions of a file in descending chronological order
475
-	 * @param string $uid user id from the owner of the file
476
-	 * @param string $filename file to find versions of, relative to the user files dir
477
-	 * @param string $userFullPath
478
-	 * @return array versions newest version first
479
-	 */
480
-	public static function getVersions($uid, $filename, $userFullPath = '') {
481
-		$versions = [];
482
-		if (empty($filename)) {
483
-			return $versions;
484
-		}
485
-		// fetch for old versions
486
-		$view = new View('/' . $uid . '/');
487
-
488
-		$pathinfo = pathinfo($filename);
489
-		$versionedFile = $pathinfo['basename'];
490
-
491
-		$dir = Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
492
-
493
-		$dirContent = false;
494
-		if ($view->is_dir($dir)) {
495
-			$dirContent = $view->opendir($dir);
496
-		}
497
-
498
-		if ($dirContent === false) {
499
-			return $versions;
500
-		}
501
-
502
-		if (is_resource($dirContent)) {
503
-			while (($entryName = readdir($dirContent)) !== false) {
504
-				if (!Filesystem::isIgnoredDir($entryName)) {
505
-					$pathparts = pathinfo($entryName);
506
-					$filename = $pathparts['filename'];
507
-					if ($filename === $versionedFile) {
508
-						$pathparts = pathinfo($entryName);
509
-						$timestamp = substr($pathparts['extension'] ?? '', 1);
510
-						if (!is_numeric($timestamp)) {
511
-							\OC::$server->get(LoggerInterface::class)->error(
512
-								'Version file {path} has incorrect name format',
513
-								[
514
-									'path' => $entryName,
515
-									'app' => 'files_versions',
516
-								]
517
-							);
518
-							continue;
519
-						}
520
-						$filename = $pathparts['filename'];
521
-						$key = $timestamp . '#' . $filename;
522
-						$versions[$key]['version'] = $timestamp;
523
-						$versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp((int)$timestamp);
524
-						if (empty($userFullPath)) {
525
-							$versions[$key]['preview'] = '';
526
-						} else {
527
-							/** @var IURLGenerator $urlGenerator */
528
-							$urlGenerator = \OC::$server->get(IURLGenerator::class);
529
-							$versions[$key]['preview'] = $urlGenerator->linkToRoute('files_version.Preview.getPreview',
530
-								['file' => $userFullPath, 'version' => $timestamp]);
531
-						}
532
-						$versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
533
-						$versions[$key]['name'] = $versionedFile;
534
-						$versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
535
-						$versions[$key]['mimetype'] = \OC::$server->get(IMimeTypeDetector::class)->detectPath($versionedFile);
536
-					}
537
-				}
538
-			}
539
-			closedir($dirContent);
540
-		}
541
-
542
-		// sort with newest version first
543
-		krsort($versions);
544
-
545
-		return $versions;
546
-	}
547
-
548
-	/**
549
-	 * Expire versions that older than max version retention time
550
-	 *
551
-	 * @param string $uid
552
-	 */
553
-	public static function expireOlderThanMaxForUser($uid) {
554
-		/** @var IRootFolder $root */
555
-		$root = \OC::$server->get(IRootFolder::class);
556
-		try {
557
-			/** @var Folder $versionsRoot */
558
-			$versionsRoot = $root->get('/' . $uid . '/files_versions');
559
-		} catch (NotFoundException $e) {
560
-			return;
561
-		}
562
-
563
-		$expiration = self::getExpiration();
564
-		$threshold = $expiration->getMaxAgeAsTimestamp();
565
-		if (!$threshold) {
566
-			return;
567
-		}
568
-
569
-		$allVersions = $versionsRoot->search(new SearchQuery(
570
-			new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
571
-				new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', FileInfo::MIMETYPE_FOLDER),
572
-			]),
573
-			0,
574
-			0,
575
-			[]
576
-		));
577
-
578
-		/** @var VersionsMapper $versionsMapper */
579
-		$versionsMapper = \OC::$server->get(VersionsMapper::class);
580
-		$userFolder = $root->getUserFolder($uid);
581
-		$versionEntities = [];
582
-
583
-		/** @var Node[] $versions */
584
-		$versions = array_filter($allVersions, function (Node $info) use ($threshold, $userFolder, $versionsMapper, $versionsRoot, &$versionEntities) {
585
-			// Check that the file match '*.v*'
586
-			$versionsBegin = strrpos($info->getName(), '.v');
587
-			if ($versionsBegin === false) {
588
-				return false;
589
-			}
590
-
591
-			$version = (int)substr($info->getName(), $versionsBegin + 2);
592
-
593
-			// Check that the version does not have a label.
594
-			$path = $versionsRoot->getRelativePath($info->getPath());
595
-			$node = $userFolder->get(substr($path, 0, -strlen('.v'.$version)));
596
-			try {
597
-				$versionEntity = $versionsMapper->findVersionForFileId($node->getId(), $version);
598
-				$versionEntities[$info->getId()] = $versionEntity;
599
-
600
-				if ($versionEntity->getLabel() !== '') {
601
-					return false;
602
-				}
603
-			} catch (DoesNotExistException $ex) {
604
-				// Version on FS can have no equivalent in the DB if they were created before the version naming feature.
605
-				// So we ignore DoesNotExistException.
606
-			}
607
-
608
-			// Check that the version's timestamp is lower than $threshold
609
-			return $version < $threshold;
610
-		});
611
-
612
-		foreach ($versions as $version) {
613
-			$internalPath = $version->getInternalPath();
614
-			\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
615
-			$versionsMapper->delete($versionEntities[$version->getId()]);
616
-			$version->delete();
617
-			\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
618
-		}
619
-	}
620
-
621
-	/**
622
-	 * translate a timestamp into a string like "5 days ago"
623
-	 *
624
-	 * @param int $timestamp
625
-	 * @return string for example "5 days ago"
626
-	 */
627
-	private static function getHumanReadableTimestamp(int $timestamp): string {
628
-		$diff = time() - $timestamp;
629
-
630
-		if ($diff < 60) { // first minute
631
-			return  $diff . " seconds ago";
632
-		} elseif ($diff < 3600) { //first hour
633
-			return round($diff / 60) . " minutes ago";
634
-		} elseif ($diff < 86400) { // first day
635
-			return round($diff / 3600) . " hours ago";
636
-		} elseif ($diff < 604800) { //first week
637
-			return round($diff / 86400) . " days ago";
638
-		} elseif ($diff < 2419200) { //first month
639
-			return round($diff / 604800) . " weeks ago";
640
-		} elseif ($diff < 29030400) { // first year
641
-			return round($diff / 2419200) . " months ago";
642
-		} else {
643
-			return round($diff / 29030400) . " years ago";
644
-		}
645
-	}
646
-
647
-	/**
648
-	 * returns all stored file versions from a given user
649
-	 * @param string $uid id of the user
650
-	 * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
651
-	 */
652
-	private static function getAllVersions($uid) {
653
-		$view = new View('/' . $uid . '/');
654
-		$dirs = [self::VERSIONS_ROOT];
655
-		$versions = [];
656
-
657
-		while (!empty($dirs)) {
658
-			$dir = array_pop($dirs);
659
-			$files = $view->getDirectoryContent($dir);
660
-
661
-			foreach ($files as $file) {
662
-				$fileData = $file->getData();
663
-				$filePath = $dir . '/' . $fileData['name'];
664
-				if ($file['type'] === 'dir') {
665
-					$dirs[] = $filePath;
666
-				} else {
667
-					$versionsBegin = strrpos($filePath, '.v');
668
-					$relPathStart = strlen(self::VERSIONS_ROOT);
669
-					$version = substr($filePath, $versionsBegin + 2);
670
-					$relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
671
-					$key = $version . '#' . $relpath;
672
-					$versions[$key] = ['path' => $relpath, 'timestamp' => $version];
673
-				}
674
-			}
675
-		}
676
-
677
-		// newest version first
678
-		krsort($versions);
679
-
680
-		$result = [
681
-			'all' => [],
682
-			'by_file' => [],
683
-		];
684
-
685
-		foreach ($versions as $key => $value) {
686
-			$size = $view->filesize(self::VERSIONS_ROOT.'/'.$value['path'].'.v'.$value['timestamp']);
687
-			$filename = $value['path'];
688
-
689
-			$result['all'][$key]['version'] = $value['timestamp'];
690
-			$result['all'][$key]['path'] = $filename;
691
-			$result['all'][$key]['size'] = $size;
692
-
693
-			$result['by_file'][$filename][$key]['version'] = $value['timestamp'];
694
-			$result['by_file'][$filename][$key]['path'] = $filename;
695
-			$result['by_file'][$filename][$key]['size'] = $size;
696
-		}
697
-
698
-		return $result;
699
-	}
700
-
701
-	/**
702
-	 * get list of files we want to expire
703
-	 * @param array $versions list of versions
704
-	 * @param integer $time
705
-	 * @param bool $quotaExceeded is versions storage limit reached
706
-	 * @return array containing the list of to deleted versions and the size of them
707
-	 */
708
-	protected static function getExpireList($time, $versions, $quotaExceeded = false) {
709
-		$expiration = self::getExpiration();
710
-
711
-		if ($expiration->shouldAutoExpire()) {
712
-			[$toDelete, $size] = self::getAutoExpireList($time, $versions);
713
-		} else {
714
-			$size = 0;
715
-			$toDelete = [];  // versions we want to delete
716
-		}
717
-
718
-		foreach ($versions as $key => $version) {
719
-			if ($expiration->isExpired($version['version'], $quotaExceeded) && !isset($toDelete[$key])) {
720
-				$size += $version['size'];
721
-				$toDelete[$key] = $version['path'] . '.v' . $version['version'];
722
-			}
723
-		}
724
-
725
-		return [$toDelete, $size];
726
-	}
727
-
728
-	/**
729
-	 * get list of files we want to expire
730
-	 * @param array $versions list of versions
731
-	 * @param integer $time
732
-	 * @return array containing the list of to deleted versions and the size of them
733
-	 */
734
-	protected static function getAutoExpireList($time, $versions) {
735
-		$size = 0;
736
-		$toDelete = [];  // versions we want to delete
737
-
738
-		$interval = 1;
739
-		$step = Storage::$max_versions_per_interval[$interval]['step'];
740
-		if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
741
-			$nextInterval = -1;
742
-		} else {
743
-			$nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
744
-		}
745
-
746
-		$firstVersion = reset($versions);
747
-
748
-		if ($firstVersion === false) {
749
-			return [$toDelete, $size];
750
-		}
751
-
752
-		$firstKey = key($versions);
753
-		$prevTimestamp = $firstVersion['version'];
754
-		$nextVersion = $firstVersion['version'] - $step;
755
-		unset($versions[$firstKey]);
756
-
757
-		foreach ($versions as $key => $version) {
758
-			$newInterval = true;
759
-			while ($newInterval) {
760
-				if ($nextInterval === -1 || $prevTimestamp > $nextInterval) {
761
-					if ($version['version'] > $nextVersion) {
762
-						//distance between two version too small, mark to delete
763
-						$toDelete[$key] = $version['path'] . '.v' . $version['version'];
764
-						$size += $version['size'];
765
-						\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']);
766
-					} else {
767
-						$nextVersion = $version['version'] - $step;
768
-						$prevTimestamp = $version['version'];
769
-					}
770
-					$newInterval = false; // version checked so we can move to the next one
771
-				} else { // time to move on to the next interval
772
-					$interval++;
773
-					$step = Storage::$max_versions_per_interval[$interval]['step'];
774
-					$nextVersion = $prevTimestamp - $step;
775
-					if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
776
-						$nextInterval = -1;
777
-					} else {
778
-						$nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
779
-					}
780
-					$newInterval = true; // we changed the interval -> check same version with new interval
781
-				}
782
-			}
783
-		}
784
-
785
-		return [$toDelete, $size];
786
-	}
787
-
788
-	/**
789
-	 * Schedule versions expiration for the given file
790
-	 *
791
-	 * @param string $uid owner of the file
792
-	 * @param string $fileName file/folder for which to schedule expiration
793
-	 */
794
-	public static function scheduleExpire($uid, $fileName) {
795
-		// let the admin disable auto expire
796
-		$expiration = self::getExpiration();
797
-		if ($expiration->isEnabled()) {
798
-			$command = new Expire($uid, $fileName);
799
-			/** @var IBus $bus */
800
-			$bus = \OC::$server->get(IBus::class);
801
-			$bus->push($command);
802
-		}
803
-	}
804
-
805
-	/**
806
-	 * Expire versions which exceed the quota.
807
-	 *
808
-	 * This will setup the filesystem for the given user but will not
809
-	 * tear it down afterwards.
810
-	 *
811
-	 * @param string $filename path to file to expire
812
-	 * @param string $uid user for which to expire the version
813
-	 * @return bool|int|null
814
-	 */
815
-	public static function expire($filename, $uid) {
816
-		$expiration = self::getExpiration();
817
-
818
-		/** @var LoggerInterface $logger */
819
-		$logger = \OC::$server->get(LoggerInterface::class);
820
-
821
-		if ($expiration->isEnabled()) {
822
-			// get available disk space for user
823
-			$user = \OC::$server->get(IUserManager::class)->get($uid);
824
-			if (is_null($user)) {
825
-				$logger->error('Backends provided no user object for ' . $uid, ['app' => 'files_versions']);
826
-				throw new \OC\User\NoUserException('Backends provided no user object for ' . $uid);
827
-			}
828
-
829
-			\OC_Util::setupFS($uid);
830
-
831
-			try {
832
-				if (!Filesystem::file_exists($filename)) {
833
-					return false;
834
-				}
835
-			} catch (StorageNotAvailableException $e) {
836
-				// if we can't check that the file hasn't been deleted we can only assume that it hasn't
837
-				// note that this `StorageNotAvailableException` is about the file the versions originate from,
838
-				// not the storage that the versions are stored on
839
-			}
840
-
841
-			if (empty($filename)) {
842
-				// file maybe renamed or deleted
843
-				return false;
844
-			}
845
-			$versionsFileview = new View('/'.$uid.'/files_versions');
846
-
847
-			$softQuota = true;
848
-			$quota = $user->getQuota();
849
-			if ($quota === null || $quota === 'none') {
850
-				$quota = Filesystem::free_space('/');
851
-				$softQuota = false;
852
-			} else {
853
-				$quota = \OCP\Util::computerFileSize($quota);
854
-			}
855
-
856
-			// make sure that we have the current size of the version history
857
-			$versionsSize = self::getVersionsSize($uid);
858
-
859
-			// calculate available space for version history
860
-			// subtract size of files and current versions size from quota
861
-			if ($quota >= 0) {
862
-				if ($softQuota) {
863
-					$root = \OC::$server->get(IRootFolder::class);
864
-					$userFolder = $root->getUserFolder($uid);
865
-					if (is_null($userFolder)) {
866
-						$availableSpace = 0;
867
-					} else {
868
-						$free = $quota - $userFolder->getSize(false); // remaining free space for user
869
-						if ($free > 0) {
870
-							$availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
871
-						} else {
872
-							$availableSpace = $free - $versionsSize;
873
-						}
874
-					}
875
-				} else {
876
-					$availableSpace = $quota;
877
-				}
878
-			} else {
879
-				$availableSpace = PHP_INT_MAX;
880
-			}
881
-
882
-			$allVersions = Storage::getVersions($uid, $filename);
883
-
884
-			$time = time();
885
-			[$toDelete, $sizeOfDeletedVersions] = self::getExpireList($time, $allVersions, $availableSpace <= 0);
886
-
887
-			$availableSpace = $availableSpace + $sizeOfDeletedVersions;
888
-			$versionsSize = $versionsSize - $sizeOfDeletedVersions;
889
-
890
-			// if still not enough free space we rearrange the versions from all files
891
-			if ($availableSpace <= 0) {
892
-				$result = self::getAllVersions($uid);
893
-				$allVersions = $result['all'];
894
-
895
-				foreach ($result['by_file'] as $versions) {
896
-					[$toDeleteNew, $size] = self::getExpireList($time, $versions, $availableSpace <= 0);
897
-					$toDelete = array_merge($toDelete, $toDeleteNew);
898
-					$sizeOfDeletedVersions += $size;
899
-				}
900
-				$availableSpace = $availableSpace + $sizeOfDeletedVersions;
901
-				$versionsSize = $versionsSize - $sizeOfDeletedVersions;
902
-			}
903
-
904
-			foreach ($toDelete as $key => $path) {
905
-				\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
906
-				self::deleteVersion($versionsFileview, $path);
907
-				\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
908
-				unset($allVersions[$key]); // update array with the versions we keep
909
-				$logger->info('Expire: ' . $path, ['app' => 'files_versions']);
910
-			}
911
-
912
-			// Check if enough space is available after versions are rearranged.
913
-			// If not we delete the oldest versions until we meet the size limit for versions,
914
-			// but always keep the two latest versions
915
-			$numOfVersions = count($allVersions) - 2 ;
916
-			$i = 0;
917
-			// sort oldest first and make sure that we start at the first element
918
-			ksort($allVersions);
919
-			reset($allVersions);
920
-			while ($availableSpace < 0 && $i < $numOfVersions) {
921
-				$version = current($allVersions);
922
-				\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
923
-				self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
924
-				\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
925
-				$logger->info('running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'], ['app' => 'files_versions']);
926
-				$versionsSize -= $version['size'];
927
-				$availableSpace += $version['size'];
928
-				next($allVersions);
929
-				$i++;
930
-			}
931
-
932
-			return $versionsSize; // finally return the new size of the version history
933
-		}
934
-
935
-		return false;
936
-	}
937
-
938
-	/**
939
-	 * Create recursively missing directories inside of files_versions
940
-	 * that match the given path to a file.
941
-	 *
942
-	 * @param string $filename $path to a file, relative to the user's
943
-	 * "files" folder
944
-	 * @param View $view view on data/user/
945
-	 */
946
-	public static function createMissingDirectories($filename, $view) {
947
-		$dirname = Filesystem::normalizePath(dirname($filename));
948
-		$dirParts = explode('/', $dirname);
949
-		$dir = "/files_versions";
950
-		foreach ($dirParts as $part) {
951
-			$dir = $dir . '/' . $part;
952
-			if (!$view->file_exists($dir)) {
953
-				$view->mkdir($dir);
954
-			}
955
-		}
956
-	}
957
-
958
-	/**
959
-	 * Static workaround
960
-	 * @return Expiration
961
-	 */
962
-	protected static function getExpiration() {
963
-		if (self::$application === null) {
964
-			self::$application = \OC::$server->get(Application::class);
965
-		}
966
-		return self::$application->getContainer()->get(Expiration::class);
967
-	}
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
+            // TODO: move away from those legacy hooks!
421
+            \OC_Hook::emit('\OCP\Versions', 'rollback', [
422
+                'path' => $filename,
423
+                'revision' => $revision,
424
+                'node' => $node,
425
+            ]);
426
+            return true;
427
+        } elseif ($versionCreated) {
428
+            self::deleteVersion($users_view, $version);
429
+        }
430
+
431
+        return false;
432
+    }
433
+
434
+    /**
435
+     * Stream copy file contents from $path1 to $path2
436
+     *
437
+     * @param View $view view to use for copying
438
+     * @param string $path1 source file to copy
439
+     * @param string $path2 target file
440
+     *
441
+     * @return bool true for success, false otherwise
442
+     */
443
+    private static function copyFileContents($view, $path1, $path2) {
444
+        /** @var \OC\Files\Storage\Storage $storage1 */
445
+        [$storage1, $internalPath1] = $view->resolvePath($path1);
446
+        /** @var \OC\Files\Storage\Storage $storage2 */
447
+        [$storage2, $internalPath2] = $view->resolvePath($path2);
448
+
449
+        $view->lockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
450
+        $view->lockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
451
+
452
+        // TODO add a proper way of overwriting a file while maintaining file ids
453
+        if ($storage1->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage') || $storage2->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage')) {
454
+            $source = $storage1->fopen($internalPath1, 'r');
455
+            $target = $storage2->fopen($internalPath2, 'w');
456
+            [, $result] = \OC_Helper::streamCopy($source, $target);
457
+            fclose($source);
458
+            fclose($target);
459
+
460
+            if ($result !== false) {
461
+                $storage1->unlink($internalPath1);
462
+            }
463
+        } else {
464
+            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
465
+        }
466
+
467
+        $view->unlockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
468
+        $view->unlockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
469
+
470
+        return ($result !== false);
471
+    }
472
+
473
+    /**
474
+     * get a list of all available versions of a file in descending chronological order
475
+     * @param string $uid user id from the owner of the file
476
+     * @param string $filename file to find versions of, relative to the user files dir
477
+     * @param string $userFullPath
478
+     * @return array versions newest version first
479
+     */
480
+    public static function getVersions($uid, $filename, $userFullPath = '') {
481
+        $versions = [];
482
+        if (empty($filename)) {
483
+            return $versions;
484
+        }
485
+        // fetch for old versions
486
+        $view = new View('/' . $uid . '/');
487
+
488
+        $pathinfo = pathinfo($filename);
489
+        $versionedFile = $pathinfo['basename'];
490
+
491
+        $dir = Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
492
+
493
+        $dirContent = false;
494
+        if ($view->is_dir($dir)) {
495
+            $dirContent = $view->opendir($dir);
496
+        }
497
+
498
+        if ($dirContent === false) {
499
+            return $versions;
500
+        }
501
+
502
+        if (is_resource($dirContent)) {
503
+            while (($entryName = readdir($dirContent)) !== false) {
504
+                if (!Filesystem::isIgnoredDir($entryName)) {
505
+                    $pathparts = pathinfo($entryName);
506
+                    $filename = $pathparts['filename'];
507
+                    if ($filename === $versionedFile) {
508
+                        $pathparts = pathinfo($entryName);
509
+                        $timestamp = substr($pathparts['extension'] ?? '', 1);
510
+                        if (!is_numeric($timestamp)) {
511
+                            \OC::$server->get(LoggerInterface::class)->error(
512
+                                'Version file {path} has incorrect name format',
513
+                                [
514
+                                    'path' => $entryName,
515
+                                    'app' => 'files_versions',
516
+                                ]
517
+                            );
518
+                            continue;
519
+                        }
520
+                        $filename = $pathparts['filename'];
521
+                        $key = $timestamp . '#' . $filename;
522
+                        $versions[$key]['version'] = $timestamp;
523
+                        $versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp((int)$timestamp);
524
+                        if (empty($userFullPath)) {
525
+                            $versions[$key]['preview'] = '';
526
+                        } else {
527
+                            /** @var IURLGenerator $urlGenerator */
528
+                            $urlGenerator = \OC::$server->get(IURLGenerator::class);
529
+                            $versions[$key]['preview'] = $urlGenerator->linkToRoute('files_version.Preview.getPreview',
530
+                                ['file' => $userFullPath, 'version' => $timestamp]);
531
+                        }
532
+                        $versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
533
+                        $versions[$key]['name'] = $versionedFile;
534
+                        $versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
535
+                        $versions[$key]['mimetype'] = \OC::$server->get(IMimeTypeDetector::class)->detectPath($versionedFile);
536
+                    }
537
+                }
538
+            }
539
+            closedir($dirContent);
540
+        }
541
+
542
+        // sort with newest version first
543
+        krsort($versions);
544
+
545
+        return $versions;
546
+    }
547
+
548
+    /**
549
+     * Expire versions that older than max version retention time
550
+     *
551
+     * @param string $uid
552
+     */
553
+    public static function expireOlderThanMaxForUser($uid) {
554
+        /** @var IRootFolder $root */
555
+        $root = \OC::$server->get(IRootFolder::class);
556
+        try {
557
+            /** @var Folder $versionsRoot */
558
+            $versionsRoot = $root->get('/' . $uid . '/files_versions');
559
+        } catch (NotFoundException $e) {
560
+            return;
561
+        }
562
+
563
+        $expiration = self::getExpiration();
564
+        $threshold = $expiration->getMaxAgeAsTimestamp();
565
+        if (!$threshold) {
566
+            return;
567
+        }
568
+
569
+        $allVersions = $versionsRoot->search(new SearchQuery(
570
+            new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
571
+                new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', FileInfo::MIMETYPE_FOLDER),
572
+            ]),
573
+            0,
574
+            0,
575
+            []
576
+        ));
577
+
578
+        /** @var VersionsMapper $versionsMapper */
579
+        $versionsMapper = \OC::$server->get(VersionsMapper::class);
580
+        $userFolder = $root->getUserFolder($uid);
581
+        $versionEntities = [];
582
+
583
+        /** @var Node[] $versions */
584
+        $versions = array_filter($allVersions, function (Node $info) use ($threshold, $userFolder, $versionsMapper, $versionsRoot, &$versionEntities) {
585
+            // Check that the file match '*.v*'
586
+            $versionsBegin = strrpos($info->getName(), '.v');
587
+            if ($versionsBegin === false) {
588
+                return false;
589
+            }
590
+
591
+            $version = (int)substr($info->getName(), $versionsBegin + 2);
592
+
593
+            // Check that the version does not have a label.
594
+            $path = $versionsRoot->getRelativePath($info->getPath());
595
+            $node = $userFolder->get(substr($path, 0, -strlen('.v'.$version)));
596
+            try {
597
+                $versionEntity = $versionsMapper->findVersionForFileId($node->getId(), $version);
598
+                $versionEntities[$info->getId()] = $versionEntity;
599
+
600
+                if ($versionEntity->getLabel() !== '') {
601
+                    return false;
602
+                }
603
+            } catch (DoesNotExistException $ex) {
604
+                // Version on FS can have no equivalent in the DB if they were created before the version naming feature.
605
+                // So we ignore DoesNotExistException.
606
+            }
607
+
608
+            // Check that the version's timestamp is lower than $threshold
609
+            return $version < $threshold;
610
+        });
611
+
612
+        foreach ($versions as $version) {
613
+            $internalPath = $version->getInternalPath();
614
+            \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
615
+            $versionsMapper->delete($versionEntities[$version->getId()]);
616
+            $version->delete();
617
+            \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
618
+        }
619
+    }
620
+
621
+    /**
622
+     * translate a timestamp into a string like "5 days ago"
623
+     *
624
+     * @param int $timestamp
625
+     * @return string for example "5 days ago"
626
+     */
627
+    private static function getHumanReadableTimestamp(int $timestamp): string {
628
+        $diff = time() - $timestamp;
629
+
630
+        if ($diff < 60) { // first minute
631
+            return  $diff . " seconds ago";
632
+        } elseif ($diff < 3600) { //first hour
633
+            return round($diff / 60) . " minutes ago";
634
+        } elseif ($diff < 86400) { // first day
635
+            return round($diff / 3600) . " hours ago";
636
+        } elseif ($diff < 604800) { //first week
637
+            return round($diff / 86400) . " days ago";
638
+        } elseif ($diff < 2419200) { //first month
639
+            return round($diff / 604800) . " weeks ago";
640
+        } elseif ($diff < 29030400) { // first year
641
+            return round($diff / 2419200) . " months ago";
642
+        } else {
643
+            return round($diff / 29030400) . " years ago";
644
+        }
645
+    }
646
+
647
+    /**
648
+     * returns all stored file versions from a given user
649
+     * @param string $uid id of the user
650
+     * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
651
+     */
652
+    private static function getAllVersions($uid) {
653
+        $view = new View('/' . $uid . '/');
654
+        $dirs = [self::VERSIONS_ROOT];
655
+        $versions = [];
656
+
657
+        while (!empty($dirs)) {
658
+            $dir = array_pop($dirs);
659
+            $files = $view->getDirectoryContent($dir);
660
+
661
+            foreach ($files as $file) {
662
+                $fileData = $file->getData();
663
+                $filePath = $dir . '/' . $fileData['name'];
664
+                if ($file['type'] === 'dir') {
665
+                    $dirs[] = $filePath;
666
+                } else {
667
+                    $versionsBegin = strrpos($filePath, '.v');
668
+                    $relPathStart = strlen(self::VERSIONS_ROOT);
669
+                    $version = substr($filePath, $versionsBegin + 2);
670
+                    $relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
671
+                    $key = $version . '#' . $relpath;
672
+                    $versions[$key] = ['path' => $relpath, 'timestamp' => $version];
673
+                }
674
+            }
675
+        }
676
+
677
+        // newest version first
678
+        krsort($versions);
679
+
680
+        $result = [
681
+            'all' => [],
682
+            'by_file' => [],
683
+        ];
684
+
685
+        foreach ($versions as $key => $value) {
686
+            $size = $view->filesize(self::VERSIONS_ROOT.'/'.$value['path'].'.v'.$value['timestamp']);
687
+            $filename = $value['path'];
688
+
689
+            $result['all'][$key]['version'] = $value['timestamp'];
690
+            $result['all'][$key]['path'] = $filename;
691
+            $result['all'][$key]['size'] = $size;
692
+
693
+            $result['by_file'][$filename][$key]['version'] = $value['timestamp'];
694
+            $result['by_file'][$filename][$key]['path'] = $filename;
695
+            $result['by_file'][$filename][$key]['size'] = $size;
696
+        }
697
+
698
+        return $result;
699
+    }
700
+
701
+    /**
702
+     * get list of files we want to expire
703
+     * @param array $versions list of versions
704
+     * @param integer $time
705
+     * @param bool $quotaExceeded is versions storage limit reached
706
+     * @return array containing the list of to deleted versions and the size of them
707
+     */
708
+    protected static function getExpireList($time, $versions, $quotaExceeded = false) {
709
+        $expiration = self::getExpiration();
710
+
711
+        if ($expiration->shouldAutoExpire()) {
712
+            [$toDelete, $size] = self::getAutoExpireList($time, $versions);
713
+        } else {
714
+            $size = 0;
715
+            $toDelete = [];  // versions we want to delete
716
+        }
717
+
718
+        foreach ($versions as $key => $version) {
719
+            if ($expiration->isExpired($version['version'], $quotaExceeded) && !isset($toDelete[$key])) {
720
+                $size += $version['size'];
721
+                $toDelete[$key] = $version['path'] . '.v' . $version['version'];
722
+            }
723
+        }
724
+
725
+        return [$toDelete, $size];
726
+    }
727
+
728
+    /**
729
+     * get list of files we want to expire
730
+     * @param array $versions list of versions
731
+     * @param integer $time
732
+     * @return array containing the list of to deleted versions and the size of them
733
+     */
734
+    protected static function getAutoExpireList($time, $versions) {
735
+        $size = 0;
736
+        $toDelete = [];  // versions we want to delete
737
+
738
+        $interval = 1;
739
+        $step = Storage::$max_versions_per_interval[$interval]['step'];
740
+        if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
741
+            $nextInterval = -1;
742
+        } else {
743
+            $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
744
+        }
745
+
746
+        $firstVersion = reset($versions);
747
+
748
+        if ($firstVersion === false) {
749
+            return [$toDelete, $size];
750
+        }
751
+
752
+        $firstKey = key($versions);
753
+        $prevTimestamp = $firstVersion['version'];
754
+        $nextVersion = $firstVersion['version'] - $step;
755
+        unset($versions[$firstKey]);
756
+
757
+        foreach ($versions as $key => $version) {
758
+            $newInterval = true;
759
+            while ($newInterval) {
760
+                if ($nextInterval === -1 || $prevTimestamp > $nextInterval) {
761
+                    if ($version['version'] > $nextVersion) {
762
+                        //distance between two version too small, mark to delete
763
+                        $toDelete[$key] = $version['path'] . '.v' . $version['version'];
764
+                        $size += $version['size'];
765
+                        \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']);
766
+                    } else {
767
+                        $nextVersion = $version['version'] - $step;
768
+                        $prevTimestamp = $version['version'];
769
+                    }
770
+                    $newInterval = false; // version checked so we can move to the next one
771
+                } else { // time to move on to the next interval
772
+                    $interval++;
773
+                    $step = Storage::$max_versions_per_interval[$interval]['step'];
774
+                    $nextVersion = $prevTimestamp - $step;
775
+                    if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
776
+                        $nextInterval = -1;
777
+                    } else {
778
+                        $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
779
+                    }
780
+                    $newInterval = true; // we changed the interval -> check same version with new interval
781
+                }
782
+            }
783
+        }
784
+
785
+        return [$toDelete, $size];
786
+    }
787
+
788
+    /**
789
+     * Schedule versions expiration for the given file
790
+     *
791
+     * @param string $uid owner of the file
792
+     * @param string $fileName file/folder for which to schedule expiration
793
+     */
794
+    public static function scheduleExpire($uid, $fileName) {
795
+        // let the admin disable auto expire
796
+        $expiration = self::getExpiration();
797
+        if ($expiration->isEnabled()) {
798
+            $command = new Expire($uid, $fileName);
799
+            /** @var IBus $bus */
800
+            $bus = \OC::$server->get(IBus::class);
801
+            $bus->push($command);
802
+        }
803
+    }
804
+
805
+    /**
806
+     * Expire versions which exceed the quota.
807
+     *
808
+     * This will setup the filesystem for the given user but will not
809
+     * tear it down afterwards.
810
+     *
811
+     * @param string $filename path to file to expire
812
+     * @param string $uid user for which to expire the version
813
+     * @return bool|int|null
814
+     */
815
+    public static function expire($filename, $uid) {
816
+        $expiration = self::getExpiration();
817
+
818
+        /** @var LoggerInterface $logger */
819
+        $logger = \OC::$server->get(LoggerInterface::class);
820
+
821
+        if ($expiration->isEnabled()) {
822
+            // get available disk space for user
823
+            $user = \OC::$server->get(IUserManager::class)->get($uid);
824
+            if (is_null($user)) {
825
+                $logger->error('Backends provided no user object for ' . $uid, ['app' => 'files_versions']);
826
+                throw new \OC\User\NoUserException('Backends provided no user object for ' . $uid);
827
+            }
828
+
829
+            \OC_Util::setupFS($uid);
830
+
831
+            try {
832
+                if (!Filesystem::file_exists($filename)) {
833
+                    return false;
834
+                }
835
+            } catch (StorageNotAvailableException $e) {
836
+                // if we can't check that the file hasn't been deleted we can only assume that it hasn't
837
+                // note that this `StorageNotAvailableException` is about the file the versions originate from,
838
+                // not the storage that the versions are stored on
839
+            }
840
+
841
+            if (empty($filename)) {
842
+                // file maybe renamed or deleted
843
+                return false;
844
+            }
845
+            $versionsFileview = new View('/'.$uid.'/files_versions');
846
+
847
+            $softQuota = true;
848
+            $quota = $user->getQuota();
849
+            if ($quota === null || $quota === 'none') {
850
+                $quota = Filesystem::free_space('/');
851
+                $softQuota = false;
852
+            } else {
853
+                $quota = \OCP\Util::computerFileSize($quota);
854
+            }
855
+
856
+            // make sure that we have the current size of the version history
857
+            $versionsSize = self::getVersionsSize($uid);
858
+
859
+            // calculate available space for version history
860
+            // subtract size of files and current versions size from quota
861
+            if ($quota >= 0) {
862
+                if ($softQuota) {
863
+                    $root = \OC::$server->get(IRootFolder::class);
864
+                    $userFolder = $root->getUserFolder($uid);
865
+                    if (is_null($userFolder)) {
866
+                        $availableSpace = 0;
867
+                    } else {
868
+                        $free = $quota - $userFolder->getSize(false); // remaining free space for user
869
+                        if ($free > 0) {
870
+                            $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
871
+                        } else {
872
+                            $availableSpace = $free - $versionsSize;
873
+                        }
874
+                    }
875
+                } else {
876
+                    $availableSpace = $quota;
877
+                }
878
+            } else {
879
+                $availableSpace = PHP_INT_MAX;
880
+            }
881
+
882
+            $allVersions = Storage::getVersions($uid, $filename);
883
+
884
+            $time = time();
885
+            [$toDelete, $sizeOfDeletedVersions] = self::getExpireList($time, $allVersions, $availableSpace <= 0);
886
+
887
+            $availableSpace = $availableSpace + $sizeOfDeletedVersions;
888
+            $versionsSize = $versionsSize - $sizeOfDeletedVersions;
889
+
890
+            // if still not enough free space we rearrange the versions from all files
891
+            if ($availableSpace <= 0) {
892
+                $result = self::getAllVersions($uid);
893
+                $allVersions = $result['all'];
894
+
895
+                foreach ($result['by_file'] as $versions) {
896
+                    [$toDeleteNew, $size] = self::getExpireList($time, $versions, $availableSpace <= 0);
897
+                    $toDelete = array_merge($toDelete, $toDeleteNew);
898
+                    $sizeOfDeletedVersions += $size;
899
+                }
900
+                $availableSpace = $availableSpace + $sizeOfDeletedVersions;
901
+                $versionsSize = $versionsSize - $sizeOfDeletedVersions;
902
+            }
903
+
904
+            foreach ($toDelete as $key => $path) {
905
+                \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
906
+                self::deleteVersion($versionsFileview, $path);
907
+                \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
908
+                unset($allVersions[$key]); // update array with the versions we keep
909
+                $logger->info('Expire: ' . $path, ['app' => 'files_versions']);
910
+            }
911
+
912
+            // Check if enough space is available after versions are rearranged.
913
+            // If not we delete the oldest versions until we meet the size limit for versions,
914
+            // but always keep the two latest versions
915
+            $numOfVersions = count($allVersions) - 2 ;
916
+            $i = 0;
917
+            // sort oldest first and make sure that we start at the first element
918
+            ksort($allVersions);
919
+            reset($allVersions);
920
+            while ($availableSpace < 0 && $i < $numOfVersions) {
921
+                $version = current($allVersions);
922
+                \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
923
+                self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
924
+                \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
925
+                $logger->info('running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'], ['app' => 'files_versions']);
926
+                $versionsSize -= $version['size'];
927
+                $availableSpace += $version['size'];
928
+                next($allVersions);
929
+                $i++;
930
+            }
931
+
932
+            return $versionsSize; // finally return the new size of the version history
933
+        }
934
+
935
+        return false;
936
+    }
937
+
938
+    /**
939
+     * Create recursively missing directories inside of files_versions
940
+     * that match the given path to a file.
941
+     *
942
+     * @param string $filename $path to a file, relative to the user's
943
+     * "files" folder
944
+     * @param View $view view on data/user/
945
+     */
946
+    public static function createMissingDirectories($filename, $view) {
947
+        $dirname = Filesystem::normalizePath(dirname($filename));
948
+        $dirParts = explode('/', $dirname);
949
+        $dir = "/files_versions";
950
+        foreach ($dirParts as $part) {
951
+            $dir = $dir . '/' . $part;
952
+            if (!$view->file_exists($dir)) {
953
+                $view->mkdir($dir);
954
+            }
955
+        }
956
+    }
957
+
958
+    /**
959
+     * Static workaround
960
+     * @return Expiration
961
+     */
962
+    protected static function getExpiration() {
963
+        if (self::$application === null) {
964
+            self::$application = \OC::$server->get(Application::class);
965
+        }
966
+        return self::$application->getContainer()->get(Expiration::class);
967
+    }
968 968
 }
Please login to merge, or discard this patch.