Passed
Push — master ( 62403d...0c3e2f )
by Joas
14:50 queued 14s
created
apps/encryption/templates/mail.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -15,10 +15,10 @@
 block discarded – undo
15 15
 					<td width="20px">&nbsp;</td>
16 16
 					<td style="font-weight:normal; font-size:0.8em; line-height:1.2em; font-family:verdana,'arial',sans;">
17 17
 						<?php
18
-						print_unescaped($l->t('Hey there,<br><br>the admin enabled server-side-encryption. Your files were encrypted using the password <strong>%s</strong>.<br><br>Please login to the web interface, go to the section "basic encryption module" of your personal settings and update your encryption password by entering this password into the "old log-in password" field and your current login-password.<br><br>', [$_['password']]));
19
-						// TRANSLATORS term at the end of a mail
20
-						p($l->t('Cheers!'));
21
-						?>
18
+                        print_unescaped($l->t('Hey there,<br><br>the admin enabled server-side-encryption. Your files were encrypted using the password <strong>%s</strong>.<br><br>Please login to the web interface, go to the section "basic encryption module" of your personal settings and update your encryption password by entering this password into the "old log-in password" field and your current login-password.<br><br>', [$_['password']]));
19
+                        // TRANSLATORS term at the end of a mail
20
+                        p($l->t('Cheers!'));
21
+                        ?>
22 22
 					</td>
23 23
 				</tr>
24 24
 				<tr><td colspan="2">&nbsp;</td></tr>
Please login to merge, or discard this patch.
core/Command/Status.php 1 patch
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -28,23 +28,23 @@
 block discarded – undo
28 28
 use Symfony\Component\Console\Output\OutputInterface;
29 29
 
30 30
 class Status extends Base {
31
-	protected function configure() {
32
-		parent::configure();
31
+    protected function configure() {
32
+        parent::configure();
33 33
 
34
-		$this
35
-			->setName('status')
36
-			->setDescription('show some status information')
37
-		;
38
-	}
34
+        $this
35
+            ->setName('status')
36
+            ->setDescription('show some status information')
37
+        ;
38
+    }
39 39
 
40
-	protected function execute(InputInterface $input, OutputInterface $output) {
41
-		$values = [
42
-			'installed' => (bool) \OC::$server->getConfig()->getSystemValue('installed', false),
43
-			'version' => implode('.', \OCP\Util::getVersion()),
44
-			'versionstring' => \OC_Util::getVersionString(),
45
-			'edition' => '',
46
-		];
40
+    protected function execute(InputInterface $input, OutputInterface $output) {
41
+        $values = [
42
+            'installed' => (bool) \OC::$server->getConfig()->getSystemValue('installed', false),
43
+            'version' => implode('.', \OCP\Util::getVersion()),
44
+            'versionstring' => \OC_Util::getVersionString(),
45
+            'edition' => '',
46
+        ];
47 47
 
48
-		$this->writeArrayInOutputFormat($input, $output, $values);
49
-	}
48
+        $this->writeArrayInOutputFormat($input, $output, $values);
49
+    }
50 50
 }
Please login to merge, or discard this patch.
index.php 1 patch
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -33,48 +33,48 @@
 block discarded – undo
33 33
 
34 34
 try {
35 35
 
36
-	require_once __DIR__ . '/lib/base.php';
36
+    require_once __DIR__ . '/lib/base.php';
37 37
 
38
-	OC::handleRequest();
38
+    OC::handleRequest();
39 39
 
40 40
 } catch(\OC\ServiceUnavailableException $ex) {
41
-	\OC::$server->getLogger()->logException($ex, ['app' => 'index']);
41
+    \OC::$server->getLogger()->logException($ex, ['app' => 'index']);
42 42
 
43
-	//show the user a detailed error page
44
-	OC_Template::printExceptionErrorPage($ex, 503);
43
+    //show the user a detailed error page
44
+    OC_Template::printExceptionErrorPage($ex, 503);
45 45
 } catch (\OC\HintException $ex) {
46
-	try {
47
-		OC_Template::printErrorPage($ex->getMessage(), $ex->getHint(), 503);
48
-	} catch (Exception $ex2) {
49
-		try {
50
-			\OC::$server->getLogger()->logException($ex, ['app' => 'index']);
51
-			\OC::$server->getLogger()->logException($ex2, ['app' => 'index']);
52
-		} catch (Throwable $e) {
53
-			// no way to log it properly - but to avoid a white page of death we try harder and ignore this one here
54
-		}
46
+    try {
47
+        OC_Template::printErrorPage($ex->getMessage(), $ex->getHint(), 503);
48
+    } catch (Exception $ex2) {
49
+        try {
50
+            \OC::$server->getLogger()->logException($ex, ['app' => 'index']);
51
+            \OC::$server->getLogger()->logException($ex2, ['app' => 'index']);
52
+        } catch (Throwable $e) {
53
+            // no way to log it properly - but to avoid a white page of death we try harder and ignore this one here
54
+        }
55 55
 
56
-		//show the user a detailed error page
57
-		OC_Template::printExceptionErrorPage($ex, 500);
58
-	}
56
+        //show the user a detailed error page
57
+        OC_Template::printExceptionErrorPage($ex, 500);
58
+    }
59 59
 } catch (\OC\User\LoginException $ex) {
60
-	OC_Template::printErrorPage($ex->getMessage(), $ex->getMessage(), 403);
60
+    OC_Template::printErrorPage($ex->getMessage(), $ex->getMessage(), 403);
61 61
 } catch (Exception $ex) {
62
-	\OC::$server->getLogger()->logException($ex, ['app' => 'index']);
62
+    \OC::$server->getLogger()->logException($ex, ['app' => 'index']);
63 63
 
64
-	//show the user a detailed error page
65
-	OC_Template::printExceptionErrorPage($ex, 500);
64
+    //show the user a detailed error page
65
+    OC_Template::printExceptionErrorPage($ex, 500);
66 66
 } catch (Error $ex) {
67
-	try {
68
-		\OC::$server->getLogger()->logException($ex, ['app' => 'index']);
69
-	} catch (Error $e) {
70
-		http_response_code(500);
71
-		header('Content-Type: text/plain; charset=utf-8');
72
-		print("Internal Server Error\n\n");
73
-		print("The server encountered an internal error and was unable to complete your request.\n");
74
-		print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
75
-		print("More details can be found in the webserver log.\n");
67
+    try {
68
+        \OC::$server->getLogger()->logException($ex, ['app' => 'index']);
69
+    } catch (Error $e) {
70
+        http_response_code(500);
71
+        header('Content-Type: text/plain; charset=utf-8');
72
+        print("Internal Server Error\n\n");
73
+        print("The server encountered an internal error and was unable to complete your request.\n");
74
+        print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
75
+        print("More details can be found in the webserver log.\n");
76 76
 
77
-		throw $ex;
78
-	}
79
-	OC_Template::printExceptionErrorPage($ex, 500);
77
+        throw $ex;
78
+    }
79
+    OC_Template::printExceptionErrorPage($ex, 500);
80 80
 }
Please login to merge, or discard this patch.
public.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -34,62 +34,62 @@
 block discarded – undo
34 34
 
35 35
 try {
36 36
 
37
-	require_once __DIR__ . '/lib/base.php';
38
-	if (\OCP\Util::needUpgrade()) {
39
-		// since the behavior of apps or remotes are unpredictable during
40
-		// an upgrade, return a 503 directly
41
-		OC_Template::printErrorPage('Service unavailable', '', 503);
42
-		exit;
43
-	}
37
+    require_once __DIR__ . '/lib/base.php';
38
+    if (\OCP\Util::needUpgrade()) {
39
+        // since the behavior of apps or remotes are unpredictable during
40
+        // an upgrade, return a 503 directly
41
+        OC_Template::printErrorPage('Service unavailable', '', 503);
42
+        exit;
43
+    }
44 44
 
45
-	OC::checkMaintenanceMode();
46
-	$request = \OC::$server->getRequest();
47
-	$pathInfo = $request->getPathInfo();
45
+    OC::checkMaintenanceMode();
46
+    $request = \OC::$server->getRequest();
47
+    $pathInfo = $request->getPathInfo();
48 48
 
49
-	if (!$pathInfo && $request->getParam('service', '') === '') {
50
-		http_response_code(404);
51
-		exit;
52
-	} elseif ($request->getParam('service', '')) {
53
-		$service = $request->getParam('service', '');
54
-	} else {
55
-		$pathInfo = trim($pathInfo, '/');
56
-		list($service) = explode('/', $pathInfo);
57
-	}
58
-	$file = \OC::$server->getConfig()->getAppValue('core', 'public_' . strip_tags($service));
59
-	if ($file === '') {
60
-		http_response_code(404);
61
-		exit;
62
-	}
49
+    if (!$pathInfo && $request->getParam('service', '') === '') {
50
+        http_response_code(404);
51
+        exit;
52
+    } elseif ($request->getParam('service', '')) {
53
+        $service = $request->getParam('service', '');
54
+    } else {
55
+        $pathInfo = trim($pathInfo, '/');
56
+        list($service) = explode('/', $pathInfo);
57
+    }
58
+    $file = \OC::$server->getConfig()->getAppValue('core', 'public_' . strip_tags($service));
59
+    if ($file === '') {
60
+        http_response_code(404);
61
+        exit;
62
+    }
63 63
 
64
-	$parts = explode('/', $file, 2);
65
-	$app = $parts[0];
64
+    $parts = explode('/', $file, 2);
65
+    $app = $parts[0];
66 66
 
67
-	// Load all required applications
68
-	\OC::$REQUESTEDAPP = $app;
69
-	OC_App::loadApps(['authentication']);
70
-	OC_App::loadApps(['filesystem', 'logging']);
67
+    // Load all required applications
68
+    \OC::$REQUESTEDAPP = $app;
69
+    OC_App::loadApps(['authentication']);
70
+    OC_App::loadApps(['filesystem', 'logging']);
71 71
 
72
-	if (!\OC::$server->getAppManager()->isInstalled($app)) {
73
-		http_response_code(404);
74
-		exit;
75
-	}
76
-	OC_App::loadApp($app);
77
-	OC_User::setIncognitoMode(true);
72
+    if (!\OC::$server->getAppManager()->isInstalled($app)) {
73
+        http_response_code(404);
74
+        exit;
75
+    }
76
+    OC_App::loadApp($app);
77
+    OC_User::setIncognitoMode(true);
78 78
 
79
-	$baseuri = OC::$WEBROOT . '/public.php/' . $service . '/';
79
+    $baseuri = OC::$WEBROOT . '/public.php/' . $service . '/';
80 80
 
81
-	require_once OC_App::getAppPath($app) . '/' . $parts[1];
81
+    require_once OC_App::getAppPath($app) . '/' . $parts[1];
82 82
 
83 83
 } catch (Exception $ex) {
84
-	$status = 500;
85
-	if ($ex instanceof \OC\ServiceUnavailableException) {
86
-		$status = 503;
87
-	}
88
-	//show the user a detailed error page
89
-	\OC::$server->getLogger()->logException($ex, ['app' => 'public']);
90
-	OC_Template::printExceptionErrorPage($ex, $status);
84
+    $status = 500;
85
+    if ($ex instanceof \OC\ServiceUnavailableException) {
86
+        $status = 503;
87
+    }
88
+    //show the user a detailed error page
89
+    \OC::$server->getLogger()->logException($ex, ['app' => 'public']);
90
+    OC_Template::printExceptionErrorPage($ex, $status);
91 91
 } catch (Error $ex) {
92
-	//show the user a detailed error page
93
-	\OC::$server->getLogger()->logException($ex, ['app' => 'public']);
94
-	OC_Template::printExceptionErrorPage($ex, 500);
92
+    //show the user a detailed error page
93
+    \OC::$server->getLogger()->logException($ex, ['app' => 'public']);
94
+    OC_Template::printExceptionErrorPage($ex, 500);
95 95
 }
Please login to merge, or discard this patch.
cron.php 1 patch
Indentation   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -39,126 +39,126 @@
 block discarded – undo
39 39
 
40 40
 try {
41 41
 
42
-	require_once __DIR__ . '/lib/base.php';
43
-
44
-	if (\OCP\Util::needUpgrade()) {
45
-		\OC::$server->getLogger()->debug('Update required, skipping cron', ['app' => 'cron']);
46
-		exit;
47
-	}
48
-	if ((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) {
49
-		\OC::$server->getLogger()->debug('We are in maintenance mode, skipping cron', ['app' => 'cron']);
50
-		exit;
51
-	}
52
-
53
-	// load all apps to get all api routes properly setup
54
-	OC_App::loadApps();
55
-
56
-	\OC::$server->getSession()->close();
57
-
58
-	// initialize a dummy memory session
59
-	$session = new \OC\Session\Memory('');
60
-	$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
61
-	$session = $cryptoWrapper->wrapSession($session);
62
-	\OC::$server->setSession($session);
63
-
64
-	$logger = \OC::$server->getLogger();
65
-	$config = \OC::$server->getConfig();
66
-
67
-	// Don't do anything if Nextcloud has not been installed
68
-	if (!$config->getSystemValue('installed', false)) {
69
-		exit(0);
70
-	}
71
-
72
-	\OC::$server->getTempManager()->cleanOld();
73
-
74
-	// Exit if background jobs are disabled!
75
-	$appMode = $config->getAppValue('core', 'backgroundjobs_mode', 'ajax');
76
-	if ($appMode === 'none') {
77
-		if (OC::$CLI) {
78
-			echo 'Background Jobs are disabled!' . PHP_EOL;
79
-		} else {
80
-			OC_JSON::error(['data' => ['message' => 'Background jobs disabled!']]);
81
-		}
82
-		exit(1);
83
-	}
84
-
85
-	if (OC::$CLI) {
86
-		// set to run indefinitely if needed
87
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
88
-			@set_time_limit(0);
89
-		}
90
-
91
-		// the cron job must be executed with the right user
92
-		if (!function_exists('posix_getuid')) {
93
-			echo "The posix extensions are required - see http://php.net/manual/en/book.posix.php" . PHP_EOL;
94
-			exit(1);
95
-		}
96
-
97
-		$user = posix_getpwuid(posix_getuid());
98
-		$configUser = posix_getpwuid(fileowner(OC::$configDir . 'config.php'));
99
-		if ($user['name'] !== $configUser['name']) {
100
-			echo "Console has to be executed with the user that owns the file config/config.php" . PHP_EOL;
101
-			echo "Current user: " . $user['name'] . PHP_EOL;
102
-			echo "Owner of config.php: " . $configUser['name'] . PHP_EOL;
103
-			exit(1);
104
-		}
105
-
106
-		// We call Nextcloud from the CLI (aka cron)
107
-		if ($appMode !== 'cron') {
108
-			$config->setAppValue('core', 'backgroundjobs_mode', 'cron');
109
-		}
110
-
111
-		// Work
112
-		$jobList = \OC::$server->getJobList();
113
-
114
-		// We only ask for jobs for 14 minutes, because after 5 minutes the next
115
-		// system cron task should spawn and we want to have at most three
116
-		// cron jobs running in parallel.
117
-		$endTime = time() + 14 * 60;
118
-
119
-		$executedJobs = [];
120
-		while ($job = $jobList->getNext()) {
121
-			if (isset($executedJobs[$job->getId()])) {
122
-				$jobList->unlockJob($job);
123
-				break;
124
-			}
125
-
126
-			$job->execute($jobList, $logger);
127
-			// clean up after unclean jobs
128
-			\OC_Util::tearDownFS();
129
-
130
-			$jobList->setLastJob($job);
131
-			$executedJobs[$job->getId()] = true;
132
-			unset($job);
133
-
134
-			if (time() > $endTime) {
135
-				break;
136
-			}
137
-		}
138
-
139
-	} else {
140
-		// We call cron.php from some website
141
-		if ($appMode === 'cron') {
142
-			// Cron is cron :-P
143
-			OC_JSON::error(['data' => ['message' => 'Backgroundjobs are using system cron!']]);
144
-		} else {
145
-			// Work and success :-)
146
-			$jobList = \OC::$server->getJobList();
147
-			$job = $jobList->getNext();
148
-			if ($job != null) {
149
-				$job->execute($jobList, $logger);
150
-				$jobList->setLastJob($job);
151
-			}
152
-			OC_JSON::success();
153
-		}
154
-	}
155
-
156
-	// Log the successful cron execution
157
-	$config->setAppValue('core', 'lastcron', time());
158
-	exit();
42
+    require_once __DIR__ . '/lib/base.php';
43
+
44
+    if (\OCP\Util::needUpgrade()) {
45
+        \OC::$server->getLogger()->debug('Update required, skipping cron', ['app' => 'cron']);
46
+        exit;
47
+    }
48
+    if ((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) {
49
+        \OC::$server->getLogger()->debug('We are in maintenance mode, skipping cron', ['app' => 'cron']);
50
+        exit;
51
+    }
52
+
53
+    // load all apps to get all api routes properly setup
54
+    OC_App::loadApps();
55
+
56
+    \OC::$server->getSession()->close();
57
+
58
+    // initialize a dummy memory session
59
+    $session = new \OC\Session\Memory('');
60
+    $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
61
+    $session = $cryptoWrapper->wrapSession($session);
62
+    \OC::$server->setSession($session);
63
+
64
+    $logger = \OC::$server->getLogger();
65
+    $config = \OC::$server->getConfig();
66
+
67
+    // Don't do anything if Nextcloud has not been installed
68
+    if (!$config->getSystemValue('installed', false)) {
69
+        exit(0);
70
+    }
71
+
72
+    \OC::$server->getTempManager()->cleanOld();
73
+
74
+    // Exit if background jobs are disabled!
75
+    $appMode = $config->getAppValue('core', 'backgroundjobs_mode', 'ajax');
76
+    if ($appMode === 'none') {
77
+        if (OC::$CLI) {
78
+            echo 'Background Jobs are disabled!' . PHP_EOL;
79
+        } else {
80
+            OC_JSON::error(['data' => ['message' => 'Background jobs disabled!']]);
81
+        }
82
+        exit(1);
83
+    }
84
+
85
+    if (OC::$CLI) {
86
+        // set to run indefinitely if needed
87
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
88
+            @set_time_limit(0);
89
+        }
90
+
91
+        // the cron job must be executed with the right user
92
+        if (!function_exists('posix_getuid')) {
93
+            echo "The posix extensions are required - see http://php.net/manual/en/book.posix.php" . PHP_EOL;
94
+            exit(1);
95
+        }
96
+
97
+        $user = posix_getpwuid(posix_getuid());
98
+        $configUser = posix_getpwuid(fileowner(OC::$configDir . 'config.php'));
99
+        if ($user['name'] !== $configUser['name']) {
100
+            echo "Console has to be executed with the user that owns the file config/config.php" . PHP_EOL;
101
+            echo "Current user: " . $user['name'] . PHP_EOL;
102
+            echo "Owner of config.php: " . $configUser['name'] . PHP_EOL;
103
+            exit(1);
104
+        }
105
+
106
+        // We call Nextcloud from the CLI (aka cron)
107
+        if ($appMode !== 'cron') {
108
+            $config->setAppValue('core', 'backgroundjobs_mode', 'cron');
109
+        }
110
+
111
+        // Work
112
+        $jobList = \OC::$server->getJobList();
113
+
114
+        // We only ask for jobs for 14 minutes, because after 5 minutes the next
115
+        // system cron task should spawn and we want to have at most three
116
+        // cron jobs running in parallel.
117
+        $endTime = time() + 14 * 60;
118
+
119
+        $executedJobs = [];
120
+        while ($job = $jobList->getNext()) {
121
+            if (isset($executedJobs[$job->getId()])) {
122
+                $jobList->unlockJob($job);
123
+                break;
124
+            }
125
+
126
+            $job->execute($jobList, $logger);
127
+            // clean up after unclean jobs
128
+            \OC_Util::tearDownFS();
129
+
130
+            $jobList->setLastJob($job);
131
+            $executedJobs[$job->getId()] = true;
132
+            unset($job);
133
+
134
+            if (time() > $endTime) {
135
+                break;
136
+            }
137
+        }
138
+
139
+    } else {
140
+        // We call cron.php from some website
141
+        if ($appMode === 'cron') {
142
+            // Cron is cron :-P
143
+            OC_JSON::error(['data' => ['message' => 'Backgroundjobs are using system cron!']]);
144
+        } else {
145
+            // Work and success :-)
146
+            $jobList = \OC::$server->getJobList();
147
+            $job = $jobList->getNext();
148
+            if ($job != null) {
149
+                $job->execute($jobList, $logger);
150
+                $jobList->setLastJob($job);
151
+            }
152
+            OC_JSON::success();
153
+        }
154
+    }
155
+
156
+    // Log the successful cron execution
157
+    $config->setAppValue('core', 'lastcron', time());
158
+    exit();
159 159
 
160 160
 } catch (Exception $ex) {
161
-	\OC::$server->getLogger()->logException($ex, ['app' => 'cron']);
161
+    \OC::$server->getLogger()->logException($ex, ['app' => 'cron']);
162 162
 } catch (Error $ex) {
163
-	\OC::$server->getLogger()->logException($ex, ['app' => 'cron']);
163
+    \OC::$server->getLogger()->logException($ex, ['app' => 'cron']);
164 164
 }
Please login to merge, or discard this patch.
apps/cloud_federation_api/lib/Controller/RequestHandlerController.php 1 patch
Indentation   +244 added lines, -244 removed lines patch added patch discarded remove patch
@@ -52,249 +52,249 @@
 block discarded – undo
52 52
  */
53 53
 class RequestHandlerController extends Controller {
54 54
 
55
-	/** @var ILogger */
56
-	private $logger;
57
-
58
-	/** @var IUserManager */
59
-	private $userManager;
60
-
61
-	/** @var IGroupManager */
62
-	private $groupManager;
63
-
64
-	/** @var IURLGenerator */
65
-	private $urlGenerator;
66
-
67
-	/** @var ICloudFederationProviderManager */
68
-	private $cloudFederationProviderManager;
69
-
70
-	/** @var Config */
71
-	private $config;
72
-
73
-	/** @var ICloudFederationFactory */
74
-	private $factory;
75
-
76
-	/** @var ICloudIdManager */
77
-	private $cloudIdManager;
78
-
79
-	public function __construct($appName,
80
-								IRequest $request,
81
-								ILogger $logger,
82
-								IUserManager $userManager,
83
-								IGroupManager $groupManager,
84
-								IURLGenerator $urlGenerator,
85
-								ICloudFederationProviderManager $cloudFederationProviderManager,
86
-								Config $config,
87
-								ICloudFederationFactory $factory,
88
-								ICloudIdManager $cloudIdManager
89
-	) {
90
-		parent::__construct($appName, $request);
91
-
92
-		$this->logger = $logger;
93
-		$this->userManager = $userManager;
94
-		$this->groupManager = $groupManager;
95
-		$this->urlGenerator = $urlGenerator;
96
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
97
-		$this->config = $config;
98
-		$this->factory = $factory;
99
-		$this->cloudIdManager = $cloudIdManager;
100
-	}
101
-
102
-	/**
103
-	 * add share
104
-	 *
105
-	 * @NoCSRFRequired
106
-	 * @PublicPage
107
-	 * @BruteForceProtection(action=receiveFederatedShare)
108
-	 *
109
-	 * @param string $shareWith
110
-	 * @param string $name resource name (e.g. document.odt)
111
-	 * @param string $description share description (optional)
112
-	 * @param string $providerId resource UID on the provider side
113
-	 * @param string $owner provider specific UID of the user who owns the resource
114
-	 * @param string $ownerDisplayName display name of the user who shared the item
115
-	 * @param string $sharedBy provider specific UID of the user who shared the resource
116
-	 * @param string $sharedByDisplayName display name of the user who shared the resource
117
-	 * @param array $protocol (e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]])
118
-	 * @param string $shareType ('group' or 'user' share)
119
-	 * @param $resourceType ('file', 'calendar',...)
120
-	 * @return Http\DataResponse|JSONResponse
121
-	 *
122
-	 * Example: curl -H "Content-Type: application/json" -X POST -d '{"shareWith":"admin1@serve1","name":"welcome server2.txt","description":"desc","providerId":"2","owner":"admin2@http://localhost/server2","ownerDisplayName":"admin2 display","shareType":"user","resourceType":"file","protocol":{"name":"webdav","options":{"sharedSecret":"secret","permissions":"webdav-property"}}}' http://localhost/server/index.php/ocm/shares
123
-	 */
124
-	public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
125
-
126
-		// check if all required parameters are set
127
-		if ($shareWith === null ||
128
-			$name === null ||
129
-			$providerId === null ||
130
-			$owner === null ||
131
-			$resourceType === null ||
132
-			$shareType === null ||
133
-			!is_array($protocol) ||
134
-			!isset($protocol['name']) ||
135
-			!isset ($protocol['options']) ||
136
-			!is_array($protocol['options']) ||
137
-			!isset($protocol['options']['sharedSecret'])
138
-		) {
139
-			return new JSONResponse(
140
-				['message' => 'Missing arguments'],
141
-				Http::STATUS_BAD_REQUEST
142
-			);
143
-		}
144
-
145
-		$supportedShareTypes = $this->config->getSupportedShareTypes($resourceType);
146
-		if (!in_array($shareType, $supportedShareTypes)) {
147
-			return new JSONResponse(
148
-				['message' => 'Share type "' . $shareType . '" not implemented'],
149
-				Http::STATUS_NOT_IMPLEMENTED
150
-			);
151
-		}
152
-
153
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
154
-		$shareWith = $cloudId->getUser();
155
-
156
-		if ($shareType === 'user') {
157
-			$shareWith = $this->mapUid($shareWith);
158
-
159
-			if (!$this->userManager->userExists($shareWith)) {
160
-				return new JSONResponse(
161
-					['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
162
-					Http::STATUS_BAD_REQUEST
163
-				);
164
-			}
165
-		}
166
-
167
-		if ($shareType === 'group') {
168
-			if(!$this->groupManager->groupExists($shareWith)) {
169
-				return new JSONResponse(
170
-					['message' => 'Group "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
171
-					Http::STATUS_BAD_REQUEST
172
-				);
173
-			}
174
-		}
175
-
176
-		// if no explicit display name is given, we use the uid as display name
177
-		$ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
178
-		$sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
179
-
180
-		// sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
181
-		if ($sharedBy === null) {
182
-			$sharedBy = $owner;
183
-			$sharedByDisplayName = $ownerDisplayName;
184
-		}
185
-
186
-		try {
187
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
188
-			$share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, '', $shareType, $resourceType);
189
-			$share->setProtocol($protocol);
190
-			$provider->shareReceived($share);
191
-		} catch (ProviderDoesNotExistsException $e) {
192
-			return new JSONResponse(
193
-				['message' => $e->getMessage()],
194
-				Http::STATUS_NOT_IMPLEMENTED
195
-			);
196
-		} catch (ProviderCouldNotAddShareException $e) {
197
-			return new JSONResponse(
198
-				['message' => $e->getMessage()],
199
-				$e->getCode()
200
-			);
201
-		} catch (\Exception $e) {
202
-			return new JSONResponse(
203
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
204
-				Http::STATUS_BAD_REQUEST
205
-			);
206
-		}
207
-
208
-		$user = $this->userManager->get($shareWith);
209
-		$recipientDisplayName = '';
210
-		if($user) {
211
-			$recipientDisplayName = $user->getDisplayName();
212
-		}
213
-
214
-		return new JSONResponse(
215
-			['recipientDisplayName' => $recipientDisplayName],
216
-			Http::STATUS_CREATED);
217
-
218
-	}
219
-
220
-	/**
221
-	 * receive notification about existing share
222
-	 *
223
-	 * @NoCSRFRequired
224
-	 * @PublicPage
225
-	 * @BruteForceProtection(action=receiveFederatedShareNotification)
226
-	 *
227
-	 * @param string $notificationType (notification type, e.g. SHARE_ACCEPTED)
228
-	 * @param string $resourceType (calendar, file, contact,...)
229
-	 * @param string $providerId id of the share
230
-	 * @param array $notification the actual payload of the notification
231
-	 * @return JSONResponse
232
-	 */
233
-	public function receiveNotification($notificationType, $resourceType, $providerId, array $notification) {
234
-
235
-		// check if all required parameters are set
236
-		if ($notificationType === null ||
237
-			$resourceType === null ||
238
-			$providerId === null ||
239
-			!is_array($notification)
240
-		) {
241
-			return new JSONResponse(
242
-				['message' => 'Missing arguments'],
243
-				Http::STATUS_BAD_REQUEST
244
-			);
245
-		}
246
-
247
-		try {
248
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
249
-			$result = $provider->notificationReceived($notificationType, $providerId, $notification);
250
-		} catch (ProviderDoesNotExistsException $e) {
251
-			return new JSONResponse(
252
-				['message' => $e->getMessage()],
253
-				Http::STATUS_BAD_REQUEST
254
-			);
255
-		} catch (ShareNotFound $e) {
256
-			return new JSONResponse(
257
-				['message' => $e->getMessage()],
258
-				Http::STATUS_BAD_REQUEST
259
-			);
260
-		} catch (ActionNotSupportedException $e) {
261
-			return new JSONResponse(
262
-				['message' => $e->getMessage()],
263
-				Http::STATUS_NOT_IMPLEMENTED
264
-			);
265
-		} catch (BadRequestException $e) {
266
-			return new JSONResponse($e->getReturnMessage(), Http::STATUS_BAD_REQUEST);
267
-		} catch (AuthenticationFailedException $e) {
268
-			return new JSONResponse(["message" => "RESOURCE_NOT_FOUND"], Http::STATUS_FORBIDDEN);
269
-		}
270
-		catch (\Exception $e) {
271
-			return new JSONResponse(
272
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
273
-				Http::STATUS_BAD_REQUEST
274
-			);
275
-		}
276
-
277
-		return new JSONResponse($result,Http::STATUS_CREATED);
278
-
279
-	}
280
-
281
-	/**
282
-	 * map login name to internal LDAP UID if a LDAP backend is in use
283
-	 *
284
-	 * @param string $uid
285
-	 * @return string mixed
286
-	 */
287
-	private function mapUid($uid) {
288
-		// FIXME this should be a method in the user management instead
289
-		$this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
290
-		\OCP\Util::emitHook(
291
-			'\OCA\Files_Sharing\API\Server2Server',
292
-			'preLoginNameUsedAsUserName',
293
-			['uid' => &$uid]
294
-		);
295
-		$this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
296
-
297
-		return $uid;
298
-	}
55
+    /** @var ILogger */
56
+    private $logger;
57
+
58
+    /** @var IUserManager */
59
+    private $userManager;
60
+
61
+    /** @var IGroupManager */
62
+    private $groupManager;
63
+
64
+    /** @var IURLGenerator */
65
+    private $urlGenerator;
66
+
67
+    /** @var ICloudFederationProviderManager */
68
+    private $cloudFederationProviderManager;
69
+
70
+    /** @var Config */
71
+    private $config;
72
+
73
+    /** @var ICloudFederationFactory */
74
+    private $factory;
75
+
76
+    /** @var ICloudIdManager */
77
+    private $cloudIdManager;
78
+
79
+    public function __construct($appName,
80
+                                IRequest $request,
81
+                                ILogger $logger,
82
+                                IUserManager $userManager,
83
+                                IGroupManager $groupManager,
84
+                                IURLGenerator $urlGenerator,
85
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
86
+                                Config $config,
87
+                                ICloudFederationFactory $factory,
88
+                                ICloudIdManager $cloudIdManager
89
+    ) {
90
+        parent::__construct($appName, $request);
91
+
92
+        $this->logger = $logger;
93
+        $this->userManager = $userManager;
94
+        $this->groupManager = $groupManager;
95
+        $this->urlGenerator = $urlGenerator;
96
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
97
+        $this->config = $config;
98
+        $this->factory = $factory;
99
+        $this->cloudIdManager = $cloudIdManager;
100
+    }
101
+
102
+    /**
103
+     * add share
104
+     *
105
+     * @NoCSRFRequired
106
+     * @PublicPage
107
+     * @BruteForceProtection(action=receiveFederatedShare)
108
+     *
109
+     * @param string $shareWith
110
+     * @param string $name resource name (e.g. document.odt)
111
+     * @param string $description share description (optional)
112
+     * @param string $providerId resource UID on the provider side
113
+     * @param string $owner provider specific UID of the user who owns the resource
114
+     * @param string $ownerDisplayName display name of the user who shared the item
115
+     * @param string $sharedBy provider specific UID of the user who shared the resource
116
+     * @param string $sharedByDisplayName display name of the user who shared the resource
117
+     * @param array $protocol (e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]])
118
+     * @param string $shareType ('group' or 'user' share)
119
+     * @param $resourceType ('file', 'calendar',...)
120
+     * @return Http\DataResponse|JSONResponse
121
+     *
122
+     * Example: curl -H "Content-Type: application/json" -X POST -d '{"shareWith":"admin1@serve1","name":"welcome server2.txt","description":"desc","providerId":"2","owner":"admin2@http://localhost/server2","ownerDisplayName":"admin2 display","shareType":"user","resourceType":"file","protocol":{"name":"webdav","options":{"sharedSecret":"secret","permissions":"webdav-property"}}}' http://localhost/server/index.php/ocm/shares
123
+     */
124
+    public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
125
+
126
+        // check if all required parameters are set
127
+        if ($shareWith === null ||
128
+            $name === null ||
129
+            $providerId === null ||
130
+            $owner === null ||
131
+            $resourceType === null ||
132
+            $shareType === null ||
133
+            !is_array($protocol) ||
134
+            !isset($protocol['name']) ||
135
+            !isset ($protocol['options']) ||
136
+            !is_array($protocol['options']) ||
137
+            !isset($protocol['options']['sharedSecret'])
138
+        ) {
139
+            return new JSONResponse(
140
+                ['message' => 'Missing arguments'],
141
+                Http::STATUS_BAD_REQUEST
142
+            );
143
+        }
144
+
145
+        $supportedShareTypes = $this->config->getSupportedShareTypes($resourceType);
146
+        if (!in_array($shareType, $supportedShareTypes)) {
147
+            return new JSONResponse(
148
+                ['message' => 'Share type "' . $shareType . '" not implemented'],
149
+                Http::STATUS_NOT_IMPLEMENTED
150
+            );
151
+        }
152
+
153
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
154
+        $shareWith = $cloudId->getUser();
155
+
156
+        if ($shareType === 'user') {
157
+            $shareWith = $this->mapUid($shareWith);
158
+
159
+            if (!$this->userManager->userExists($shareWith)) {
160
+                return new JSONResponse(
161
+                    ['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
162
+                    Http::STATUS_BAD_REQUEST
163
+                );
164
+            }
165
+        }
166
+
167
+        if ($shareType === 'group') {
168
+            if(!$this->groupManager->groupExists($shareWith)) {
169
+                return new JSONResponse(
170
+                    ['message' => 'Group "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
171
+                    Http::STATUS_BAD_REQUEST
172
+                );
173
+            }
174
+        }
175
+
176
+        // if no explicit display name is given, we use the uid as display name
177
+        $ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
178
+        $sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
179
+
180
+        // sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
181
+        if ($sharedBy === null) {
182
+            $sharedBy = $owner;
183
+            $sharedByDisplayName = $ownerDisplayName;
184
+        }
185
+
186
+        try {
187
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
188
+            $share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, '', $shareType, $resourceType);
189
+            $share->setProtocol($protocol);
190
+            $provider->shareReceived($share);
191
+        } catch (ProviderDoesNotExistsException $e) {
192
+            return new JSONResponse(
193
+                ['message' => $e->getMessage()],
194
+                Http::STATUS_NOT_IMPLEMENTED
195
+            );
196
+        } catch (ProviderCouldNotAddShareException $e) {
197
+            return new JSONResponse(
198
+                ['message' => $e->getMessage()],
199
+                $e->getCode()
200
+            );
201
+        } catch (\Exception $e) {
202
+            return new JSONResponse(
203
+                ['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
204
+                Http::STATUS_BAD_REQUEST
205
+            );
206
+        }
207
+
208
+        $user = $this->userManager->get($shareWith);
209
+        $recipientDisplayName = '';
210
+        if($user) {
211
+            $recipientDisplayName = $user->getDisplayName();
212
+        }
213
+
214
+        return new JSONResponse(
215
+            ['recipientDisplayName' => $recipientDisplayName],
216
+            Http::STATUS_CREATED);
217
+
218
+    }
219
+
220
+    /**
221
+     * receive notification about existing share
222
+     *
223
+     * @NoCSRFRequired
224
+     * @PublicPage
225
+     * @BruteForceProtection(action=receiveFederatedShareNotification)
226
+     *
227
+     * @param string $notificationType (notification type, e.g. SHARE_ACCEPTED)
228
+     * @param string $resourceType (calendar, file, contact,...)
229
+     * @param string $providerId id of the share
230
+     * @param array $notification the actual payload of the notification
231
+     * @return JSONResponse
232
+     */
233
+    public function receiveNotification($notificationType, $resourceType, $providerId, array $notification) {
234
+
235
+        // check if all required parameters are set
236
+        if ($notificationType === null ||
237
+            $resourceType === null ||
238
+            $providerId === null ||
239
+            !is_array($notification)
240
+        ) {
241
+            return new JSONResponse(
242
+                ['message' => 'Missing arguments'],
243
+                Http::STATUS_BAD_REQUEST
244
+            );
245
+        }
246
+
247
+        try {
248
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
249
+            $result = $provider->notificationReceived($notificationType, $providerId, $notification);
250
+        } catch (ProviderDoesNotExistsException $e) {
251
+            return new JSONResponse(
252
+                ['message' => $e->getMessage()],
253
+                Http::STATUS_BAD_REQUEST
254
+            );
255
+        } catch (ShareNotFound $e) {
256
+            return new JSONResponse(
257
+                ['message' => $e->getMessage()],
258
+                Http::STATUS_BAD_REQUEST
259
+            );
260
+        } catch (ActionNotSupportedException $e) {
261
+            return new JSONResponse(
262
+                ['message' => $e->getMessage()],
263
+                Http::STATUS_NOT_IMPLEMENTED
264
+            );
265
+        } catch (BadRequestException $e) {
266
+            return new JSONResponse($e->getReturnMessage(), Http::STATUS_BAD_REQUEST);
267
+        } catch (AuthenticationFailedException $e) {
268
+            return new JSONResponse(["message" => "RESOURCE_NOT_FOUND"], Http::STATUS_FORBIDDEN);
269
+        }
270
+        catch (\Exception $e) {
271
+            return new JSONResponse(
272
+                ['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
273
+                Http::STATUS_BAD_REQUEST
274
+            );
275
+        }
276
+
277
+        return new JSONResponse($result,Http::STATUS_CREATED);
278
+
279
+    }
280
+
281
+    /**
282
+     * map login name to internal LDAP UID if a LDAP backend is in use
283
+     *
284
+     * @param string $uid
285
+     * @return string mixed
286
+     */
287
+    private function mapUid($uid) {
288
+        // FIXME this should be a method in the user management instead
289
+        $this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
290
+        \OCP\Util::emitHook(
291
+            '\OCA\Files_Sharing\API\Server2Server',
292
+            'preLoginNameUsedAsUserName',
293
+            ['uid' => &$uid]
294
+        );
295
+        $this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
296
+
297
+        return $uid;
298
+    }
299 299
 
300 300
 }
Please login to merge, or discard this patch.
apps/files_versions/lib/Storage.php 1 patch
Indentation   +796 added lines, -796 removed lines patch added patch discarded remove patch
@@ -58,801 +58,801 @@
 block discarded – undo
58 58
 
59 59
 class Storage {
60 60
 
61
-	const DEFAULTENABLED=true;
62
-	const DEFAULTMAXSIZE=50; // unit: percentage; 50% of available disk space/quota
63
-	const VERSIONS_ROOT = 'files_versions/';
64
-
65
-	const DELETE_TRIGGER_MASTER_REMOVED = 0;
66
-	const DELETE_TRIGGER_RETENTION_CONSTRAINT = 1;
67
-	const DELETE_TRIGGER_QUOTA_EXCEEDED = 2;
68
-
69
-	// files for which we can remove the versions after the delete operation was successful
70
-	private static $deletedFiles = [];
71
-
72
-	private static $sourcePathAndUser = [];
73
-
74
-	private static $max_versions_per_interval = [
75
-		//first 10sec, one version every 2sec
76
-		1 => ['intervalEndsAfter' => 10,      'step' => 2],
77
-		//next minute, one version every 10sec
78
-		2 => ['intervalEndsAfter' => 60,      'step' => 10],
79
-		//next hour, one version every minute
80
-		3 => ['intervalEndsAfter' => 3600,    'step' => 60],
81
-		//next 24h, one version every hour
82
-		4 => ['intervalEndsAfter' => 86400,   'step' => 3600],
83
-		//next 30days, one version per day
84
-		5 => ['intervalEndsAfter' => 2592000, 'step' => 86400],
85
-		//until the end one version per week
86
-		6 => ['intervalEndsAfter' => -1,      'step' => 604800],
87
-	];
88
-
89
-	/** @var \OCA\Files_Versions\AppInfo\Application */
90
-	private static $application;
91
-
92
-	/**
93
-	 * get the UID of the owner of the file and the path to the file relative to
94
-	 * owners files folder
95
-	 *
96
-	 * @param string $filename
97
-	 * @return array
98
-	 * @throws \OC\User\NoUserException
99
-	 */
100
-	public static function getUidAndFilename($filename) {
101
-		$uid = Filesystem::getOwner($filename);
102
-		$userManager = \OC::$server->getUserManager();
103
-		// if the user with the UID doesn't exists, e.g. because the UID points
104
-		// to a remote user with a federated cloud ID we use the current logged-in
105
-		// user. We need a valid local user to create the versions
106
-		if (!$userManager->userExists($uid)) {
107
-			$uid = User::getUser();
108
-		}
109
-		Filesystem::initMountPoints($uid);
110
-		if ( $uid !== User::getUser() ) {
111
-			$info = Filesystem::getFileInfo($filename);
112
-			$ownerView = new View('/'.$uid.'/files');
113
-			try {
114
-				$filename = $ownerView->getPath($info['fileid']);
115
-				// make sure that the file name doesn't end with a trailing slash
116
-				// can for example happen single files shared across servers
117
-				$filename = rtrim($filename, '/');
118
-			} catch (NotFoundException $e) {
119
-				$filename = null;
120
-			}
121
-		}
122
-		return [$uid, $filename];
123
-	}
124
-
125
-	/**
126
-	 * Remember the owner and the owner path of the source file
127
-	 *
128
-	 * @param string $source source path
129
-	 */
130
-	public static function setSourcePathAndUser($source) {
131
-		list($uid, $path) = self::getUidAndFilename($source);
132
-		self::$sourcePathAndUser[$source] = ['uid' => $uid, 'path' => $path];
133
-	}
134
-
135
-	/**
136
-	 * Gets the owner and the owner path from the source path
137
-	 *
138
-	 * @param string $source source path
139
-	 * @return array with user id and path
140
-	 */
141
-	public static function getSourcePathAndUser($source) {
142
-
143
-		if (isset(self::$sourcePathAndUser[$source])) {
144
-			$uid = self::$sourcePathAndUser[$source]['uid'];
145
-			$path = self::$sourcePathAndUser[$source]['path'];
146
-			unset(self::$sourcePathAndUser[$source]);
147
-		} else {
148
-			$uid = $path = false;
149
-		}
150
-		return [$uid, $path];
151
-	}
152
-
153
-	/**
154
-	 * get current size of all versions from a given user
155
-	 *
156
-	 * @param string $user user who owns the versions
157
-	 * @return int versions size
158
-	 */
159
-	private static function getVersionsSize($user) {
160
-		$view = new View('/' . $user);
161
-		$fileInfo = $view->getFileInfo('/files_versions');
162
-		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
163
-	}
164
-
165
-	/**
166
-	 * store a new version of a file.
167
-	 */
168
-	public static function store($filename) {
169
-
170
-		// if the file gets streamed we need to remove the .part extension
171
-		// to get the right target
172
-		$ext = pathinfo($filename, PATHINFO_EXTENSION);
173
-		if ($ext === 'part') {
174
-			$filename = substr($filename, 0, -5);
175
-		}
176
-
177
-		// we only handle existing files
178
-		if (! Filesystem::file_exists($filename) || Filesystem::is_dir($filename)) {
179
-			return false;
180
-		}
181
-
182
-		list($uid, $filename) = self::getUidAndFilename($filename);
183
-
184
-		$files_view = new View('/'.$uid .'/files');
185
-
186
-		$eventDispatcher = \OC::$server->getEventDispatcher();
187
-		$fileInfo = $files_view->getFileInfo($filename);
188
-		$id = $fileInfo->getId();
189
-		$nodes = \OC::$server->getRootFolder()->getUserFolder($uid)->getById($id);
190
-		foreach ($nodes as $node) {
191
-			$event = new CreateVersionEvent($node);
192
-			$eventDispatcher->dispatch('OCA\Files_Versions::createVersion', $event);
193
-			if ($event->shouldCreateVersion() === false) {
194
-				return false;
195
-			}
196
-		}
197
-
198
-		// no use making versions for empty files
199
-		if ($fileInfo->getSize() === 0) {
200
-			return false;
201
-		}
202
-
203
-		/** @var IVersionManager $versionManager */
204
-		$versionManager = \OC::$server->query(IVersionManager::class);
205
-		$userManager = \OC::$server->getUserManager();
206
-		$user = $userManager->get($uid);
207
-
208
-		$versionManager->createVersion($user, $fileInfo);
209
-	}
210
-
211
-
212
-	/**
213
-	 * mark file as deleted so that we can remove the versions if the file is gone
214
-	 * @param string $path
215
-	 */
216
-	public static function markDeletedFile($path) {
217
-		list($uid, $filename) = self::getUidAndFilename($path);
218
-		self::$deletedFiles[$path] = [
219
-			'uid' => $uid,
220
-			'filename' => $filename];
221
-	}
222
-
223
-	/**
224
-	 * delete the version from the storage and cache
225
-	 *
226
-	 * @param View $view
227
-	 * @param string $path
228
-	 */
229
-	protected static function deleteVersion($view, $path) {
230
-		$view->unlink($path);
231
-		/**
232
-		 * @var \OC\Files\Storage\Storage $storage
233
-		 * @var string $internalPath
234
-		 */
235
-		list($storage, $internalPath) = $view->resolvePath($path);
236
-		$cache = $storage->getCache($internalPath);
237
-		$cache->remove($internalPath);
238
-	}
239
-
240
-	/**
241
-	 * Delete versions of a file
242
-	 */
243
-	public static function delete($path) {
244
-
245
-		$deletedFile = self::$deletedFiles[$path];
246
-		$uid = $deletedFile['uid'];
247
-		$filename = $deletedFile['filename'];
248
-
249
-		if (!Filesystem::file_exists($path)) {
250
-
251
-			$view = new View('/' . $uid . '/files_versions');
252
-
253
-			$versions = self::getVersions($uid, $filename);
254
-			if (!empty($versions)) {
255
-				foreach ($versions as $v) {
256
-					\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
257
-					self::deleteVersion($view, $filename . '.v' . $v['version']);
258
-					\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
259
-				}
260
-			}
261
-		}
262
-		unset(self::$deletedFiles[$path]);
263
-	}
264
-
265
-	/**
266
-	 * Rename or copy versions of a file of the given paths
267
-	 *
268
-	 * @param string $sourcePath source path of the file to move, relative to
269
-	 * the currently logged in user's "files" folder
270
-	 * @param string $targetPath target path of the file to move, relative to
271
-	 * the currently logged in user's "files" folder
272
-	 * @param string $operation can be 'copy' or 'rename'
273
-	 */
274
-	public static function renameOrCopy($sourcePath, $targetPath, $operation) {
275
-		list($sourceOwner, $sourcePath) = self::getSourcePathAndUser($sourcePath);
276
-
277
-		// it was a upload of a existing file if no old path exists
278
-		// in this case the pre-hook already called the store method and we can
279
-		// stop here
280
-		if ($sourcePath === false) {
281
-			return true;
282
-		}
283
-
284
-		list($targetOwner, $targetPath) = self::getUidAndFilename($targetPath);
285
-
286
-		$sourcePath = ltrim($sourcePath, '/');
287
-		$targetPath = ltrim($targetPath, '/');
288
-
289
-		$rootView = new View('');
290
-
291
-		// did we move a directory ?
292
-		if ($rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
293
-			// does the directory exists for versions too ?
294
-			if ($rootView->is_dir('/' . $sourceOwner . '/files_versions/' . $sourcePath)) {
295
-				// create missing dirs if necessary
296
-				self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
297
-
298
-				// move the directory containing the versions
299
-				$rootView->$operation(
300
-					'/' . $sourceOwner . '/files_versions/' . $sourcePath,
301
-					'/' . $targetOwner . '/files_versions/' . $targetPath
302
-				);
303
-			}
304
-		} else if ($versions = Storage::getVersions($sourceOwner, '/' . $sourcePath)) {
305
-			// create missing dirs if necessary
306
-			self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
307
-
308
-			foreach ($versions as $v) {
309
-				// move each version one by one to the target directory
310
-				$rootView->$operation(
311
-					'/' . $sourceOwner . '/files_versions/' . $sourcePath.'.v' . $v['version'],
312
-					'/' . $targetOwner . '/files_versions/' . $targetPath.'.v'.$v['version']
313
-				);
314
-			}
315
-		}
316
-
317
-		// if we moved versions directly for a file, schedule expiration check for that file
318
-		if (!$rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
319
-			self::scheduleExpire($targetOwner, $targetPath);
320
-		}
321
-
322
-	}
323
-
324
-	/**
325
-	 * Rollback to an old version of a file.
326
-	 *
327
-	 * @param string $file file name
328
-	 * @param int $revision revision timestamp
329
-	 * @return bool
330
-	 */
331
-	public static function rollback(string $file, int $revision, IUser $user) {
332
-
333
-		// add expected leading slash
334
-		$filename = '/' . ltrim($file, '/');
335
-
336
-		// Fetch the userfolder to trigger view hooks
337
-		$userFolder = \OC::$server->getUserFolder($user->getUID());
338
-
339
-		$users_view = new View('/'.$user->getUID());
340
-		$files_view = new View('/'. $user->getUID().'/files');
341
-
342
-		$versionCreated = false;
343
-
344
-		$fileInfo = $files_view->getFileInfo($file);
345
-
346
-		// check if user has the permissions to revert a version
347
-		if (!$fileInfo->isUpdateable()) {
348
-			return false;
349
-		}
350
-
351
-		//first create a new version
352
-		$version = 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename);
353
-		if (!$users_view->file_exists($version)) {
354
-			$users_view->copy('files'.$filename, 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename));
355
-			$versionCreated = true;
356
-		}
357
-
358
-		$fileToRestore =  'files_versions' . $filename . '.v' . $revision;
359
-
360
-		// Restore encrypted version of the old file for the newly restored file
361
-		// This has to happen manually here since the file is manually copied below
362
-		$oldVersion = $users_view->getFileInfo($fileToRestore)->getEncryptedVersion();
363
-		$oldFileInfo = $users_view->getFileInfo($fileToRestore);
364
-		$cache = $fileInfo->getStorage()->getCache();
365
-		$cache->update(
366
-			$fileInfo->getId(), [
367
-				'encrypted' => $oldVersion,
368
-				'encryptedVersion' => $oldVersion,
369
-				'size' => $oldFileInfo->getSize()
370
-			]
371
-		);
372
-
373
-		// rollback
374
-		if (self::copyFileContents($users_view, $fileToRestore, 'files' . $filename)) {
375
-			$files_view->touch($file, $revision);
376
-			Storage::scheduleExpire($user->getUID(), $file);
377
-
378
-			$node = $userFolder->get($file);
379
-
380
-			// TODO: move away from those legacy hooks!
381
-			\OC_Hook::emit('\OCP\Versions', 'rollback', [
382
-				'path' => $filename,
383
-				'revision' => $revision,
384
-				'node' => $node,
385
-			]);
386
-			return true;
387
-		} else if ($versionCreated) {
388
-			self::deleteVersion($users_view, $version);
389
-		}
390
-
391
-		return false;
392
-
393
-	}
394
-
395
-	/**
396
-	 * Stream copy file contents from $path1 to $path2
397
-	 *
398
-	 * @param View $view view to use for copying
399
-	 * @param string $path1 source file to copy
400
-	 * @param string $path2 target file
401
-	 *
402
-	 * @return bool true for success, false otherwise
403
-	 */
404
-	private static function copyFileContents($view, $path1, $path2) {
405
-		/** @var \OC\Files\Storage\Storage $storage1 */
406
-		list($storage1, $internalPath1) = $view->resolvePath($path1);
407
-		/** @var \OC\Files\Storage\Storage $storage2 */
408
-		list($storage2, $internalPath2) = $view->resolvePath($path2);
409
-
410
-		$view->lockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
411
-		$view->lockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
412
-
413
-		// TODO add a proper way of overwriting a file while maintaining file ids
414
-		if ($storage1->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage') || $storage2->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage')) {
415
-			$source = $storage1->fopen($internalPath1, 'r');
416
-			$target = $storage2->fopen($internalPath2, 'w');
417
-			list(, $result) = \OC_Helper::streamCopy($source, $target);
418
-			fclose($source);
419
-			fclose($target);
420
-
421
-			if ($result !== false) {
422
-				$storage1->unlink($internalPath1);
423
-			}
424
-		} else {
425
-			$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
426
-		}
427
-
428
-		$view->unlockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
429
-		$view->unlockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
430
-
431
-		return ($result !== false);
432
-	}
433
-
434
-	/**
435
-	 * get a list of all available versions of a file in descending chronological order
436
-	 * @param string $uid user id from the owner of the file
437
-	 * @param string $filename file to find versions of, relative to the user files dir
438
-	 * @param string $userFullPath
439
-	 * @return array versions newest version first
440
-	 */
441
-	public static function getVersions($uid, $filename, $userFullPath = '') {
442
-		$versions = [];
443
-		if (empty($filename)) {
444
-			return $versions;
445
-		}
446
-		// fetch for old versions
447
-		$view = new View('/' . $uid . '/');
448
-
449
-		$pathinfo = pathinfo($filename);
450
-		$versionedFile = $pathinfo['basename'];
451
-
452
-		$dir = Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
453
-
454
-		$dirContent = false;
455
-		if ($view->is_dir($dir)) {
456
-			$dirContent = $view->opendir($dir);
457
-		}
458
-
459
-		if ($dirContent === false) {
460
-			return $versions;
461
-		}
462
-
463
-		if (is_resource($dirContent)) {
464
-			while (($entryName = readdir($dirContent)) !== false) {
465
-				if (!Filesystem::isIgnoredDir($entryName)) {
466
-					$pathparts = pathinfo($entryName);
467
-					$filename = $pathparts['filename'];
468
-					if ($filename === $versionedFile) {
469
-						$pathparts = pathinfo($entryName);
470
-						$timestamp = substr($pathparts['extension'], 1);
471
-						$filename = $pathparts['filename'];
472
-						$key = $timestamp . '#' . $filename;
473
-						$versions[$key]['version'] = $timestamp;
474
-						$versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp($timestamp);
475
-						if (empty($userFullPath)) {
476
-							$versions[$key]['preview'] = '';
477
-						} else {
478
-							$versions[$key]['preview'] = \OC::$server->getURLGenerator('files_version.Preview.getPreview', ['file' => $userFullPath, 'version' => $timestamp]);
479
-						}
480
-						$versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
481
-						$versions[$key]['name'] = $versionedFile;
482
-						$versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
483
-						$versions[$key]['mimetype'] = \OC::$server->getMimeTypeDetector()->detectPath($versionedFile);
484
-					}
485
-				}
486
-			}
487
-			closedir($dirContent);
488
-		}
489
-
490
-		// sort with newest version first
491
-		krsort($versions);
492
-
493
-		return $versions;
494
-	}
495
-
496
-	/**
497
-	 * Expire versions that older than max version retention time
498
-	 * @param string $uid
499
-	 */
500
-	public static function expireOlderThanMaxForUser($uid){
501
-		$expiration = self::getExpiration();
502
-		$threshold = $expiration->getMaxAgeAsTimestamp();
503
-		$versions = self::getAllVersions($uid);
504
-		if (!$threshold || !array_key_exists('all', $versions)) {
505
-			return;
506
-		}
507
-
508
-		$toDelete = [];
509
-		foreach (array_reverse($versions['all']) as $key => $version) {
510
-			if ((int)$version['version'] <$threshold) {
511
-				$toDelete[$key] = $version;
512
-			} else {
513
-				//Versions are sorted by time - nothing mo to iterate.
514
-				break;
515
-			}
516
-		}
517
-
518
-		$view = new View('/' . $uid . '/files_versions');
519
-		if (!empty($toDelete)) {
520
-			foreach ($toDelete as $version) {
521
-				\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
522
-				self::deleteVersion($view, $version['path'] . '.v' . $version['version']);
523
-				\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
524
-			}
525
-		}
526
-	}
527
-
528
-	/**
529
-	 * translate a timestamp into a string like "5 days ago"
530
-	 * @param int $timestamp
531
-	 * @return string for example "5 days ago"
532
-	 */
533
-	private static function getHumanReadableTimestamp($timestamp) {
534
-
535
-		$diff = time() - $timestamp;
536
-
537
-		if ($diff < 60) { // first minute
538
-			return  $diff . " seconds ago";
539
-		} elseif ($diff < 3600) { //first hour
540
-			return round($diff / 60) . " minutes ago";
541
-		} elseif ($diff < 86400) { // first day
542
-			return round($diff / 3600) . " hours ago";
543
-		} elseif ($diff < 604800) { //first week
544
-			return round($diff / 86400) . " days ago";
545
-		} elseif ($diff < 2419200) { //first month
546
-			return round($diff / 604800) . " weeks ago";
547
-		} elseif ($diff < 29030400) { // first year
548
-			return round($diff / 2419200) . " months ago";
549
-		} else {
550
-			return round($diff / 29030400) . " years ago";
551
-		}
552
-
553
-	}
554
-
555
-	/**
556
-	 * returns all stored file versions from a given user
557
-	 * @param string $uid id of the user
558
-	 * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
559
-	 */
560
-	private static function getAllVersions($uid) {
561
-		$view = new View('/' . $uid . '/');
562
-		$dirs = [self::VERSIONS_ROOT];
563
-		$versions = [];
564
-
565
-		while (!empty($dirs)) {
566
-			$dir = array_pop($dirs);
567
-			$files = $view->getDirectoryContent($dir);
568
-
569
-			foreach ($files as $file) {
570
-				$fileData = $file->getData();
571
-				$filePath = $dir . '/' . $fileData['name'];
572
-				if ($file['type'] === 'dir') {
573
-					$dirs[] = $filePath;
574
-				} else {
575
-					$versionsBegin = strrpos($filePath, '.v');
576
-					$relPathStart = strlen(self::VERSIONS_ROOT);
577
-					$version = substr($filePath, $versionsBegin + 2);
578
-					$relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
579
-					$key = $version . '#' . $relpath;
580
-					$versions[$key] = ['path' => $relpath, 'timestamp' => $version];
581
-				}
582
-			}
583
-		}
584
-
585
-		// newest version first
586
-		krsort($versions);
587
-
588
-		$result = [];
589
-
590
-		foreach ($versions as $key => $value) {
591
-			$size = $view->filesize(self::VERSIONS_ROOT.'/'.$value['path'].'.v'.$value['timestamp']);
592
-			$filename = $value['path'];
593
-
594
-			$result['all'][$key]['version'] = $value['timestamp'];
595
-			$result['all'][$key]['path'] = $filename;
596
-			$result['all'][$key]['size'] = $size;
597
-
598
-			$result['by_file'][$filename][$key]['version'] = $value['timestamp'];
599
-			$result['by_file'][$filename][$key]['path'] = $filename;
600
-			$result['by_file'][$filename][$key]['size'] = $size;
601
-		}
602
-
603
-		return $result;
604
-	}
605
-
606
-	/**
607
-	 * get list of files we want to expire
608
-	 * @param array $versions list of versions
609
-	 * @param integer $time
610
-	 * @param bool $quotaExceeded is versions storage limit reached
611
-	 * @return array containing the list of to deleted versions and the size of them
612
-	 */
613
-	protected static function getExpireList($time, $versions, $quotaExceeded = false) {
614
-		$expiration = self::getExpiration();
615
-
616
-		if ($expiration->shouldAutoExpire()) {
617
-			list($toDelete, $size) = self::getAutoExpireList($time, $versions);
618
-		} else {
619
-			$size = 0;
620
-			$toDelete = [];  // versions we want to delete
621
-		}
622
-
623
-		foreach ($versions as $key => $version) {
624
-			if ($expiration->isExpired($version['version'], $quotaExceeded) && !isset($toDelete[$key])) {
625
-				$size += $version['size'];
626
-				$toDelete[$key] = $version['path'] . '.v' . $version['version'];
627
-			}
628
-		}
629
-
630
-		return [$toDelete, $size];
631
-	}
632
-
633
-	/**
634
-	 * get list of files we want to expire
635
-	 * @param array $versions list of versions
636
-	 * @param integer $time
637
-	 * @return array containing the list of to deleted versions and the size of them
638
-	 */
639
-	protected static function getAutoExpireList($time, $versions) {
640
-		$size = 0;
641
-		$toDelete = [];  // versions we want to delete
642
-
643
-		$interval = 1;
644
-		$step = Storage::$max_versions_per_interval[$interval]['step'];
645
-		if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
646
-			$nextInterval = -1;
647
-		} else {
648
-			$nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
649
-		}
650
-
651
-		$firstVersion = reset($versions);
652
-		$firstKey = key($versions);
653
-		$prevTimestamp = $firstVersion['version'];
654
-		$nextVersion = $firstVersion['version'] - $step;
655
-		unset($versions[$firstKey]);
656
-
657
-		foreach ($versions as $key => $version) {
658
-			$newInterval = true;
659
-			while ($newInterval) {
660
-				if ($nextInterval === -1 || $prevTimestamp > $nextInterval) {
661
-					if ($version['version'] > $nextVersion) {
662
-						//distance between two version too small, mark to delete
663
-						$toDelete[$key] = $version['path'] . '.v' . $version['version'];
664
-						$size += $version['size'];
665
-						\OC::$server->getLogger()->info('Mark to expire '. $version['path'] .' next version should be ' . $nextVersion . " or smaller. (prevTimestamp: " . $prevTimestamp . "; step: " . $step, ['app' => 'files_versions']);
666
-					} else {
667
-						$nextVersion = $version['version'] - $step;
668
-						$prevTimestamp = $version['version'];
669
-					}
670
-					$newInterval = false; // version checked so we can move to the next one
671
-				} else { // time to move on to the next interval
672
-					$interval++;
673
-					$step = Storage::$max_versions_per_interval[$interval]['step'];
674
-					$nextVersion = $prevTimestamp - $step;
675
-					if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
676
-						$nextInterval = -1;
677
-					} else {
678
-						$nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
679
-					}
680
-					$newInterval = true; // we changed the interval -> check same version with new interval
681
-				}
682
-			}
683
-		}
684
-
685
-		return [$toDelete, $size];
686
-	}
687
-
688
-	/**
689
-	 * Schedule versions expiration for the given file
690
-	 *
691
-	 * @param string $uid owner of the file
692
-	 * @param string $fileName file/folder for which to schedule expiration
693
-	 */
694
-	public static function scheduleExpire($uid, $fileName) {
695
-		// let the admin disable auto expire
696
-		$expiration = self::getExpiration();
697
-		if ($expiration->isEnabled()) {
698
-			$command = new Expire($uid, $fileName);
699
-			\OC::$server->getCommandBus()->push($command);
700
-		}
701
-	}
702
-
703
-	/**
704
-	 * Expire versions which exceed the quota.
705
-	 *
706
-	 * This will setup the filesystem for the given user but will not
707
-	 * tear it down afterwards.
708
-	 *
709
-	 * @param string $filename path to file to expire
710
-	 * @param string $uid user for which to expire the version
711
-	 * @return bool|int|null
712
-	 */
713
-	public static function expire($filename, $uid) {
714
-		$expiration = self::getExpiration();
715
-
716
-		if ($expiration->isEnabled()) {
717
-			// get available disk space for user
718
-			$user = \OC::$server->getUserManager()->get($uid);
719
-			if (is_null($user)) {
720
-				\OC::$server->getLogger()->error('Backends provided no user object for ' . $uid, ['app' => 'files_versions']);
721
-				throw new \OC\User\NoUserException('Backends provided no user object for ' . $uid);
722
-			}
723
-
724
-			\OC_Util::setupFS($uid);
725
-
726
-			if (!Filesystem::file_exists($filename)) {
727
-				return false;
728
-			}
729
-
730
-			if (empty($filename)) {
731
-				// file maybe renamed or deleted
732
-				return false;
733
-			}
734
-			$versionsFileview = new View('/'.$uid.'/files_versions');
735
-
736
-			$softQuota = true;
737
-			$quota = $user->getQuota();
738
-			if ( $quota === null || $quota === 'none' ) {
739
-				$quota = Filesystem::free_space('/');
740
-				$softQuota = false;
741
-			} else {
742
-				$quota = \OCP\Util::computerFileSize($quota);
743
-			}
744
-
745
-			// make sure that we have the current size of the version history
746
-			$versionsSize = self::getVersionsSize($uid);
747
-
748
-			// calculate available space for version history
749
-			// subtract size of files and current versions size from quota
750
-			if ($quota >= 0) {
751
-				if ($softQuota) {
752
-					$userFolder = \OC::$server->getUserFolder($uid);
753
-					if(is_null($userFolder)) {
754
-						$availableSpace = 0;
755
-					} else {
756
-						$free = $quota - $userFolder->getSize(false); // remaining free space for user
757
-						if ($free > 0) {
758
-							$availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
759
-						} else {
760
-							$availableSpace = $free - $versionsSize;
761
-						}
762
-					}
763
-				} else {
764
-					$availableSpace = $quota;
765
-				}
766
-			} else {
767
-				$availableSpace = PHP_INT_MAX;
768
-			}
769
-
770
-			$allVersions = Storage::getVersions($uid, $filename);
771
-
772
-			$time = time();
773
-			list($toDelete, $sizeOfDeletedVersions) = self::getExpireList($time, $allVersions, $availableSpace <= 0);
774
-
775
-			$availableSpace = $availableSpace + $sizeOfDeletedVersions;
776
-			$versionsSize = $versionsSize - $sizeOfDeletedVersions;
777
-
778
-			// if still not enough free space we rearrange the versions from all files
779
-			if ($availableSpace <= 0) {
780
-				$result = Storage::getAllVersions($uid);
781
-				$allVersions = $result['all'];
782
-
783
-				foreach ($result['by_file'] as $versions) {
784
-					list($toDeleteNew, $size) = self::getExpireList($time, $versions, $availableSpace <= 0);
785
-					$toDelete = array_merge($toDelete, $toDeleteNew);
786
-					$sizeOfDeletedVersions += $size;
787
-				}
788
-				$availableSpace = $availableSpace + $sizeOfDeletedVersions;
789
-				$versionsSize = $versionsSize - $sizeOfDeletedVersions;
790
-			}
791
-
792
-			$logger = \OC::$server->getLogger();
793
-			foreach($toDelete as $key => $path) {
794
-				\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
795
-				self::deleteVersion($versionsFileview, $path);
796
-				\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
797
-				unset($allVersions[$key]); // update array with the versions we keep
798
-				$logger->info('Expire: ' . $path, ['app' => 'files_versions']);
799
-			}
800
-
801
-			// Check if enough space is available after versions are rearranged.
802
-			// If not we delete the oldest versions until we meet the size limit for versions,
803
-			// but always keep the two latest versions
804
-			$numOfVersions = count($allVersions) -2 ;
805
-			$i = 0;
806
-			// sort oldest first and make sure that we start at the first element
807
-			ksort($allVersions);
808
-			reset($allVersions);
809
-			while ($availableSpace < 0 && $i < $numOfVersions) {
810
-				$version = current($allVersions);
811
-				\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
812
-				self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
813
-				\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
814
-				\OC::$server->getLogger()->info('running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'], ['app' => 'files_versions']);
815
-				$versionsSize -= $version['size'];
816
-				$availableSpace += $version['size'];
817
-				next($allVersions);
818
-				$i++;
819
-			}
820
-
821
-			return $versionsSize; // finally return the new size of the version history
822
-		}
823
-
824
-		return false;
825
-	}
826
-
827
-	/**
828
-	 * Create recursively missing directories inside of files_versions
829
-	 * that match the given path to a file.
830
-	 *
831
-	 * @param string $filename $path to a file, relative to the user's
832
-	 * "files" folder
833
-	 * @param View $view view on data/user/
834
-	 */
835
-	public static function createMissingDirectories($filename, $view) {
836
-		$dirname = Filesystem::normalizePath(dirname($filename));
837
-		$dirParts = explode('/', $dirname);
838
-		$dir = "/files_versions";
839
-		foreach ($dirParts as $part) {
840
-			$dir = $dir . '/' . $part;
841
-			if (!$view->file_exists($dir)) {
842
-				$view->mkdir($dir);
843
-			}
844
-		}
845
-	}
846
-
847
-	/**
848
-	 * Static workaround
849
-	 * @return Expiration
850
-	 */
851
-	protected static function getExpiration(){
852
-		if (self::$application === null) {
853
-			self::$application = \OC::$server->query(Application::class);
854
-		}
855
-		return self::$application->getContainer()->query(Expiration::class);
856
-	}
61
+    const DEFAULTENABLED=true;
62
+    const DEFAULTMAXSIZE=50; // unit: percentage; 50% of available disk space/quota
63
+    const VERSIONS_ROOT = 'files_versions/';
64
+
65
+    const DELETE_TRIGGER_MASTER_REMOVED = 0;
66
+    const DELETE_TRIGGER_RETENTION_CONSTRAINT = 1;
67
+    const DELETE_TRIGGER_QUOTA_EXCEEDED = 2;
68
+
69
+    // files for which we can remove the versions after the delete operation was successful
70
+    private static $deletedFiles = [];
71
+
72
+    private static $sourcePathAndUser = [];
73
+
74
+    private static $max_versions_per_interval = [
75
+        //first 10sec, one version every 2sec
76
+        1 => ['intervalEndsAfter' => 10,      'step' => 2],
77
+        //next minute, one version every 10sec
78
+        2 => ['intervalEndsAfter' => 60,      'step' => 10],
79
+        //next hour, one version every minute
80
+        3 => ['intervalEndsAfter' => 3600,    'step' => 60],
81
+        //next 24h, one version every hour
82
+        4 => ['intervalEndsAfter' => 86400,   'step' => 3600],
83
+        //next 30days, one version per day
84
+        5 => ['intervalEndsAfter' => 2592000, 'step' => 86400],
85
+        //until the end one version per week
86
+        6 => ['intervalEndsAfter' => -1,      'step' => 604800],
87
+    ];
88
+
89
+    /** @var \OCA\Files_Versions\AppInfo\Application */
90
+    private static $application;
91
+
92
+    /**
93
+     * get the UID of the owner of the file and the path to the file relative to
94
+     * owners files folder
95
+     *
96
+     * @param string $filename
97
+     * @return array
98
+     * @throws \OC\User\NoUserException
99
+     */
100
+    public static function getUidAndFilename($filename) {
101
+        $uid = Filesystem::getOwner($filename);
102
+        $userManager = \OC::$server->getUserManager();
103
+        // if the user with the UID doesn't exists, e.g. because the UID points
104
+        // to a remote user with a federated cloud ID we use the current logged-in
105
+        // user. We need a valid local user to create the versions
106
+        if (!$userManager->userExists($uid)) {
107
+            $uid = User::getUser();
108
+        }
109
+        Filesystem::initMountPoints($uid);
110
+        if ( $uid !== User::getUser() ) {
111
+            $info = Filesystem::getFileInfo($filename);
112
+            $ownerView = new View('/'.$uid.'/files');
113
+            try {
114
+                $filename = $ownerView->getPath($info['fileid']);
115
+                // make sure that the file name doesn't end with a trailing slash
116
+                // can for example happen single files shared across servers
117
+                $filename = rtrim($filename, '/');
118
+            } catch (NotFoundException $e) {
119
+                $filename = null;
120
+            }
121
+        }
122
+        return [$uid, $filename];
123
+    }
124
+
125
+    /**
126
+     * Remember the owner and the owner path of the source file
127
+     *
128
+     * @param string $source source path
129
+     */
130
+    public static function setSourcePathAndUser($source) {
131
+        list($uid, $path) = self::getUidAndFilename($source);
132
+        self::$sourcePathAndUser[$source] = ['uid' => $uid, 'path' => $path];
133
+    }
134
+
135
+    /**
136
+     * Gets the owner and the owner path from the source path
137
+     *
138
+     * @param string $source source path
139
+     * @return array with user id and path
140
+     */
141
+    public static function getSourcePathAndUser($source) {
142
+
143
+        if (isset(self::$sourcePathAndUser[$source])) {
144
+            $uid = self::$sourcePathAndUser[$source]['uid'];
145
+            $path = self::$sourcePathAndUser[$source]['path'];
146
+            unset(self::$sourcePathAndUser[$source]);
147
+        } else {
148
+            $uid = $path = false;
149
+        }
150
+        return [$uid, $path];
151
+    }
152
+
153
+    /**
154
+     * get current size of all versions from a given user
155
+     *
156
+     * @param string $user user who owns the versions
157
+     * @return int versions size
158
+     */
159
+    private static function getVersionsSize($user) {
160
+        $view = new View('/' . $user);
161
+        $fileInfo = $view->getFileInfo('/files_versions');
162
+        return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
163
+    }
164
+
165
+    /**
166
+     * store a new version of a file.
167
+     */
168
+    public static function store($filename) {
169
+
170
+        // if the file gets streamed we need to remove the .part extension
171
+        // to get the right target
172
+        $ext = pathinfo($filename, PATHINFO_EXTENSION);
173
+        if ($ext === 'part') {
174
+            $filename = substr($filename, 0, -5);
175
+        }
176
+
177
+        // we only handle existing files
178
+        if (! Filesystem::file_exists($filename) || Filesystem::is_dir($filename)) {
179
+            return false;
180
+        }
181
+
182
+        list($uid, $filename) = self::getUidAndFilename($filename);
183
+
184
+        $files_view = new View('/'.$uid .'/files');
185
+
186
+        $eventDispatcher = \OC::$server->getEventDispatcher();
187
+        $fileInfo = $files_view->getFileInfo($filename);
188
+        $id = $fileInfo->getId();
189
+        $nodes = \OC::$server->getRootFolder()->getUserFolder($uid)->getById($id);
190
+        foreach ($nodes as $node) {
191
+            $event = new CreateVersionEvent($node);
192
+            $eventDispatcher->dispatch('OCA\Files_Versions::createVersion', $event);
193
+            if ($event->shouldCreateVersion() === false) {
194
+                return false;
195
+            }
196
+        }
197
+
198
+        // no use making versions for empty files
199
+        if ($fileInfo->getSize() === 0) {
200
+            return false;
201
+        }
202
+
203
+        /** @var IVersionManager $versionManager */
204
+        $versionManager = \OC::$server->query(IVersionManager::class);
205
+        $userManager = \OC::$server->getUserManager();
206
+        $user = $userManager->get($uid);
207
+
208
+        $versionManager->createVersion($user, $fileInfo);
209
+    }
210
+
211
+
212
+    /**
213
+     * mark file as deleted so that we can remove the versions if the file is gone
214
+     * @param string $path
215
+     */
216
+    public static function markDeletedFile($path) {
217
+        list($uid, $filename) = self::getUidAndFilename($path);
218
+        self::$deletedFiles[$path] = [
219
+            'uid' => $uid,
220
+            'filename' => $filename];
221
+    }
222
+
223
+    /**
224
+     * delete the version from the storage and cache
225
+     *
226
+     * @param View $view
227
+     * @param string $path
228
+     */
229
+    protected static function deleteVersion($view, $path) {
230
+        $view->unlink($path);
231
+        /**
232
+         * @var \OC\Files\Storage\Storage $storage
233
+         * @var string $internalPath
234
+         */
235
+        list($storage, $internalPath) = $view->resolvePath($path);
236
+        $cache = $storage->getCache($internalPath);
237
+        $cache->remove($internalPath);
238
+    }
239
+
240
+    /**
241
+     * Delete versions of a file
242
+     */
243
+    public static function delete($path) {
244
+
245
+        $deletedFile = self::$deletedFiles[$path];
246
+        $uid = $deletedFile['uid'];
247
+        $filename = $deletedFile['filename'];
248
+
249
+        if (!Filesystem::file_exists($path)) {
250
+
251
+            $view = new View('/' . $uid . '/files_versions');
252
+
253
+            $versions = self::getVersions($uid, $filename);
254
+            if (!empty($versions)) {
255
+                foreach ($versions as $v) {
256
+                    \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
257
+                    self::deleteVersion($view, $filename . '.v' . $v['version']);
258
+                    \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
259
+                }
260
+            }
261
+        }
262
+        unset(self::$deletedFiles[$path]);
263
+    }
264
+
265
+    /**
266
+     * Rename or copy versions of a file of the given paths
267
+     *
268
+     * @param string $sourcePath source path of the file to move, relative to
269
+     * the currently logged in user's "files" folder
270
+     * @param string $targetPath target path of the file to move, relative to
271
+     * the currently logged in user's "files" folder
272
+     * @param string $operation can be 'copy' or 'rename'
273
+     */
274
+    public static function renameOrCopy($sourcePath, $targetPath, $operation) {
275
+        list($sourceOwner, $sourcePath) = self::getSourcePathAndUser($sourcePath);
276
+
277
+        // it was a upload of a existing file if no old path exists
278
+        // in this case the pre-hook already called the store method and we can
279
+        // stop here
280
+        if ($sourcePath === false) {
281
+            return true;
282
+        }
283
+
284
+        list($targetOwner, $targetPath) = self::getUidAndFilename($targetPath);
285
+
286
+        $sourcePath = ltrim($sourcePath, '/');
287
+        $targetPath = ltrim($targetPath, '/');
288
+
289
+        $rootView = new View('');
290
+
291
+        // did we move a directory ?
292
+        if ($rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
293
+            // does the directory exists for versions too ?
294
+            if ($rootView->is_dir('/' . $sourceOwner . '/files_versions/' . $sourcePath)) {
295
+                // create missing dirs if necessary
296
+                self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
297
+
298
+                // move the directory containing the versions
299
+                $rootView->$operation(
300
+                    '/' . $sourceOwner . '/files_versions/' . $sourcePath,
301
+                    '/' . $targetOwner . '/files_versions/' . $targetPath
302
+                );
303
+            }
304
+        } else if ($versions = Storage::getVersions($sourceOwner, '/' . $sourcePath)) {
305
+            // create missing dirs if necessary
306
+            self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
307
+
308
+            foreach ($versions as $v) {
309
+                // move each version one by one to the target directory
310
+                $rootView->$operation(
311
+                    '/' . $sourceOwner . '/files_versions/' . $sourcePath.'.v' . $v['version'],
312
+                    '/' . $targetOwner . '/files_versions/' . $targetPath.'.v'.$v['version']
313
+                );
314
+            }
315
+        }
316
+
317
+        // if we moved versions directly for a file, schedule expiration check for that file
318
+        if (!$rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
319
+            self::scheduleExpire($targetOwner, $targetPath);
320
+        }
321
+
322
+    }
323
+
324
+    /**
325
+     * Rollback to an old version of a file.
326
+     *
327
+     * @param string $file file name
328
+     * @param int $revision revision timestamp
329
+     * @return bool
330
+     */
331
+    public static function rollback(string $file, int $revision, IUser $user) {
332
+
333
+        // add expected leading slash
334
+        $filename = '/' . ltrim($file, '/');
335
+
336
+        // Fetch the userfolder to trigger view hooks
337
+        $userFolder = \OC::$server->getUserFolder($user->getUID());
338
+
339
+        $users_view = new View('/'.$user->getUID());
340
+        $files_view = new View('/'. $user->getUID().'/files');
341
+
342
+        $versionCreated = false;
343
+
344
+        $fileInfo = $files_view->getFileInfo($file);
345
+
346
+        // check if user has the permissions to revert a version
347
+        if (!$fileInfo->isUpdateable()) {
348
+            return false;
349
+        }
350
+
351
+        //first create a new version
352
+        $version = 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename);
353
+        if (!$users_view->file_exists($version)) {
354
+            $users_view->copy('files'.$filename, 'files_versions'.$filename.'.v'.$users_view->filemtime('files'.$filename));
355
+            $versionCreated = true;
356
+        }
357
+
358
+        $fileToRestore =  'files_versions' . $filename . '.v' . $revision;
359
+
360
+        // Restore encrypted version of the old file for the newly restored file
361
+        // This has to happen manually here since the file is manually copied below
362
+        $oldVersion = $users_view->getFileInfo($fileToRestore)->getEncryptedVersion();
363
+        $oldFileInfo = $users_view->getFileInfo($fileToRestore);
364
+        $cache = $fileInfo->getStorage()->getCache();
365
+        $cache->update(
366
+            $fileInfo->getId(), [
367
+                'encrypted' => $oldVersion,
368
+                'encryptedVersion' => $oldVersion,
369
+                'size' => $oldFileInfo->getSize()
370
+            ]
371
+        );
372
+
373
+        // rollback
374
+        if (self::copyFileContents($users_view, $fileToRestore, 'files' . $filename)) {
375
+            $files_view->touch($file, $revision);
376
+            Storage::scheduleExpire($user->getUID(), $file);
377
+
378
+            $node = $userFolder->get($file);
379
+
380
+            // TODO: move away from those legacy hooks!
381
+            \OC_Hook::emit('\OCP\Versions', 'rollback', [
382
+                'path' => $filename,
383
+                'revision' => $revision,
384
+                'node' => $node,
385
+            ]);
386
+            return true;
387
+        } else if ($versionCreated) {
388
+            self::deleteVersion($users_view, $version);
389
+        }
390
+
391
+        return false;
392
+
393
+    }
394
+
395
+    /**
396
+     * Stream copy file contents from $path1 to $path2
397
+     *
398
+     * @param View $view view to use for copying
399
+     * @param string $path1 source file to copy
400
+     * @param string $path2 target file
401
+     *
402
+     * @return bool true for success, false otherwise
403
+     */
404
+    private static function copyFileContents($view, $path1, $path2) {
405
+        /** @var \OC\Files\Storage\Storage $storage1 */
406
+        list($storage1, $internalPath1) = $view->resolvePath($path1);
407
+        /** @var \OC\Files\Storage\Storage $storage2 */
408
+        list($storage2, $internalPath2) = $view->resolvePath($path2);
409
+
410
+        $view->lockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
411
+        $view->lockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
412
+
413
+        // TODO add a proper way of overwriting a file while maintaining file ids
414
+        if ($storage1->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage') || $storage2->instanceOfStorage('\OC\Files\ObjectStore\ObjectStoreStorage')) {
415
+            $source = $storage1->fopen($internalPath1, 'r');
416
+            $target = $storage2->fopen($internalPath2, 'w');
417
+            list(, $result) = \OC_Helper::streamCopy($source, $target);
418
+            fclose($source);
419
+            fclose($target);
420
+
421
+            if ($result !== false) {
422
+                $storage1->unlink($internalPath1);
423
+            }
424
+        } else {
425
+            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
426
+        }
427
+
428
+        $view->unlockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
429
+        $view->unlockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
430
+
431
+        return ($result !== false);
432
+    }
433
+
434
+    /**
435
+     * get a list of all available versions of a file in descending chronological order
436
+     * @param string $uid user id from the owner of the file
437
+     * @param string $filename file to find versions of, relative to the user files dir
438
+     * @param string $userFullPath
439
+     * @return array versions newest version first
440
+     */
441
+    public static function getVersions($uid, $filename, $userFullPath = '') {
442
+        $versions = [];
443
+        if (empty($filename)) {
444
+            return $versions;
445
+        }
446
+        // fetch for old versions
447
+        $view = new View('/' . $uid . '/');
448
+
449
+        $pathinfo = pathinfo($filename);
450
+        $versionedFile = $pathinfo['basename'];
451
+
452
+        $dir = Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
453
+
454
+        $dirContent = false;
455
+        if ($view->is_dir($dir)) {
456
+            $dirContent = $view->opendir($dir);
457
+        }
458
+
459
+        if ($dirContent === false) {
460
+            return $versions;
461
+        }
462
+
463
+        if (is_resource($dirContent)) {
464
+            while (($entryName = readdir($dirContent)) !== false) {
465
+                if (!Filesystem::isIgnoredDir($entryName)) {
466
+                    $pathparts = pathinfo($entryName);
467
+                    $filename = $pathparts['filename'];
468
+                    if ($filename === $versionedFile) {
469
+                        $pathparts = pathinfo($entryName);
470
+                        $timestamp = substr($pathparts['extension'], 1);
471
+                        $filename = $pathparts['filename'];
472
+                        $key = $timestamp . '#' . $filename;
473
+                        $versions[$key]['version'] = $timestamp;
474
+                        $versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp($timestamp);
475
+                        if (empty($userFullPath)) {
476
+                            $versions[$key]['preview'] = '';
477
+                        } else {
478
+                            $versions[$key]['preview'] = \OC::$server->getURLGenerator('files_version.Preview.getPreview', ['file' => $userFullPath, 'version' => $timestamp]);
479
+                        }
480
+                        $versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
481
+                        $versions[$key]['name'] = $versionedFile;
482
+                        $versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
483
+                        $versions[$key]['mimetype'] = \OC::$server->getMimeTypeDetector()->detectPath($versionedFile);
484
+                    }
485
+                }
486
+            }
487
+            closedir($dirContent);
488
+        }
489
+
490
+        // sort with newest version first
491
+        krsort($versions);
492
+
493
+        return $versions;
494
+    }
495
+
496
+    /**
497
+     * Expire versions that older than max version retention time
498
+     * @param string $uid
499
+     */
500
+    public static function expireOlderThanMaxForUser($uid){
501
+        $expiration = self::getExpiration();
502
+        $threshold = $expiration->getMaxAgeAsTimestamp();
503
+        $versions = self::getAllVersions($uid);
504
+        if (!$threshold || !array_key_exists('all', $versions)) {
505
+            return;
506
+        }
507
+
508
+        $toDelete = [];
509
+        foreach (array_reverse($versions['all']) as $key => $version) {
510
+            if ((int)$version['version'] <$threshold) {
511
+                $toDelete[$key] = $version;
512
+            } else {
513
+                //Versions are sorted by time - nothing mo to iterate.
514
+                break;
515
+            }
516
+        }
517
+
518
+        $view = new View('/' . $uid . '/files_versions');
519
+        if (!empty($toDelete)) {
520
+            foreach ($toDelete as $version) {
521
+                \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
522
+                self::deleteVersion($view, $version['path'] . '.v' . $version['version']);
523
+                \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
524
+            }
525
+        }
526
+    }
527
+
528
+    /**
529
+     * translate a timestamp into a string like "5 days ago"
530
+     * @param int $timestamp
531
+     * @return string for example "5 days ago"
532
+     */
533
+    private static function getHumanReadableTimestamp($timestamp) {
534
+
535
+        $diff = time() - $timestamp;
536
+
537
+        if ($diff < 60) { // first minute
538
+            return  $diff . " seconds ago";
539
+        } elseif ($diff < 3600) { //first hour
540
+            return round($diff / 60) . " minutes ago";
541
+        } elseif ($diff < 86400) { // first day
542
+            return round($diff / 3600) . " hours ago";
543
+        } elseif ($diff < 604800) { //first week
544
+            return round($diff / 86400) . " days ago";
545
+        } elseif ($diff < 2419200) { //first month
546
+            return round($diff / 604800) . " weeks ago";
547
+        } elseif ($diff < 29030400) { // first year
548
+            return round($diff / 2419200) . " months ago";
549
+        } else {
550
+            return round($diff / 29030400) . " years ago";
551
+        }
552
+
553
+    }
554
+
555
+    /**
556
+     * returns all stored file versions from a given user
557
+     * @param string $uid id of the user
558
+     * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
559
+     */
560
+    private static function getAllVersions($uid) {
561
+        $view = new View('/' . $uid . '/');
562
+        $dirs = [self::VERSIONS_ROOT];
563
+        $versions = [];
564
+
565
+        while (!empty($dirs)) {
566
+            $dir = array_pop($dirs);
567
+            $files = $view->getDirectoryContent($dir);
568
+
569
+            foreach ($files as $file) {
570
+                $fileData = $file->getData();
571
+                $filePath = $dir . '/' . $fileData['name'];
572
+                if ($file['type'] === 'dir') {
573
+                    $dirs[] = $filePath;
574
+                } else {
575
+                    $versionsBegin = strrpos($filePath, '.v');
576
+                    $relPathStart = strlen(self::VERSIONS_ROOT);
577
+                    $version = substr($filePath, $versionsBegin + 2);
578
+                    $relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
579
+                    $key = $version . '#' . $relpath;
580
+                    $versions[$key] = ['path' => $relpath, 'timestamp' => $version];
581
+                }
582
+            }
583
+        }
584
+
585
+        // newest version first
586
+        krsort($versions);
587
+
588
+        $result = [];
589
+
590
+        foreach ($versions as $key => $value) {
591
+            $size = $view->filesize(self::VERSIONS_ROOT.'/'.$value['path'].'.v'.$value['timestamp']);
592
+            $filename = $value['path'];
593
+
594
+            $result['all'][$key]['version'] = $value['timestamp'];
595
+            $result['all'][$key]['path'] = $filename;
596
+            $result['all'][$key]['size'] = $size;
597
+
598
+            $result['by_file'][$filename][$key]['version'] = $value['timestamp'];
599
+            $result['by_file'][$filename][$key]['path'] = $filename;
600
+            $result['by_file'][$filename][$key]['size'] = $size;
601
+        }
602
+
603
+        return $result;
604
+    }
605
+
606
+    /**
607
+     * get list of files we want to expire
608
+     * @param array $versions list of versions
609
+     * @param integer $time
610
+     * @param bool $quotaExceeded is versions storage limit reached
611
+     * @return array containing the list of to deleted versions and the size of them
612
+     */
613
+    protected static function getExpireList($time, $versions, $quotaExceeded = false) {
614
+        $expiration = self::getExpiration();
615
+
616
+        if ($expiration->shouldAutoExpire()) {
617
+            list($toDelete, $size) = self::getAutoExpireList($time, $versions);
618
+        } else {
619
+            $size = 0;
620
+            $toDelete = [];  // versions we want to delete
621
+        }
622
+
623
+        foreach ($versions as $key => $version) {
624
+            if ($expiration->isExpired($version['version'], $quotaExceeded) && !isset($toDelete[$key])) {
625
+                $size += $version['size'];
626
+                $toDelete[$key] = $version['path'] . '.v' . $version['version'];
627
+            }
628
+        }
629
+
630
+        return [$toDelete, $size];
631
+    }
632
+
633
+    /**
634
+     * get list of files we want to expire
635
+     * @param array $versions list of versions
636
+     * @param integer $time
637
+     * @return array containing the list of to deleted versions and the size of them
638
+     */
639
+    protected static function getAutoExpireList($time, $versions) {
640
+        $size = 0;
641
+        $toDelete = [];  // versions we want to delete
642
+
643
+        $interval = 1;
644
+        $step = Storage::$max_versions_per_interval[$interval]['step'];
645
+        if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
646
+            $nextInterval = -1;
647
+        } else {
648
+            $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
649
+        }
650
+
651
+        $firstVersion = reset($versions);
652
+        $firstKey = key($versions);
653
+        $prevTimestamp = $firstVersion['version'];
654
+        $nextVersion = $firstVersion['version'] - $step;
655
+        unset($versions[$firstKey]);
656
+
657
+        foreach ($versions as $key => $version) {
658
+            $newInterval = true;
659
+            while ($newInterval) {
660
+                if ($nextInterval === -1 || $prevTimestamp > $nextInterval) {
661
+                    if ($version['version'] > $nextVersion) {
662
+                        //distance between two version too small, mark to delete
663
+                        $toDelete[$key] = $version['path'] . '.v' . $version['version'];
664
+                        $size += $version['size'];
665
+                        \OC::$server->getLogger()->info('Mark to expire '. $version['path'] .' next version should be ' . $nextVersion . " or smaller. (prevTimestamp: " . $prevTimestamp . "; step: " . $step, ['app' => 'files_versions']);
666
+                    } else {
667
+                        $nextVersion = $version['version'] - $step;
668
+                        $prevTimestamp = $version['version'];
669
+                    }
670
+                    $newInterval = false; // version checked so we can move to the next one
671
+                } else { // time to move on to the next interval
672
+                    $interval++;
673
+                    $step = Storage::$max_versions_per_interval[$interval]['step'];
674
+                    $nextVersion = $prevTimestamp - $step;
675
+                    if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
676
+                        $nextInterval = -1;
677
+                    } else {
678
+                        $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
679
+                    }
680
+                    $newInterval = true; // we changed the interval -> check same version with new interval
681
+                }
682
+            }
683
+        }
684
+
685
+        return [$toDelete, $size];
686
+    }
687
+
688
+    /**
689
+     * Schedule versions expiration for the given file
690
+     *
691
+     * @param string $uid owner of the file
692
+     * @param string $fileName file/folder for which to schedule expiration
693
+     */
694
+    public static function scheduleExpire($uid, $fileName) {
695
+        // let the admin disable auto expire
696
+        $expiration = self::getExpiration();
697
+        if ($expiration->isEnabled()) {
698
+            $command = new Expire($uid, $fileName);
699
+            \OC::$server->getCommandBus()->push($command);
700
+        }
701
+    }
702
+
703
+    /**
704
+     * Expire versions which exceed the quota.
705
+     *
706
+     * This will setup the filesystem for the given user but will not
707
+     * tear it down afterwards.
708
+     *
709
+     * @param string $filename path to file to expire
710
+     * @param string $uid user for which to expire the version
711
+     * @return bool|int|null
712
+     */
713
+    public static function expire($filename, $uid) {
714
+        $expiration = self::getExpiration();
715
+
716
+        if ($expiration->isEnabled()) {
717
+            // get available disk space for user
718
+            $user = \OC::$server->getUserManager()->get($uid);
719
+            if (is_null($user)) {
720
+                \OC::$server->getLogger()->error('Backends provided no user object for ' . $uid, ['app' => 'files_versions']);
721
+                throw new \OC\User\NoUserException('Backends provided no user object for ' . $uid);
722
+            }
723
+
724
+            \OC_Util::setupFS($uid);
725
+
726
+            if (!Filesystem::file_exists($filename)) {
727
+                return false;
728
+            }
729
+
730
+            if (empty($filename)) {
731
+                // file maybe renamed or deleted
732
+                return false;
733
+            }
734
+            $versionsFileview = new View('/'.$uid.'/files_versions');
735
+
736
+            $softQuota = true;
737
+            $quota = $user->getQuota();
738
+            if ( $quota === null || $quota === 'none' ) {
739
+                $quota = Filesystem::free_space('/');
740
+                $softQuota = false;
741
+            } else {
742
+                $quota = \OCP\Util::computerFileSize($quota);
743
+            }
744
+
745
+            // make sure that we have the current size of the version history
746
+            $versionsSize = self::getVersionsSize($uid);
747
+
748
+            // calculate available space for version history
749
+            // subtract size of files and current versions size from quota
750
+            if ($quota >= 0) {
751
+                if ($softQuota) {
752
+                    $userFolder = \OC::$server->getUserFolder($uid);
753
+                    if(is_null($userFolder)) {
754
+                        $availableSpace = 0;
755
+                    } else {
756
+                        $free = $quota - $userFolder->getSize(false); // remaining free space for user
757
+                        if ($free > 0) {
758
+                            $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
759
+                        } else {
760
+                            $availableSpace = $free - $versionsSize;
761
+                        }
762
+                    }
763
+                } else {
764
+                    $availableSpace = $quota;
765
+                }
766
+            } else {
767
+                $availableSpace = PHP_INT_MAX;
768
+            }
769
+
770
+            $allVersions = Storage::getVersions($uid, $filename);
771
+
772
+            $time = time();
773
+            list($toDelete, $sizeOfDeletedVersions) = self::getExpireList($time, $allVersions, $availableSpace <= 0);
774
+
775
+            $availableSpace = $availableSpace + $sizeOfDeletedVersions;
776
+            $versionsSize = $versionsSize - $sizeOfDeletedVersions;
777
+
778
+            // if still not enough free space we rearrange the versions from all files
779
+            if ($availableSpace <= 0) {
780
+                $result = Storage::getAllVersions($uid);
781
+                $allVersions = $result['all'];
782
+
783
+                foreach ($result['by_file'] as $versions) {
784
+                    list($toDeleteNew, $size) = self::getExpireList($time, $versions, $availableSpace <= 0);
785
+                    $toDelete = array_merge($toDelete, $toDeleteNew);
786
+                    $sizeOfDeletedVersions += $size;
787
+                }
788
+                $availableSpace = $availableSpace + $sizeOfDeletedVersions;
789
+                $versionsSize = $versionsSize - $sizeOfDeletedVersions;
790
+            }
791
+
792
+            $logger = \OC::$server->getLogger();
793
+            foreach($toDelete as $key => $path) {
794
+                \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
795
+                self::deleteVersion($versionsFileview, $path);
796
+                \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
797
+                unset($allVersions[$key]); // update array with the versions we keep
798
+                $logger->info('Expire: ' . $path, ['app' => 'files_versions']);
799
+            }
800
+
801
+            // Check if enough space is available after versions are rearranged.
802
+            // If not we delete the oldest versions until we meet the size limit for versions,
803
+            // but always keep the two latest versions
804
+            $numOfVersions = count($allVersions) -2 ;
805
+            $i = 0;
806
+            // sort oldest first and make sure that we start at the first element
807
+            ksort($allVersions);
808
+            reset($allVersions);
809
+            while ($availableSpace < 0 && $i < $numOfVersions) {
810
+                $version = current($allVersions);
811
+                \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
812
+                self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
813
+                \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
814
+                \OC::$server->getLogger()->info('running out of space! Delete oldest version: ' . $version['path'].'.v'.$version['version'], ['app' => 'files_versions']);
815
+                $versionsSize -= $version['size'];
816
+                $availableSpace += $version['size'];
817
+                next($allVersions);
818
+                $i++;
819
+            }
820
+
821
+            return $versionsSize; // finally return the new size of the version history
822
+        }
823
+
824
+        return false;
825
+    }
826
+
827
+    /**
828
+     * Create recursively missing directories inside of files_versions
829
+     * that match the given path to a file.
830
+     *
831
+     * @param string $filename $path to a file, relative to the user's
832
+     * "files" folder
833
+     * @param View $view view on data/user/
834
+     */
835
+    public static function createMissingDirectories($filename, $view) {
836
+        $dirname = Filesystem::normalizePath(dirname($filename));
837
+        $dirParts = explode('/', $dirname);
838
+        $dir = "/files_versions";
839
+        foreach ($dirParts as $part) {
840
+            $dir = $dir . '/' . $part;
841
+            if (!$view->file_exists($dir)) {
842
+                $view->mkdir($dir);
843
+            }
844
+        }
845
+    }
846
+
847
+    /**
848
+     * Static workaround
849
+     * @return Expiration
850
+     */
851
+    protected static function getExpiration(){
852
+        if (self::$application === null) {
853
+            self::$application = \OC::$server->query(Application::class);
854
+        }
855
+        return self::$application->getContainer()->query(Expiration::class);
856
+    }
857 857
 
858 858
 }
Please login to merge, or discard this patch.
apps/files/ajax/list.php 1 patch
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -37,72 +37,72 @@
 block discarded – undo
37 37
 $dir = \OC\Files\Filesystem::normalizePath($dir);
38 38
 
39 39
 try {
40
-	$dirInfo = \OC\Files\Filesystem::getFileInfo($dir);
41
-	if (!$dirInfo || !$dirInfo->getType() === 'dir') {
42
-		http_response_code(404);
43
-		exit();
44
-	}
40
+    $dirInfo = \OC\Files\Filesystem::getFileInfo($dir);
41
+    if (!$dirInfo || !$dirInfo->getType() === 'dir') {
42
+        http_response_code(404);
43
+        exit();
44
+    }
45 45
 
46
-	$data = [];
47
-	$baseUrl = \OC::$server->getURLGenerator()->linkTo('files', 'index.php') . '?dir=';
46
+    $data = [];
47
+    $baseUrl = \OC::$server->getURLGenerator()->linkTo('files', 'index.php') . '?dir=';
48 48
 
49
-	$permissions = $dirInfo->getPermissions();
49
+    $permissions = $dirInfo->getPermissions();
50 50
 
51
-	$sortAttribute = isset($_GET['sort']) ? (string)$_GET['sort'] : 'name';
52
-	$sortDirection = isset($_GET['sortdirection']) ? ($_GET['sortdirection'] === 'desc') : false;
53
-	$mimetypeFilters = isset($_GET['mimetypes']) ? json_decode($_GET['mimetypes']) : '';
51
+    $sortAttribute = isset($_GET['sort']) ? (string)$_GET['sort'] : 'name';
52
+    $sortDirection = isset($_GET['sortdirection']) ? ($_GET['sortdirection'] === 'desc') : false;
53
+    $mimetypeFilters = isset($_GET['mimetypes']) ? json_decode($_GET['mimetypes']) : '';
54 54
 
55
-	$files = [];
56
-	// Clean up duplicates from array
57
-	if (is_array($mimetypeFilters) && count($mimetypeFilters)) {
58
-		$mimetypeFilters = array_unique($mimetypeFilters);
55
+    $files = [];
56
+    // Clean up duplicates from array
57
+    if (is_array($mimetypeFilters) && count($mimetypeFilters)) {
58
+        $mimetypeFilters = array_unique($mimetypeFilters);
59 59
 
60
-		if (!in_array('httpd/unix-directory', $mimetypeFilters)) {
61
-			// append folder filter to be able to browse folders
62
-			$mimetypeFilters[] = 'httpd/unix-directory';
63
-		}
60
+        if (!in_array('httpd/unix-directory', $mimetypeFilters)) {
61
+            // append folder filter to be able to browse folders
62
+            $mimetypeFilters[] = 'httpd/unix-directory';
63
+        }
64 64
 
65
-		// create filelist with mimetype filter - as getFiles only supports on
66
-		// mimetype filter at once we will filter this folder for each
67
-		// mimetypeFilter
68
-		foreach ($mimetypeFilters as $mimetypeFilter) {
69
-			$files = array_merge($files, \OCA\Files\Helper::getFiles($dir, $sortAttribute, $sortDirection, $mimetypeFilter));
70
-		}
65
+        // create filelist with mimetype filter - as getFiles only supports on
66
+        // mimetype filter at once we will filter this folder for each
67
+        // mimetypeFilter
68
+        foreach ($mimetypeFilters as $mimetypeFilter) {
69
+            $files = array_merge($files, \OCA\Files\Helper::getFiles($dir, $sortAttribute, $sortDirection, $mimetypeFilter));
70
+        }
71 71
 
72
-		// sort the files accordingly
73
-		$files = \OCA\Files\Helper::sortFiles($files, $sortAttribute, $sortDirection);
74
-	} else {
75
-		// create file list without mimetype filter
76
-		$files = \OCA\Files\Helper::getFiles($dir, $sortAttribute, $sortDirection);
77
-	}
72
+        // sort the files accordingly
73
+        $files = \OCA\Files\Helper::sortFiles($files, $sortAttribute, $sortDirection);
74
+    } else {
75
+        // create file list without mimetype filter
76
+        $files = \OCA\Files\Helper::getFiles($dir, $sortAttribute, $sortDirection);
77
+    }
78 78
 
79
-	$data['directory'] = $dir;
80
-	$data['files'] = \OCA\Files\Helper::formatFileInfos($files);
81
-	$data['permissions'] = $permissions;
79
+    $data['directory'] = $dir;
80
+    $data['files'] = \OCA\Files\Helper::formatFileInfos($files);
81
+    $data['permissions'] = $permissions;
82 82
 
83
-	\OC_JSON::success(['data' => $data]);
83
+    \OC_JSON::success(['data' => $data]);
84 84
 } catch (\OCP\Files\StorageNotAvailableException $e) {
85
-	\OC::$server->getLogger()->logException($e, ['app' => 'files']);
86
-	\OC_JSON::error([
87
-		'data' => [
88
-			'exception' => StorageNotAvailableException::class,
89
-			'message' => $l->t('Storage is temporarily not available')
90
-		]
91
-	]);
85
+    \OC::$server->getLogger()->logException($e, ['app' => 'files']);
86
+    \OC_JSON::error([
87
+        'data' => [
88
+            'exception' => StorageNotAvailableException::class,
89
+            'message' => $l->t('Storage is temporarily not available')
90
+        ]
91
+    ]);
92 92
 } catch (\OCP\Files\StorageInvalidException $e) {
93
-	\OC::$server->getLogger()->logException($e, ['app' => 'files']);
94
-	\OC_JSON::error([
95
-		'data' => [
96
-			'exception' => StorageInvalidException::class,
97
-			'message' => $l->t('Storage invalid')
98
-		]
99
-	]);
93
+    \OC::$server->getLogger()->logException($e, ['app' => 'files']);
94
+    \OC_JSON::error([
95
+        'data' => [
96
+            'exception' => StorageInvalidException::class,
97
+            'message' => $l->t('Storage invalid')
98
+        ]
99
+    ]);
100 100
 } catch (\Exception $e) {
101
-	\OC::$server->getLogger()->logException($e, ['app' => 'files']);
102
-	\OC_JSON::error([
103
-		'data' => [
104
-			'exception' => \Exception::class,
105
-			'message' => $l->t('Unknown error')
106
-		]
107
-	]);
101
+    \OC::$server->getLogger()->logException($e, ['app' => 'files']);
102
+    \OC_JSON::error([
103
+        'data' => [
104
+            'exception' => \Exception::class,
105
+            'message' => $l->t('Unknown error')
106
+        ]
107
+    ]);
108 108
 }
Please login to merge, or discard this patch.
apps/files/ajax/download.php 1 patch
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
 $files_list = json_decode($files);
39 39
 // in case we get only a single file
40 40
 if (!is_array($files_list)) {
41
-	$files_list = [$files];
41
+    $files_list = [$files];
42 42
 }
43 43
 
44 44
 /**
@@ -47,9 +47,9 @@  discard block
 block discarded – undo
47 47
  * alphanumeric characters
48 48
  */
49 49
 if(isset($_GET['downloadStartSecret'])
50
-	&& !isset($_GET['downloadStartSecret'][32])
51
-	&& preg_match('!^[a-zA-Z0-9]+$!', $_GET['downloadStartSecret']) === 1) {
52
-	setcookie('ocDownloadStarted', $_GET['downloadStartSecret'], time() + 20, '/');
50
+    && !isset($_GET['downloadStartSecret'][32])
51
+    && preg_match('!^[a-zA-Z0-9]+$!', $_GET['downloadStartSecret']) === 1) {
52
+    setcookie('ocDownloadStarted', $_GET['downloadStartSecret'], time() + 20, '/');
53 53
 }
54 54
 
55 55
 $server_params = [ 'head' => \OC::$server->getRequest()->getMethod() === 'HEAD' ];
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
  * Http range requests support
59 59
  */
60 60
 if (isset($_SERVER['HTTP_RANGE'])) {
61
-	$server_params['range'] = \OC::$server->getRequest()->getHeader('Range');
61
+    $server_params['range'] = \OC::$server->getRequest()->getHeader('Range');
62 62
 }
63 63
 
64 64
 OC_Files::get($dir, $files_list, $server_params);
Please login to merge, or discard this patch.