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