Passed
Push — master ( f734a7...416f63 )
by John
18:03 queued 13s
created
apps/files_versions/lib/Storage.php 1 patch
Indentation   +901 added lines, -901 removed lines patch added patch discarded remove patch
@@ -71,905 +71,905 @@
 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
-
612
-			$versionEntity = $versionEntities[$version->getId()];
613
-			if (!is_null($versionEntity)) {
614
-				$versionsMapper->delete($versionEntity);
615
-			}
616
-
617
-			$version->delete();
618
-			\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
619
-		}
620
-	}
621
-
622
-	/**
623
-	 * translate a timestamp into a string like "5 days ago"
624
-	 *
625
-	 * @param int $timestamp
626
-	 * @return string for example "5 days ago"
627
-	 */
628
-	private static function getHumanReadableTimestamp(int $timestamp): string {
629
-		$diff = time() - $timestamp;
630
-
631
-		if ($diff < 60) { // first minute
632
-			return  $diff . " seconds ago";
633
-		} elseif ($diff < 3600) { //first hour
634
-			return round($diff / 60) . " minutes ago";
635
-		} elseif ($diff < 86400) { // first day
636
-			return round($diff / 3600) . " hours ago";
637
-		} elseif ($diff < 604800) { //first week
638
-			return round($diff / 86400) . " days ago";
639
-		} elseif ($diff < 2419200) { //first month
640
-			return round($diff / 604800) . " weeks ago";
641
-		} elseif ($diff < 29030400) { // first year
642
-			return round($diff / 2419200) . " months ago";
643
-		} else {
644
-			return round($diff / 29030400) . " years ago";
645
-		}
646
-	}
647
-
648
-	/**
649
-	 * returns all stored file versions from a given user
650
-	 * @param string $uid id of the user
651
-	 * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
652
-	 */
653
-	private static function getAllVersions($uid) {
654
-		$view = new View('/' . $uid . '/');
655
-		$dirs = [self::VERSIONS_ROOT];
656
-		$versions = [];
657
-
658
-		while (!empty($dirs)) {
659
-			$dir = array_pop($dirs);
660
-			$files = $view->getDirectoryContent($dir);
661
-
662
-			foreach ($files as $file) {
663
-				$fileData = $file->getData();
664
-				$filePath = $dir . '/' . $fileData['name'];
665
-				if ($file['type'] === 'dir') {
666
-					$dirs[] = $filePath;
667
-				} else {
668
-					$versionsBegin = strrpos($filePath, '.v');
669
-					$relPathStart = strlen(self::VERSIONS_ROOT);
670
-					$version = substr($filePath, $versionsBegin + 2);
671
-					$relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
672
-					$key = $version . '#' . $relpath;
673
-					$versions[$key] = ['path' => $relpath, 'timestamp' => $version];
674
-				}
675
-			}
676
-		}
677
-
678
-		// newest version first
679
-		krsort($versions);
680
-
681
-		$result = [
682
-			'all' => [],
683
-			'by_file' => [],
684
-		];
685
-
686
-		foreach ($versions as $key => $value) {
687
-			$size = $view->filesize(self::VERSIONS_ROOT.'/'.$value['path'].'.v'.$value['timestamp']);
688
-			$filename = $value['path'];
689
-
690
-			$result['all'][$key]['version'] = $value['timestamp'];
691
-			$result['all'][$key]['path'] = $filename;
692
-			$result['all'][$key]['size'] = $size;
693
-
694
-			$result['by_file'][$filename][$key]['version'] = $value['timestamp'];
695
-			$result['by_file'][$filename][$key]['path'] = $filename;
696
-			$result['by_file'][$filename][$key]['size'] = $size;
697
-		}
698
-
699
-		return $result;
700
-	}
701
-
702
-	/**
703
-	 * get list of files we want to expire
704
-	 * @param array $versions list of versions
705
-	 * @param integer $time
706
-	 * @param bool $quotaExceeded is versions storage limit reached
707
-	 * @return array containing the list of to deleted versions and the size of them
708
-	 */
709
-	protected static function getExpireList($time, $versions, $quotaExceeded = false) {
710
-		$expiration = self::getExpiration();
711
-
712
-		if ($expiration->shouldAutoExpire()) {
713
-			[$toDelete, $size] = self::getAutoExpireList($time, $versions);
714
-		} else {
715
-			$size = 0;
716
-			$toDelete = [];  // versions we want to delete
717
-		}
718
-
719
-		foreach ($versions as $key => $version) {
720
-			if (!is_numeric($version['version'])) {
721
-				\OC::$server->get(LoggerInterface::class)->error(
722
-					'Found a non-numeric timestamp version: '. json_encode($version),
723
-					['app' => 'files_versions']);
724
-				continue;
725
-			}
726
-			if ($expiration->isExpired((int)($version['version']), $quotaExceeded) && !isset($toDelete[$key])) {
727
-				$size += $version['size'];
728
-				$toDelete[$key] = $version['path'] . '.v' . $version['version'];
729
-			}
730
-		}
731
-
732
-		return [$toDelete, $size];
733
-	}
734
-
735
-	/**
736
-	 * get list of files we want to expire
737
-	 * @param array $versions list of versions
738
-	 * @param integer $time
739
-	 * @return array containing the list of to deleted versions and the size of them
740
-	 */
741
-	protected static function getAutoExpireList($time, $versions) {
742
-		$size = 0;
743
-		$toDelete = [];  // versions we want to delete
744
-
745
-		$interval = 1;
746
-		$step = Storage::$max_versions_per_interval[$interval]['step'];
747
-		if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
748
-			$nextInterval = -1;
749
-		} else {
750
-			$nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
751
-		}
752
-
753
-		$firstVersion = reset($versions);
754
-
755
-		if ($firstVersion === false) {
756
-			return [$toDelete, $size];
757
-		}
758
-
759
-		$firstKey = key($versions);
760
-		$prevTimestamp = $firstVersion['version'];
761
-		$nextVersion = $firstVersion['version'] - $step;
762
-		unset($versions[$firstKey]);
763
-
764
-		foreach ($versions as $key => $version) {
765
-			$newInterval = true;
766
-			while ($newInterval) {
767
-				if ($nextInterval === -1 || $prevTimestamp > $nextInterval) {
768
-					if ($version['version'] > $nextVersion) {
769
-						//distance between two version too small, mark to delete
770
-						$toDelete[$key] = $version['path'] . '.v' . $version['version'];
771
-						$size += $version['size'];
772
-						\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']);
773
-					} else {
774
-						$nextVersion = $version['version'] - $step;
775
-						$prevTimestamp = $version['version'];
776
-					}
777
-					$newInterval = false; // version checked so we can move to the next one
778
-				} else { // time to move on to the next interval
779
-					$interval++;
780
-					$step = Storage::$max_versions_per_interval[$interval]['step'];
781
-					$nextVersion = $prevTimestamp - $step;
782
-					if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
783
-						$nextInterval = -1;
784
-					} else {
785
-						$nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
786
-					}
787
-					$newInterval = true; // we changed the interval -> check same version with new interval
788
-				}
789
-			}
790
-		}
791
-
792
-		return [$toDelete, $size];
793
-	}
794
-
795
-	/**
796
-	 * Schedule versions expiration for the given file
797
-	 *
798
-	 * @param string $uid owner of the file
799
-	 * @param string $fileName file/folder for which to schedule expiration
800
-	 */
801
-	public static function scheduleExpire($uid, $fileName) {
802
-		// let the admin disable auto expire
803
-		$expiration = self::getExpiration();
804
-		if ($expiration->isEnabled()) {
805
-			$command = new Expire($uid, $fileName);
806
-			/** @var IBus $bus */
807
-			$bus = \OC::$server->get(IBus::class);
808
-			$bus->push($command);
809
-		}
810
-	}
811
-
812
-	/**
813
-	 * Expire versions which exceed the quota.
814
-	 *
815
-	 * This will setup the filesystem for the given user but will not
816
-	 * tear it down afterwards.
817
-	 *
818
-	 * @param string $filename path to file to expire
819
-	 * @param string $uid user for which to expire the version
820
-	 * @return bool|int|null
821
-	 */
822
-	public static function expire($filename, $uid) {
823
-		$expiration = self::getExpiration();
824
-
825
-		/** @var LoggerInterface $logger */
826
-		$logger = \OC::$server->get(LoggerInterface::class);
827
-
828
-		if ($expiration->isEnabled()) {
829
-			// get available disk space for user
830
-			$user = \OC::$server->get(IUserManager::class)->get($uid);
831
-			if (is_null($user)) {
832
-				$logger->error('Backends provided no user object for ' . $uid, ['app' => 'files_versions']);
833
-				throw new \OC\User\NoUserException('Backends provided no user object for ' . $uid);
834
-			}
835
-
836
-			\OC_Util::setupFS($uid);
837
-
838
-			try {
839
-				if (!Filesystem::file_exists($filename)) {
840
-					return false;
841
-				}
842
-			} catch (StorageNotAvailableException $e) {
843
-				// if we can't check that the file hasn't been deleted we can only assume that it hasn't
844
-				// note that this `StorageNotAvailableException` is about the file the versions originate from,
845
-				// not the storage that the versions are stored on
846
-			}
847
-
848
-			if (empty($filename)) {
849
-				// file maybe renamed or deleted
850
-				return false;
851
-			}
852
-			$versionsFileview = new View('/'.$uid.'/files_versions');
853
-
854
-			$softQuota = true;
855
-			$quota = $user->getQuota();
856
-			if ($quota === null || $quota === 'none') {
857
-				$quota = Filesystem::free_space('/');
858
-				$softQuota = false;
859
-			} else {
860
-				$quota = \OCP\Util::computerFileSize($quota);
861
-			}
862
-
863
-			// make sure that we have the current size of the version history
864
-			$versionsSize = self::getVersionsSize($uid);
865
-
866
-			// calculate available space for version history
867
-			// subtract size of files and current versions size from quota
868
-			if ($quota >= 0) {
869
-				if ($softQuota) {
870
-					$root = \OC::$server->get(IRootFolder::class);
871
-					$userFolder = $root->getUserFolder($uid);
872
-					if (is_null($userFolder)) {
873
-						$availableSpace = 0;
874
-					} else {
875
-						$free = $quota - $userFolder->getSize(false); // remaining free space for user
876
-						if ($free > 0) {
877
-							$availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
878
-						} else {
879
-							$availableSpace = $free - $versionsSize;
880
-						}
881
-					}
882
-				} else {
883
-					$availableSpace = $quota;
884
-				}
885
-			} else {
886
-				$availableSpace = PHP_INT_MAX;
887
-			}
888
-
889
-			$allVersions = Storage::getVersions($uid, $filename);
890
-
891
-			$time = time();
892
-			[$toDelete, $sizeOfDeletedVersions] = self::getExpireList($time, $allVersions, $availableSpace <= 0);
893
-
894
-			$availableSpace = $availableSpace + $sizeOfDeletedVersions;
895
-			$versionsSize = $versionsSize - $sizeOfDeletedVersions;
896
-
897
-			// if still not enough free space we rearrange the versions from all files
898
-			if ($availableSpace <= 0) {
899
-				$result = self::getAllVersions($uid);
900
-				$allVersions = $result['all'];
901
-
902
-				foreach ($result['by_file'] as $versions) {
903
-					[$toDeleteNew, $size] = self::getExpireList($time, $versions, $availableSpace <= 0);
904
-					$toDelete = array_merge($toDelete, $toDeleteNew);
905
-					$sizeOfDeletedVersions += $size;
906
-				}
907
-				$availableSpace = $availableSpace + $sizeOfDeletedVersions;
908
-				$versionsSize = $versionsSize - $sizeOfDeletedVersions;
909
-			}
910
-
911
-			foreach ($toDelete as $key => $path) {
912
-				\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
913
-				self::deleteVersion($versionsFileview, $path);
914
-				\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
915
-				unset($allVersions[$key]); // update array with the versions we keep
916
-				$logger->info('Expire: ' . $path, ['app' => 'files_versions']);
917
-			}
918
-
919
-			// Check if enough space is available after versions are rearranged.
920
-			// If not we delete the oldest versions until we meet the size limit for versions,
921
-			// but always keep the two latest versions
922
-			$numOfVersions = count($allVersions) - 2 ;
923
-			$i = 0;
924
-			// sort oldest first and make sure that we start at the first element
925
-			ksort($allVersions);
926
-			reset($allVersions);
927
-			while ($availableSpace < 0 && $i < $numOfVersions) {
928
-				$version = current($allVersions);
929
-				\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
930
-				self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
931
-				\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
932
-				$logger->info('running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'], ['app' => 'files_versions']);
933
-				$versionsSize -= $version['size'];
934
-				$availableSpace += $version['size'];
935
-				next($allVersions);
936
-				$i++;
937
-			}
938
-
939
-			return $versionsSize; // finally return the new size of the version history
940
-		}
941
-
942
-		return false;
943
-	}
944
-
945
-	/**
946
-	 * Create recursively missing directories inside of files_versions
947
-	 * that match the given path to a file.
948
-	 *
949
-	 * @param string $filename $path to a file, relative to the user's
950
-	 * "files" folder
951
-	 * @param View $view view on data/user/
952
-	 */
953
-	public static function createMissingDirectories($filename, $view) {
954
-		$dirname = Filesystem::normalizePath(dirname($filename));
955
-		$dirParts = explode('/', $dirname);
956
-		$dir = "/files_versions";
957
-		foreach ($dirParts as $part) {
958
-			$dir = $dir . '/' . $part;
959
-			if (!$view->file_exists($dir)) {
960
-				$view->mkdir($dir);
961
-			}
962
-		}
963
-	}
964
-
965
-	/**
966
-	 * Static workaround
967
-	 * @return Expiration
968
-	 */
969
-	protected static function getExpiration() {
970
-		if (self::$application === null) {
971
-			self::$application = \OC::$server->get(Application::class);
972
-		}
973
-		return self::$application->getContainer()->get(Expiration::class);
974
-	}
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
+
612
+            $versionEntity = $versionEntities[$version->getId()];
613
+            if (!is_null($versionEntity)) {
614
+                $versionsMapper->delete($versionEntity);
615
+            }
616
+
617
+            $version->delete();
618
+            \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
619
+        }
620
+    }
621
+
622
+    /**
623
+     * translate a timestamp into a string like "5 days ago"
624
+     *
625
+     * @param int $timestamp
626
+     * @return string for example "5 days ago"
627
+     */
628
+    private static function getHumanReadableTimestamp(int $timestamp): string {
629
+        $diff = time() - $timestamp;
630
+
631
+        if ($diff < 60) { // first minute
632
+            return  $diff . " seconds ago";
633
+        } elseif ($diff < 3600) { //first hour
634
+            return round($diff / 60) . " minutes ago";
635
+        } elseif ($diff < 86400) { // first day
636
+            return round($diff / 3600) . " hours ago";
637
+        } elseif ($diff < 604800) { //first week
638
+            return round($diff / 86400) . " days ago";
639
+        } elseif ($diff < 2419200) { //first month
640
+            return round($diff / 604800) . " weeks ago";
641
+        } elseif ($diff < 29030400) { // first year
642
+            return round($diff / 2419200) . " months ago";
643
+        } else {
644
+            return round($diff / 29030400) . " years ago";
645
+        }
646
+    }
647
+
648
+    /**
649
+     * returns all stored file versions from a given user
650
+     * @param string $uid id of the user
651
+     * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
652
+     */
653
+    private static function getAllVersions($uid) {
654
+        $view = new View('/' . $uid . '/');
655
+        $dirs = [self::VERSIONS_ROOT];
656
+        $versions = [];
657
+
658
+        while (!empty($dirs)) {
659
+            $dir = array_pop($dirs);
660
+            $files = $view->getDirectoryContent($dir);
661
+
662
+            foreach ($files as $file) {
663
+                $fileData = $file->getData();
664
+                $filePath = $dir . '/' . $fileData['name'];
665
+                if ($file['type'] === 'dir') {
666
+                    $dirs[] = $filePath;
667
+                } else {
668
+                    $versionsBegin = strrpos($filePath, '.v');
669
+                    $relPathStart = strlen(self::VERSIONS_ROOT);
670
+                    $version = substr($filePath, $versionsBegin + 2);
671
+                    $relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
672
+                    $key = $version . '#' . $relpath;
673
+                    $versions[$key] = ['path' => $relpath, 'timestamp' => $version];
674
+                }
675
+            }
676
+        }
677
+
678
+        // newest version first
679
+        krsort($versions);
680
+
681
+        $result = [
682
+            'all' => [],
683
+            'by_file' => [],
684
+        ];
685
+
686
+        foreach ($versions as $key => $value) {
687
+            $size = $view->filesize(self::VERSIONS_ROOT.'/'.$value['path'].'.v'.$value['timestamp']);
688
+            $filename = $value['path'];
689
+
690
+            $result['all'][$key]['version'] = $value['timestamp'];
691
+            $result['all'][$key]['path'] = $filename;
692
+            $result['all'][$key]['size'] = $size;
693
+
694
+            $result['by_file'][$filename][$key]['version'] = $value['timestamp'];
695
+            $result['by_file'][$filename][$key]['path'] = $filename;
696
+            $result['by_file'][$filename][$key]['size'] = $size;
697
+        }
698
+
699
+        return $result;
700
+    }
701
+
702
+    /**
703
+     * get list of files we want to expire
704
+     * @param array $versions list of versions
705
+     * @param integer $time
706
+     * @param bool $quotaExceeded is versions storage limit reached
707
+     * @return array containing the list of to deleted versions and the size of them
708
+     */
709
+    protected static function getExpireList($time, $versions, $quotaExceeded = false) {
710
+        $expiration = self::getExpiration();
711
+
712
+        if ($expiration->shouldAutoExpire()) {
713
+            [$toDelete, $size] = self::getAutoExpireList($time, $versions);
714
+        } else {
715
+            $size = 0;
716
+            $toDelete = [];  // versions we want to delete
717
+        }
718
+
719
+        foreach ($versions as $key => $version) {
720
+            if (!is_numeric($version['version'])) {
721
+                \OC::$server->get(LoggerInterface::class)->error(
722
+                    'Found a non-numeric timestamp version: '. json_encode($version),
723
+                    ['app' => 'files_versions']);
724
+                continue;
725
+            }
726
+            if ($expiration->isExpired((int)($version['version']), $quotaExceeded) && !isset($toDelete[$key])) {
727
+                $size += $version['size'];
728
+                $toDelete[$key] = $version['path'] . '.v' . $version['version'];
729
+            }
730
+        }
731
+
732
+        return [$toDelete, $size];
733
+    }
734
+
735
+    /**
736
+     * get list of files we want to expire
737
+     * @param array $versions list of versions
738
+     * @param integer $time
739
+     * @return array containing the list of to deleted versions and the size of them
740
+     */
741
+    protected static function getAutoExpireList($time, $versions) {
742
+        $size = 0;
743
+        $toDelete = [];  // versions we want to delete
744
+
745
+        $interval = 1;
746
+        $step = Storage::$max_versions_per_interval[$interval]['step'];
747
+        if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
748
+            $nextInterval = -1;
749
+        } else {
750
+            $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
751
+        }
752
+
753
+        $firstVersion = reset($versions);
754
+
755
+        if ($firstVersion === false) {
756
+            return [$toDelete, $size];
757
+        }
758
+
759
+        $firstKey = key($versions);
760
+        $prevTimestamp = $firstVersion['version'];
761
+        $nextVersion = $firstVersion['version'] - $step;
762
+        unset($versions[$firstKey]);
763
+
764
+        foreach ($versions as $key => $version) {
765
+            $newInterval = true;
766
+            while ($newInterval) {
767
+                if ($nextInterval === -1 || $prevTimestamp > $nextInterval) {
768
+                    if ($version['version'] > $nextVersion) {
769
+                        //distance between two version too small, mark to delete
770
+                        $toDelete[$key] = $version['path'] . '.v' . $version['version'];
771
+                        $size += $version['size'];
772
+                        \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']);
773
+                    } else {
774
+                        $nextVersion = $version['version'] - $step;
775
+                        $prevTimestamp = $version['version'];
776
+                    }
777
+                    $newInterval = false; // version checked so we can move to the next one
778
+                } else { // time to move on to the next interval
779
+                    $interval++;
780
+                    $step = Storage::$max_versions_per_interval[$interval]['step'];
781
+                    $nextVersion = $prevTimestamp - $step;
782
+                    if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
783
+                        $nextInterval = -1;
784
+                    } else {
785
+                        $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
786
+                    }
787
+                    $newInterval = true; // we changed the interval -> check same version with new interval
788
+                }
789
+            }
790
+        }
791
+
792
+        return [$toDelete, $size];
793
+    }
794
+
795
+    /**
796
+     * Schedule versions expiration for the given file
797
+     *
798
+     * @param string $uid owner of the file
799
+     * @param string $fileName file/folder for which to schedule expiration
800
+     */
801
+    public static function scheduleExpire($uid, $fileName) {
802
+        // let the admin disable auto expire
803
+        $expiration = self::getExpiration();
804
+        if ($expiration->isEnabled()) {
805
+            $command = new Expire($uid, $fileName);
806
+            /** @var IBus $bus */
807
+            $bus = \OC::$server->get(IBus::class);
808
+            $bus->push($command);
809
+        }
810
+    }
811
+
812
+    /**
813
+     * Expire versions which exceed the quota.
814
+     *
815
+     * This will setup the filesystem for the given user but will not
816
+     * tear it down afterwards.
817
+     *
818
+     * @param string $filename path to file to expire
819
+     * @param string $uid user for which to expire the version
820
+     * @return bool|int|null
821
+     */
822
+    public static function expire($filename, $uid) {
823
+        $expiration = self::getExpiration();
824
+
825
+        /** @var LoggerInterface $logger */
826
+        $logger = \OC::$server->get(LoggerInterface::class);
827
+
828
+        if ($expiration->isEnabled()) {
829
+            // get available disk space for user
830
+            $user = \OC::$server->get(IUserManager::class)->get($uid);
831
+            if (is_null($user)) {
832
+                $logger->error('Backends provided no user object for ' . $uid, ['app' => 'files_versions']);
833
+                throw new \OC\User\NoUserException('Backends provided no user object for ' . $uid);
834
+            }
835
+
836
+            \OC_Util::setupFS($uid);
837
+
838
+            try {
839
+                if (!Filesystem::file_exists($filename)) {
840
+                    return false;
841
+                }
842
+            } catch (StorageNotAvailableException $e) {
843
+                // if we can't check that the file hasn't been deleted we can only assume that it hasn't
844
+                // note that this `StorageNotAvailableException` is about the file the versions originate from,
845
+                // not the storage that the versions are stored on
846
+            }
847
+
848
+            if (empty($filename)) {
849
+                // file maybe renamed or deleted
850
+                return false;
851
+            }
852
+            $versionsFileview = new View('/'.$uid.'/files_versions');
853
+
854
+            $softQuota = true;
855
+            $quota = $user->getQuota();
856
+            if ($quota === null || $quota === 'none') {
857
+                $quota = Filesystem::free_space('/');
858
+                $softQuota = false;
859
+            } else {
860
+                $quota = \OCP\Util::computerFileSize($quota);
861
+            }
862
+
863
+            // make sure that we have the current size of the version history
864
+            $versionsSize = self::getVersionsSize($uid);
865
+
866
+            // calculate available space for version history
867
+            // subtract size of files and current versions size from quota
868
+            if ($quota >= 0) {
869
+                if ($softQuota) {
870
+                    $root = \OC::$server->get(IRootFolder::class);
871
+                    $userFolder = $root->getUserFolder($uid);
872
+                    if (is_null($userFolder)) {
873
+                        $availableSpace = 0;
874
+                    } else {
875
+                        $free = $quota - $userFolder->getSize(false); // remaining free space for user
876
+                        if ($free > 0) {
877
+                            $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
878
+                        } else {
879
+                            $availableSpace = $free - $versionsSize;
880
+                        }
881
+                    }
882
+                } else {
883
+                    $availableSpace = $quota;
884
+                }
885
+            } else {
886
+                $availableSpace = PHP_INT_MAX;
887
+            }
888
+
889
+            $allVersions = Storage::getVersions($uid, $filename);
890
+
891
+            $time = time();
892
+            [$toDelete, $sizeOfDeletedVersions] = self::getExpireList($time, $allVersions, $availableSpace <= 0);
893
+
894
+            $availableSpace = $availableSpace + $sizeOfDeletedVersions;
895
+            $versionsSize = $versionsSize - $sizeOfDeletedVersions;
896
+
897
+            // if still not enough free space we rearrange the versions from all files
898
+            if ($availableSpace <= 0) {
899
+                $result = self::getAllVersions($uid);
900
+                $allVersions = $result['all'];
901
+
902
+                foreach ($result['by_file'] as $versions) {
903
+                    [$toDeleteNew, $size] = self::getExpireList($time, $versions, $availableSpace <= 0);
904
+                    $toDelete = array_merge($toDelete, $toDeleteNew);
905
+                    $sizeOfDeletedVersions += $size;
906
+                }
907
+                $availableSpace = $availableSpace + $sizeOfDeletedVersions;
908
+                $versionsSize = $versionsSize - $sizeOfDeletedVersions;
909
+            }
910
+
911
+            foreach ($toDelete as $key => $path) {
912
+                \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
913
+                self::deleteVersion($versionsFileview, $path);
914
+                \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
915
+                unset($allVersions[$key]); // update array with the versions we keep
916
+                $logger->info('Expire: ' . $path, ['app' => 'files_versions']);
917
+            }
918
+
919
+            // Check if enough space is available after versions are rearranged.
920
+            // If not we delete the oldest versions until we meet the size limit for versions,
921
+            // but always keep the two latest versions
922
+            $numOfVersions = count($allVersions) - 2 ;
923
+            $i = 0;
924
+            // sort oldest first and make sure that we start at the first element
925
+            ksort($allVersions);
926
+            reset($allVersions);
927
+            while ($availableSpace < 0 && $i < $numOfVersions) {
928
+                $version = current($allVersions);
929
+                \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
930
+                self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
931
+                \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
932
+                $logger->info('running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'], ['app' => 'files_versions']);
933
+                $versionsSize -= $version['size'];
934
+                $availableSpace += $version['size'];
935
+                next($allVersions);
936
+                $i++;
937
+            }
938
+
939
+            return $versionsSize; // finally return the new size of the version history
940
+        }
941
+
942
+        return false;
943
+    }
944
+
945
+    /**
946
+     * Create recursively missing directories inside of files_versions
947
+     * that match the given path to a file.
948
+     *
949
+     * @param string $filename $path to a file, relative to the user's
950
+     * "files" folder
951
+     * @param View $view view on data/user/
952
+     */
953
+    public static function createMissingDirectories($filename, $view) {
954
+        $dirname = Filesystem::normalizePath(dirname($filename));
955
+        $dirParts = explode('/', $dirname);
956
+        $dir = "/files_versions";
957
+        foreach ($dirParts as $part) {
958
+            $dir = $dir . '/' . $part;
959
+            if (!$view->file_exists($dir)) {
960
+                $view->mkdir($dir);
961
+            }
962
+        }
963
+    }
964
+
965
+    /**
966
+     * Static workaround
967
+     * @return Expiration
968
+     */
969
+    protected static function getExpiration() {
970
+        if (self::$application === null) {
971
+            self::$application = \OC::$server->get(Application::class);
972
+        }
973
+        return self::$application->getContainer()->get(Expiration::class);
974
+    }
975 975
 }
Please login to merge, or discard this patch.