Passed
Push — master ( 62403d...0c3e2f )
by Joas
14:50 queued 14s
created
index.php 2 patches
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.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -29,15 +29,15 @@
 block discarded – undo
29 29
  *
30 30
  */
31 31
 
32
-require_once __DIR__ . '/lib/versioncheck.php';
32
+require_once __DIR__.'/lib/versioncheck.php';
33 33
 
34 34
 try {
35 35
 
36
-	require_once __DIR__ . '/lib/base.php';
36
+	require_once __DIR__.'/lib/base.php';
37 37
 
38 38
 	OC::handleRequest();
39 39
 
40
-} catch(\OC\ServiceUnavailableException $ex) {
40
+} catch (\OC\ServiceUnavailableException $ex) {
41 41
 	\OC::$server->getLogger()->logException($ex, ['app' => 'index']);
42 42
 
43 43
 	//show the user a detailed error page
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 2 patches
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.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -35,11 +35,11 @@  discard block
 block discarded – undo
35 35
  *
36 36
  */
37 37
 
38
-require_once __DIR__ . '/lib/versioncheck.php';
38
+require_once __DIR__.'/lib/versioncheck.php';
39 39
 
40 40
 try {
41 41
 
42
-	require_once __DIR__ . '/lib/base.php';
42
+	require_once __DIR__.'/lib/base.php';
43 43
 
44 44
 	if (\OCP\Util::needUpgrade()) {
45 45
 		\OC::$server->getLogger()->debug('Update required, skipping cron', ['app' => 'cron']);
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
 	$appMode = $config->getAppValue('core', 'backgroundjobs_mode', 'ajax');
76 76
 	if ($appMode === 'none') {
77 77
 		if (OC::$CLI) {
78
-			echo 'Background Jobs are disabled!' . PHP_EOL;
78
+			echo 'Background Jobs are disabled!'.PHP_EOL;
79 79
 		} else {
80 80
 			OC_JSON::error(['data' => ['message' => 'Background jobs disabled!']]);
81 81
 		}
@@ -90,16 +90,16 @@  discard block
 block discarded – undo
90 90
 
91 91
 		// the cron job must be executed with the right user
92 92
 		if (!function_exists('posix_getuid')) {
93
-			echo "The posix extensions are required - see http://php.net/manual/en/book.posix.php" . PHP_EOL;
93
+			echo "The posix extensions are required - see http://php.net/manual/en/book.posix.php".PHP_EOL;
94 94
 			exit(1);
95 95
 		}
96 96
 
97 97
 		$user = posix_getpwuid(posix_getuid());
98
-		$configUser = posix_getpwuid(fileowner(OC::$configDir . 'config.php'));
98
+		$configUser = posix_getpwuid(fileowner(OC::$configDir.'config.php'));
99 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;
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 103
 			exit(1);
104 104
 		}
105 105
 
Please login to merge, or discard this patch.
apps/cloud_federation_api/lib/Controller/RequestHandlerController.php 2 patches
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.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 		$supportedShareTypes = $this->config->getSupportedShareTypes($resourceType);
146 146
 		if (!in_array($shareType, $supportedShareTypes)) {
147 147
 			return new JSONResponse(
148
-				['message' => 'Share type "' . $shareType . '" not implemented'],
148
+				['message' => 'Share type "'.$shareType.'" not implemented'],
149 149
 				Http::STATUS_NOT_IMPLEMENTED
150 150
 			);
151 151
 		}
@@ -158,16 +158,16 @@  discard block
 block discarded – undo
158 158
 
159 159
 			if (!$this->userManager->userExists($shareWith)) {
160 160
 				return new JSONResponse(
161
-					['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
161
+					['message' => 'User "'.$shareWith.'" does not exists at '.$this->urlGenerator->getBaseUrl()],
162 162
 					Http::STATUS_BAD_REQUEST
163 163
 				);
164 164
 			}
165 165
 		}
166 166
 
167 167
 		if ($shareType === 'group') {
168
-			if(!$this->groupManager->groupExists($shareWith)) {
168
+			if (!$this->groupManager->groupExists($shareWith)) {
169 169
 				return new JSONResponse(
170
-					['message' => 'Group "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
170
+					['message' => 'Group "'.$shareWith.'" does not exists at '.$this->urlGenerator->getBaseUrl()],
171 171
 					Http::STATUS_BAD_REQUEST
172 172
 				);
173 173
 			}
@@ -200,14 +200,14 @@  discard block
 block discarded – undo
200 200
 			);
201 201
 		} catch (\Exception $e) {
202 202
 			return new JSONResponse(
203
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
203
+				['message' => 'Internal error at '.$this->urlGenerator->getBaseUrl()],
204 204
 				Http::STATUS_BAD_REQUEST
205 205
 			);
206 206
 		}
207 207
 
208 208
 		$user = $this->userManager->get($shareWith);
209 209
 		$recipientDisplayName = '';
210
-		if($user) {
210
+		if ($user) {
211 211
 			$recipientDisplayName = $user->getDisplayName();
212 212
 		}
213 213
 
@@ -269,12 +269,12 @@  discard block
 block discarded – undo
269 269
 		}
270 270
 		catch (\Exception $e) {
271 271
 			return new JSONResponse(
272
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
272
+				['message' => 'Internal error at '.$this->urlGenerator->getBaseUrl()],
273 273
 				Http::STATUS_BAD_REQUEST
274 274
 			);
275 275
 		}
276 276
 
277
-		return new JSONResponse($result,Http::STATUS_CREATED);
277
+		return new JSONResponse($result, Http::STATUS_CREATED);
278 278
 
279 279
 	}
280 280
 
@@ -286,13 +286,13 @@  discard block
 block discarded – undo
286 286
 	 */
287 287
 	private function mapUid($uid) {
288 288
 		// FIXME this should be a method in the user management instead
289
-		$this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
289
+		$this->logger->debug('shareWith before, '.$uid, ['app' => $this->appName]);
290 290
 		\OCP\Util::emitHook(
291 291
 			'\OCA\Files_Sharing\API\Server2Server',
292 292
 			'preLoginNameUsedAsUserName',
293 293
 			['uid' => &$uid]
294 294
 		);
295
-		$this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
295
+		$this->logger->debug('shareWith after, '.$uid, ['app' => $this->appName]);
296 296
 
297 297
 		return $uid;
298 298
 	}
Please login to merge, or discard this patch.
apps/files_versions/lib/Storage.php 2 patches
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.
Spacing   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -58,8 +58,8 @@  discard block
 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
61
+	const DEFAULTENABLED = true;
62
+	const DEFAULTMAXSIZE = 50; // unit: percentage; 50% of available disk space/quota
63 63
 	const VERSIONS_ROOT = 'files_versions/';
64 64
 
65 65
 	const DELETE_TRIGGER_MASTER_REMOVED = 0;
@@ -73,17 +73,17 @@  discard block
 block discarded – undo
73 73
 
74 74
 	private static $max_versions_per_interval = [
75 75
 		//first 10sec, one version every 2sec
76
-		1 => ['intervalEndsAfter' => 10,      'step' => 2],
76
+		1 => ['intervalEndsAfter' => 10, 'step' => 2],
77 77
 		//next minute, one version every 10sec
78
-		2 => ['intervalEndsAfter' => 60,      'step' => 10],
78
+		2 => ['intervalEndsAfter' => 60, 'step' => 10],
79 79
 		//next hour, one version every minute
80
-		3 => ['intervalEndsAfter' => 3600,    'step' => 60],
80
+		3 => ['intervalEndsAfter' => 3600, 'step' => 60],
81 81
 		//next 24h, one version every hour
82
-		4 => ['intervalEndsAfter' => 86400,   'step' => 3600],
82
+		4 => ['intervalEndsAfter' => 86400, 'step' => 3600],
83 83
 		//next 30days, one version per day
84 84
 		5 => ['intervalEndsAfter' => 2592000, 'step' => 86400],
85 85
 		//until the end one version per week
86
-		6 => ['intervalEndsAfter' => -1,      'step' => 604800],
86
+		6 => ['intervalEndsAfter' => -1, 'step' => 604800],
87 87
 	];
88 88
 
89 89
 	/** @var \OCA\Files_Versions\AppInfo\Application */
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 			$uid = User::getUser();
108 108
 		}
109 109
 		Filesystem::initMountPoints($uid);
110
-		if ( $uid !== User::getUser() ) {
110
+		if ($uid !== User::getUser()) {
111 111
 			$info = Filesystem::getFileInfo($filename);
112 112
 			$ownerView = new View('/'.$uid.'/files');
113 113
 			try {
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 	 * @return int versions size
158 158
 	 */
159 159
 	private static function getVersionsSize($user) {
160
-		$view = new View('/' . $user);
160
+		$view = new View('/'.$user);
161 161
 		$fileInfo = $view->getFileInfo('/files_versions');
162 162
 		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
163 163
 	}
@@ -175,13 +175,13 @@  discard block
 block discarded – undo
175 175
 		}
176 176
 
177 177
 		// we only handle existing files
178
-		if (! Filesystem::file_exists($filename) || Filesystem::is_dir($filename)) {
178
+		if (!Filesystem::file_exists($filename) || Filesystem::is_dir($filename)) {
179 179
 			return false;
180 180
 		}
181 181
 
182 182
 		list($uid, $filename) = self::getUidAndFilename($filename);
183 183
 
184
-		$files_view = new View('/'.$uid .'/files');
184
+		$files_view = new View('/'.$uid.'/files');
185 185
 
186 186
 		$eventDispatcher = \OC::$server->getEventDispatcher();
187 187
 		$fileInfo = $files_view->getFileInfo($filename);
@@ -248,14 +248,14 @@  discard block
 block discarded – undo
248 248
 
249 249
 		if (!Filesystem::file_exists($path)) {
250 250
 
251
-			$view = new View('/' . $uid . '/files_versions');
251
+			$view = new View('/'.$uid.'/files_versions');
252 252
 
253 253
 			$versions = self::getVersions($uid, $filename);
254 254
 			if (!empty($versions)) {
255 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]);
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 259
 				}
260 260
 			}
261 261
 		}
@@ -289,33 +289,33 @@  discard block
 block discarded – undo
289 289
 		$rootView = new View('');
290 290
 
291 291
 		// did we move a directory ?
292
-		if ($rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
292
+		if ($rootView->is_dir('/'.$targetOwner.'/files/'.$targetPath)) {
293 293
 			// does the directory exists for versions too ?
294
-			if ($rootView->is_dir('/' . $sourceOwner . '/files_versions/' . $sourcePath)) {
294
+			if ($rootView->is_dir('/'.$sourceOwner.'/files_versions/'.$sourcePath)) {
295 295
 				// create missing dirs if necessary
296
-				self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
296
+				self::createMissingDirectories($targetPath, new View('/'.$targetOwner));
297 297
 
298 298
 				// move the directory containing the versions
299 299
 				$rootView->$operation(
300
-					'/' . $sourceOwner . '/files_versions/' . $sourcePath,
301
-					'/' . $targetOwner . '/files_versions/' . $targetPath
300
+					'/'.$sourceOwner.'/files_versions/'.$sourcePath,
301
+					'/'.$targetOwner.'/files_versions/'.$targetPath
302 302
 				);
303 303
 			}
304
-		} else if ($versions = Storage::getVersions($sourceOwner, '/' . $sourcePath)) {
304
+		} else if ($versions = Storage::getVersions($sourceOwner, '/'.$sourcePath)) {
305 305
 			// create missing dirs if necessary
306
-			self::createMissingDirectories($targetPath, new View('/'. $targetOwner));
306
+			self::createMissingDirectories($targetPath, new View('/'.$targetOwner));
307 307
 
308 308
 			foreach ($versions as $v) {
309 309
 				// move each version one by one to the target directory
310 310
 				$rootView->$operation(
311
-					'/' . $sourceOwner . '/files_versions/' . $sourcePath.'.v' . $v['version'],
312
-					'/' . $targetOwner . '/files_versions/' . $targetPath.'.v'.$v['version']
311
+					'/'.$sourceOwner.'/files_versions/'.$sourcePath.'.v'.$v['version'],
312
+					'/'.$targetOwner.'/files_versions/'.$targetPath.'.v'.$v['version']
313 313
 				);
314 314
 			}
315 315
 		}
316 316
 
317 317
 		// if we moved versions directly for a file, schedule expiration check for that file
318
-		if (!$rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
318
+		if (!$rootView->is_dir('/'.$targetOwner.'/files/'.$targetPath)) {
319 319
 			self::scheduleExpire($targetOwner, $targetPath);
320 320
 		}
321 321
 
@@ -331,13 +331,13 @@  discard block
 block discarded – undo
331 331
 	public static function rollback(string $file, int $revision, IUser $user) {
332 332
 
333 333
 		// add expected leading slash
334
-		$filename = '/' . ltrim($file, '/');
334
+		$filename = '/'.ltrim($file, '/');
335 335
 
336 336
 		// Fetch the userfolder to trigger view hooks
337 337
 		$userFolder = \OC::$server->getUserFolder($user->getUID());
338 338
 
339 339
 		$users_view = new View('/'.$user->getUID());
340
-		$files_view = new View('/'. $user->getUID().'/files');
340
+		$files_view = new View('/'.$user->getUID().'/files');
341 341
 
342 342
 		$versionCreated = false;
343 343
 
@@ -355,7 +355,7 @@  discard block
 block discarded – undo
355 355
 			$versionCreated = true;
356 356
 		}
357 357
 
358
-		$fileToRestore =  'files_versions' . $filename . '.v' . $revision;
358
+		$fileToRestore = 'files_versions'.$filename.'.v'.$revision;
359 359
 
360 360
 		// Restore encrypted version of the old file for the newly restored file
361 361
 		// This has to happen manually here since the file is manually copied below
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
 		);
372 372
 
373 373
 		// rollback
374
-		if (self::copyFileContents($users_view, $fileToRestore, 'files' . $filename)) {
374
+		if (self::copyFileContents($users_view, $fileToRestore, 'files'.$filename)) {
375 375
 			$files_view->touch($file, $revision);
376 376
 			Storage::scheduleExpire($user->getUID(), $file);
377 377
 
@@ -444,12 +444,12 @@  discard block
 block discarded – undo
444 444
 			return $versions;
445 445
 		}
446 446
 		// fetch for old versions
447
-		$view = new View('/' . $uid . '/');
447
+		$view = new View('/'.$uid.'/');
448 448
 
449 449
 		$pathinfo = pathinfo($filename);
450 450
 		$versionedFile = $pathinfo['basename'];
451 451
 
452
-		$dir = Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
452
+		$dir = Filesystem::normalizePath(self::VERSIONS_ROOT.'/'.$pathinfo['dirname']);
453 453
 
454 454
 		$dirContent = false;
455 455
 		if ($view->is_dir($dir)) {
@@ -469,7 +469,7 @@  discard block
 block discarded – undo
469 469
 						$pathparts = pathinfo($entryName);
470 470
 						$timestamp = substr($pathparts['extension'], 1);
471 471
 						$filename = $pathparts['filename'];
472
-						$key = $timestamp . '#' . $filename;
472
+						$key = $timestamp.'#'.$filename;
473 473
 						$versions[$key]['version'] = $timestamp;
474 474
 						$versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp($timestamp);
475 475
 						if (empty($userFullPath)) {
@@ -477,9 +477,9 @@  discard block
 block discarded – undo
477 477
 						} else {
478 478
 							$versions[$key]['preview'] = \OC::$server->getURLGenerator('files_version.Preview.getPreview', ['file' => $userFullPath, 'version' => $timestamp]);
479 479
 						}
480
-						$versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
480
+						$versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'].'/'.$filename);
481 481
 						$versions[$key]['name'] = $versionedFile;
482
-						$versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
482
+						$versions[$key]['size'] = $view->filesize($dir.'/'.$entryName);
483 483
 						$versions[$key]['mimetype'] = \OC::$server->getMimeTypeDetector()->detectPath($versionedFile);
484 484
 					}
485 485
 				}
@@ -497,7 +497,7 @@  discard block
 block discarded – undo
497 497
 	 * Expire versions that older than max version retention time
498 498
 	 * @param string $uid
499 499
 	 */
500
-	public static function expireOlderThanMaxForUser($uid){
500
+	public static function expireOlderThanMaxForUser($uid) {
501 501
 		$expiration = self::getExpiration();
502 502
 		$threshold = $expiration->getMaxAgeAsTimestamp();
503 503
 		$versions = self::getAllVersions($uid);
@@ -507,7 +507,7 @@  discard block
 block discarded – undo
507 507
 
508 508
 		$toDelete = [];
509 509
 		foreach (array_reverse($versions['all']) as $key => $version) {
510
-			if ((int)$version['version'] <$threshold) {
510
+			if ((int) $version['version'] < $threshold) {
511 511
 				$toDelete[$key] = $version;
512 512
 			} else {
513 513
 				//Versions are sorted by time - nothing mo to iterate.
@@ -515,11 +515,11 @@  discard block
 block discarded – undo
515 515
 			}
516 516
 		}
517 517
 
518
-		$view = new View('/' . $uid . '/files_versions');
518
+		$view = new View('/'.$uid.'/files_versions');
519 519
 		if (!empty($toDelete)) {
520 520
 			foreach ($toDelete as $version) {
521 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']);
522
+				self::deleteVersion($view, $version['path'].'.v'.$version['version']);
523 523
 				\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'].'.v'.$version['version'], 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
524 524
 			}
525 525
 		}
@@ -535,19 +535,19 @@  discard block
 block discarded – undo
535 535
 		$diff = time() - $timestamp;
536 536
 
537 537
 		if ($diff < 60) { // first minute
538
-			return  $diff . " seconds ago";
538
+			return  $diff." seconds ago";
539 539
 		} elseif ($diff < 3600) { //first hour
540
-			return round($diff / 60) . " minutes ago";
540
+			return round($diff / 60)." minutes ago";
541 541
 		} elseif ($diff < 86400) { // first day
542
-			return round($diff / 3600) . " hours ago";
542
+			return round($diff / 3600)." hours ago";
543 543
 		} elseif ($diff < 604800) { //first week
544
-			return round($diff / 86400) . " days ago";
544
+			return round($diff / 86400)." days ago";
545 545
 		} elseif ($diff < 2419200) { //first month
546
-			return round($diff / 604800) . " weeks ago";
546
+			return round($diff / 604800)." weeks ago";
547 547
 		} elseif ($diff < 29030400) { // first year
548
-			return round($diff / 2419200) . " months ago";
548
+			return round($diff / 2419200)." months ago";
549 549
 		} else {
550
-			return round($diff / 29030400) . " years ago";
550
+			return round($diff / 29030400)." years ago";
551 551
 		}
552 552
 
553 553
 	}
@@ -558,7 +558,7 @@  discard block
 block discarded – undo
558 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 559
 	 */
560 560
 	private static function getAllVersions($uid) {
561
-		$view = new View('/' . $uid . '/');
561
+		$view = new View('/'.$uid.'/');
562 562
 		$dirs = [self::VERSIONS_ROOT];
563 563
 		$versions = [];
564 564
 
@@ -568,7 +568,7 @@  discard block
 block discarded – undo
568 568
 
569 569
 			foreach ($files as $file) {
570 570
 				$fileData = $file->getData();
571
-				$filePath = $dir . '/' . $fileData['name'];
571
+				$filePath = $dir.'/'.$fileData['name'];
572 572
 				if ($file['type'] === 'dir') {
573 573
 					$dirs[] = $filePath;
574 574
 				} else {
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
 					$relPathStart = strlen(self::VERSIONS_ROOT);
577 577
 					$version = substr($filePath, $versionsBegin + 2);
578 578
 					$relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
579
-					$key = $version . '#' . $relpath;
579
+					$key = $version.'#'.$relpath;
580 580
 					$versions[$key] = ['path' => $relpath, 'timestamp' => $version];
581 581
 				}
582 582
 			}
@@ -617,13 +617,13 @@  discard block
 block discarded – undo
617 617
 			list($toDelete, $size) = self::getAutoExpireList($time, $versions);
618 618
 		} else {
619 619
 			$size = 0;
620
-			$toDelete = [];  // versions we want to delete
620
+			$toDelete = []; // versions we want to delete
621 621
 		}
622 622
 
623 623
 		foreach ($versions as $key => $version) {
624 624
 			if ($expiration->isExpired($version['version'], $quotaExceeded) && !isset($toDelete[$key])) {
625 625
 				$size += $version['size'];
626
-				$toDelete[$key] = $version['path'] . '.v' . $version['version'];
626
+				$toDelete[$key] = $version['path'].'.v'.$version['version'];
627 627
 			}
628 628
 		}
629 629
 
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
 	 */
639 639
 	protected static function getAutoExpireList($time, $versions) {
640 640
 		$size = 0;
641
-		$toDelete = [];  // versions we want to delete
641
+		$toDelete = []; // versions we want to delete
642 642
 
643 643
 		$interval = 1;
644 644
 		$step = Storage::$max_versions_per_interval[$interval]['step'];
@@ -660,9 +660,9 @@  discard block
 block discarded – undo
660 660
 				if ($nextInterval === -1 || $prevTimestamp > $nextInterval) {
661 661
 					if ($version['version'] > $nextVersion) {
662 662
 						//distance between two version too small, mark to delete
663
-						$toDelete[$key] = $version['path'] . '.v' . $version['version'];
663
+						$toDelete[$key] = $version['path'].'.v'.$version['version'];
664 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']);
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 666
 					} else {
667 667
 						$nextVersion = $version['version'] - $step;
668 668
 						$prevTimestamp = $version['version'];
@@ -717,8 +717,8 @@  discard block
 block discarded – undo
717 717
 			// get available disk space for user
718 718
 			$user = \OC::$server->getUserManager()->get($uid);
719 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);
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 722
 			}
723 723
 
724 724
 			\OC_Util::setupFS($uid);
@@ -735,7 +735,7 @@  discard block
 block discarded – undo
735 735
 
736 736
 			$softQuota = true;
737 737
 			$quota = $user->getQuota();
738
-			if ( $quota === null || $quota === 'none' ) {
738
+			if ($quota === null || $quota === 'none') {
739 739
 				$quota = Filesystem::free_space('/');
740 740
 				$softQuota = false;
741 741
 			} else {
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 			if ($quota >= 0) {
751 751
 				if ($softQuota) {
752 752
 					$userFolder = \OC::$server->getUserFolder($uid);
753
-					if(is_null($userFolder)) {
753
+					if (is_null($userFolder)) {
754 754
 						$availableSpace = 0;
755 755
 					} else {
756 756
 						$free = $quota - $userFolder->getSize(false); // remaining free space for user
@@ -790,18 +790,18 @@  discard block
 block discarded – undo
790 790
 			}
791 791
 
792 792
 			$logger = \OC::$server->getLogger();
793
-			foreach($toDelete as $key => $path) {
793
+			foreach ($toDelete as $key => $path) {
794 794
 				\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
795 795
 				self::deleteVersion($versionsFileview, $path);
796 796
 				\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
797 797
 				unset($allVersions[$key]); // update array with the versions we keep
798
-				$logger->info('Expire: ' . $path, ['app' => 'files_versions']);
798
+				$logger->info('Expire: '.$path, ['app' => 'files_versions']);
799 799
 			}
800 800
 
801 801
 			// Check if enough space is available after versions are rearranged.
802 802
 			// If not we delete the oldest versions until we meet the size limit for versions,
803 803
 			// but always keep the two latest versions
804
-			$numOfVersions = count($allVersions) -2 ;
804
+			$numOfVersions = count($allVersions) - 2;
805 805
 			$i = 0;
806 806
 			// sort oldest first and make sure that we start at the first element
807 807
 			ksort($allVersions);
@@ -809,9 +809,9 @@  discard block
 block discarded – undo
809 809
 			while ($availableSpace < 0 && $i < $numOfVersions) {
810 810
 				$version = current($allVersions);
811 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']);
812
+				self::deleteVersion($versionsFileview, $version['path'].'.v'.$version['version']);
813 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']);
814
+				\OC::$server->getLogger()->info('running out of space! Delete oldest version: '.$version['path'].'.v'.$version['version'], ['app' => 'files_versions']);
815 815
 				$versionsSize -= $version['size'];
816 816
 				$availableSpace += $version['size'];
817 817
 				next($allVersions);
@@ -837,7 +837,7 @@  discard block
 block discarded – undo
837 837
 		$dirParts = explode('/', $dirname);
838 838
 		$dir = "/files_versions";
839 839
 		foreach ($dirParts as $part) {
840
-			$dir = $dir . '/' . $part;
840
+			$dir = $dir.'/'.$part;
841 841
 			if (!$view->file_exists($dir)) {
842 842
 				$view->mkdir($dir);
843 843
 			}
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
 	 * Static workaround
849 849
 	 * @return Expiration
850 850
 	 */
851
-	protected static function getExpiration(){
851
+	protected static function getExpiration() {
852 852
 		if (self::$application === null) {
853 853
 			self::$application = \OC::$server->query(Application::class);
854 854
 		}
Please login to merge, or discard this patch.
apps/files/ajax/list.php 2 patches
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.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
 $l = \OC::$server->getL10N('files');
34 34
 
35 35
 // Load the files
36
-$dir = isset($_GET['dir']) ? (string)$_GET['dir'] : '';
36
+$dir = isset($_GET['dir']) ? (string) $_GET['dir'] : '';
37 37
 $dir = \OC\Files\Filesystem::normalizePath($dir);
38 38
 
39 39
 try {
@@ -44,11 +44,11 @@  discard block
 block discarded – undo
44 44
 	}
45 45
 
46 46
 	$data = [];
47
-	$baseUrl = \OC::$server->getURLGenerator()->linkTo('files', 'index.php') . '?dir=';
47
+	$baseUrl = \OC::$server->getURLGenerator()->linkTo('files', 'index.php').'?dir=';
48 48
 
49 49
 	$permissions = $dirInfo->getPermissions();
50 50
 
51
-	$sortAttribute = isset($_GET['sort']) ? (string)$_GET['sort'] : 'name';
51
+	$sortAttribute = isset($_GET['sort']) ? (string) $_GET['sort'] : 'name';
52 52
 	$sortDirection = isset($_GET['sortdirection']) ? ($_GET['sortdirection'] === 'desc') : false;
53 53
 	$mimetypeFilters = isset($_GET['mimetypes']) ? json_decode($_GET['mimetypes']) : '';
54 54
 
Please login to merge, or discard this patch.
apps/files/ajax/download.php 2 patches
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.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -32,8 +32,8 @@  discard block
 block discarded – undo
32 32
 OCP\User::checkLoggedIn();
33 33
 \OC::$server->getSession()->close();
34 34
 
35
-$files = isset($_GET['files']) ? (string)$_GET['files'] : '';
36
-$dir = isset($_GET['dir']) ? (string)$_GET['dir'] : '';
35
+$files = isset($_GET['files']) ? (string) $_GET['files'] : '';
36
+$dir = isset($_GET['dir']) ? (string) $_GET['dir'] : '';
37 37
 
38 38
 $files_list = json_decode($files);
39 39
 // in case we get only a single file
@@ -46,13 +46,13 @@  discard block
 block discarded – undo
46 46
  * the content must not be longer than 32 characters and must only contain
47 47
  * alphanumeric characters
48 48
  */
49
-if(isset($_GET['downloadStartSecret'])
49
+if (isset($_GET['downloadStartSecret'])
50 50
 	&& !isset($_GET['downloadStartSecret'][32])
51 51
 	&& preg_match('!^[a-zA-Z0-9]+$!', $_GET['downloadStartSecret']) === 1) {
52 52
 	setcookie('ocDownloadStarted', $_GET['downloadStartSecret'], time() + 20, '/');
53 53
 }
54 54
 
55
-$server_params = [ 'head' => \OC::$server->getRequest()->getMethod() === 'HEAD' ];
55
+$server_params = ['head' => \OC::$server->getRequest()->getMethod() === 'HEAD'];
56 56
 
57 57
 /**
58 58
  * Http range requests support
Please login to merge, or discard this patch.
apps/files/lib/Command/Scan.php 2 patches
Indentation   +270 added lines, -270 removed lines patch added patch discarded remove patch
@@ -51,275 +51,275 @@
 block discarded – undo
51 51
 
52 52
 class Scan extends Base {
53 53
 
54
-	/** @var IUserManager $userManager */
55
-	private $userManager;
56
-	/** @var float */
57
-	protected $execTime = 0;
58
-	/** @var int */
59
-	protected $foldersCounter = 0;
60
-	/** @var int */
61
-	protected $filesCounter = 0;
62
-
63
-	public function __construct(IUserManager $userManager) {
64
-		$this->userManager = $userManager;
65
-		parent::__construct();
66
-	}
67
-
68
-	protected function configure() {
69
-		parent::configure();
70
-
71
-		$this
72
-			->setName('files:scan')
73
-			->setDescription('rescan filesystem')
74
-			->addArgument(
75
-				'user_id',
76
-				InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
77
-				'will rescan all files of the given user(s)'
78
-			)
79
-			->addOption(
80
-				'path',
81
-				'p',
82
-				InputArgument::OPTIONAL,
83
-				'limit rescan to this path, eg. --path="/alice/files/Music", the user_id is determined by the path and the user_id parameter and --all are ignored'
84
-			)
85
-			->addOption(
86
-				'all',
87
-				null,
88
-				InputOption::VALUE_NONE,
89
-				'will rescan all files of all known users'
90
-			)->addOption(
91
-				'unscanned',
92
-				null,
93
-				InputOption::VALUE_NONE,
94
-				'only scan files which are marked as not fully scanned'
95
-			)->addOption(
96
-				'shallow',
97
-				null,
98
-				InputOption::VALUE_NONE,
99
-				'do not scan folders recursively'
100
-			)->addOption(
101
-				'home-only',
102
-				null,
103
-				InputOption::VALUE_NONE,
104
-				'only scan the home storage, ignoring any mounted external storage or share'
105
-			);
106
-	}
107
-
108
-	public function checkScanWarning($fullPath, OutputInterface $output) {
109
-		$normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
110
-		$path = basename($fullPath);
111
-
112
-		if ($normalizedPath !== $path) {
113
-			$output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
114
-		}
115
-	}
116
-
117
-	protected function scanFiles($user, $path, OutputInterface $output, $backgroundScan = false, $recursive = true, $homeOnly = false) {
118
-		$connection = $this->reconnectToDatabase($output);
119
-		$scanner = new \OC\Files\Utils\Scanner($user, $connection, \OC::$server->query(IEventDispatcher::class), \OC::$server->getLogger());
120
-
121
-		# check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
122
-
123
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
124
-			$output->writeln("\tFile\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
125
-			++$this->filesCounter;
126
-			$this->abortIfInterrupted();
127
-		});
128
-
129
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
130
-			$output->writeln("\tFolder\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
131
-			++$this->foldersCounter;
132
-			$this->abortIfInterrupted();
133
-		});
134
-
135
-		$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
136
-			$output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
137
-		});
138
-
139
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
140
-			$this->checkScanWarning($path, $output);
141
-		});
142
-
143
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
144
-			$this->checkScanWarning($path, $output);
145
-		});
146
-
147
-		try {
148
-			if ($backgroundScan) {
149
-				$scanner->backgroundScan($path);
150
-			} else {
151
-				$scanner->scan($path, $recursive, $homeOnly ? [$this, 'filterHomeMount'] : null);
152
-			}
153
-		} catch (ForbiddenException $e) {
154
-			$output->writeln("<error>Home storage for user $user not writable</error>");
155
-			$output->writeln('Make sure you\'re running the scan command only as the user the web server runs as');
156
-		} catch (InterruptedException $e) {
157
-			# exit the function if ctrl-c has been pressed
158
-			$output->writeln('Interrupted by user');
159
-		} catch (NotFoundException $e) {
160
-			$output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
161
-		} catch (\Exception $e) {
162
-			$output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
163
-			$output->writeln('<error>' . $e->getTraceAsString() . '</error>');
164
-		}
165
-	}
166
-
167
-	public function filterHomeMount(IMountPoint $mountPoint) {
168
-		// any mountpoint inside '/$user/files/'
169
-		return substr_count($mountPoint->getMountPoint(), '/') <= 3;
170
-	}
171
-
172
-	protected function execute(InputInterface $input, OutputInterface $output) {
173
-		$inputPath = $input->getOption('path');
174
-		if ($inputPath) {
175
-			$inputPath = '/' . trim($inputPath, '/');
176
-			list (, $user,) = explode('/', $inputPath, 3);
177
-			$users = [$user];
178
-		} else if ($input->getOption('all')) {
179
-			$users = $this->userManager->search('');
180
-		} else {
181
-			$users = $input->getArgument('user_id');
182
-		}
183
-
184
-		# restrict the verbosity level to VERBOSITY_VERBOSE
185
-		if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
186
-			$output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
187
-		}
188
-
189
-		# check quantity of users to be process and show it on the command line
190
-		$users_total = count($users);
191
-		if ($users_total === 0) {
192
-			$output->writeln('<error>Please specify the user id to scan, --all to scan for all users or --path=...</error>');
193
-			return;
194
-		}
195
-
196
-		$this->initTools();
197
-
198
-		$user_count = 0;
199
-		foreach ($users as $user) {
200
-			if (is_object($user)) {
201
-				$user = $user->getUID();
202
-			}
203
-			$path = $inputPath ? $inputPath : '/' . $user;
204
-			++$user_count;
205
-			if ($this->userManager->userExists($user)) {
206
-				$output->writeln("Starting scan for user $user_count out of $users_total ($user)");
207
-				$this->scanFiles($user, $path, $output, $input->getOption('unscanned'), !$input->getOption('shallow'), $input->getOption('home-only'));
208
-				$output->writeln('', OutputInterface::VERBOSITY_VERBOSE);
209
-			} else {
210
-				$output->writeln("<error>Unknown user $user_count $user</error>");
211
-				$output->writeln('', OutputInterface::VERBOSITY_VERBOSE);
212
-			}
213
-
214
-			try {
215
-				$this->abortIfInterrupted();
216
-			} catch (InterruptedException $e) {
217
-				break;
218
-			}
219
-		}
220
-
221
-		$this->presentStats($output);
222
-	}
223
-
224
-	/**
225
-	 * Initialises some useful tools for the Command
226
-	 */
227
-	protected function initTools() {
228
-		// Start the timer
229
-		$this->execTime = -microtime(true);
230
-		// Convert PHP errors to exceptions
231
-		set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
232
-	}
233
-
234
-	/**
235
-	 * Processes PHP errors as exceptions in order to be able to keep track of problems
236
-	 *
237
-	 * @see https://secure.php.net/manual/en/function.set-error-handler.php
238
-	 *
239
-	 * @param int $severity the level of the error raised
240
-	 * @param string $message
241
-	 * @param string $file the filename that the error was raised in
242
-	 * @param int $line the line number the error was raised
243
-	 *
244
-	 * @throws \ErrorException
245
-	 */
246
-	public function exceptionErrorHandler($severity, $message, $file, $line) {
247
-		if (!(error_reporting() & $severity)) {
248
-			// This error code is not included in error_reporting
249
-			return;
250
-		}
251
-		throw new \ErrorException($message, 0, $severity, $file, $line);
252
-	}
253
-
254
-	/**
255
-	 * @param OutputInterface $output
256
-	 */
257
-	protected function presentStats(OutputInterface $output) {
258
-		// Stop the timer
259
-		$this->execTime += microtime(true);
260
-
261
-		$headers = [
262
-			'Folders', 'Files', 'Elapsed time'
263
-		];
264
-
265
-		$this->showSummary($headers, null, $output);
266
-	}
267
-
268
-	/**
269
-	 * Shows a summary of operations
270
-	 *
271
-	 * @param string[] $headers
272
-	 * @param string[] $rows
273
-	 * @param OutputInterface $output
274
-	 */
275
-	protected function showSummary($headers, $rows, OutputInterface $output) {
276
-		$niceDate = $this->formatExecTime();
277
-		if (!$rows) {
278
-			$rows = [
279
-				$this->foldersCounter,
280
-				$this->filesCounter,
281
-				$niceDate,
282
-			];
283
-		}
284
-		$table = new Table($output);
285
-		$table
286
-			->setHeaders($headers)
287
-			->setRows([$rows]);
288
-		$table->render();
289
-	}
290
-
291
-
292
-	/**
293
-	 * Formats microtime into a human readable format
294
-	 *
295
-	 * @return string
296
-	 */
297
-	protected function formatExecTime() {
298
-		$secs = round($this->execTime);
299
-		# convert seconds into HH:MM:SS form
300
-		return sprintf('%02d:%02d:%02d', ($secs/3600), ($secs/60%60), $secs%60);
301
-	}
302
-
303
-	/**
304
-	 * @return \OCP\IDBConnection
305
-	 */
306
-	protected function reconnectToDatabase(OutputInterface $output) {
307
-		/** @var Connection | IDBConnection $connection */
308
-		$connection = \OC::$server->getDatabaseConnection();
309
-		try {
310
-			$connection->close();
311
-		} catch (\Exception $ex) {
312
-			$output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
313
-		}
314
-		while (!$connection->isConnected()) {
315
-			try {
316
-				$connection->connect();
317
-			} catch (\Exception $ex) {
318
-				$output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
319
-				sleep(60);
320
-			}
321
-		}
322
-		return $connection;
323
-	}
54
+    /** @var IUserManager $userManager */
55
+    private $userManager;
56
+    /** @var float */
57
+    protected $execTime = 0;
58
+    /** @var int */
59
+    protected $foldersCounter = 0;
60
+    /** @var int */
61
+    protected $filesCounter = 0;
62
+
63
+    public function __construct(IUserManager $userManager) {
64
+        $this->userManager = $userManager;
65
+        parent::__construct();
66
+    }
67
+
68
+    protected function configure() {
69
+        parent::configure();
70
+
71
+        $this
72
+            ->setName('files:scan')
73
+            ->setDescription('rescan filesystem')
74
+            ->addArgument(
75
+                'user_id',
76
+                InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
77
+                'will rescan all files of the given user(s)'
78
+            )
79
+            ->addOption(
80
+                'path',
81
+                'p',
82
+                InputArgument::OPTIONAL,
83
+                'limit rescan to this path, eg. --path="/alice/files/Music", the user_id is determined by the path and the user_id parameter and --all are ignored'
84
+            )
85
+            ->addOption(
86
+                'all',
87
+                null,
88
+                InputOption::VALUE_NONE,
89
+                'will rescan all files of all known users'
90
+            )->addOption(
91
+                'unscanned',
92
+                null,
93
+                InputOption::VALUE_NONE,
94
+                'only scan files which are marked as not fully scanned'
95
+            )->addOption(
96
+                'shallow',
97
+                null,
98
+                InputOption::VALUE_NONE,
99
+                'do not scan folders recursively'
100
+            )->addOption(
101
+                'home-only',
102
+                null,
103
+                InputOption::VALUE_NONE,
104
+                'only scan the home storage, ignoring any mounted external storage or share'
105
+            );
106
+    }
107
+
108
+    public function checkScanWarning($fullPath, OutputInterface $output) {
109
+        $normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
110
+        $path = basename($fullPath);
111
+
112
+        if ($normalizedPath !== $path) {
113
+            $output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
114
+        }
115
+    }
116
+
117
+    protected function scanFiles($user, $path, OutputInterface $output, $backgroundScan = false, $recursive = true, $homeOnly = false) {
118
+        $connection = $this->reconnectToDatabase($output);
119
+        $scanner = new \OC\Files\Utils\Scanner($user, $connection, \OC::$server->query(IEventDispatcher::class), \OC::$server->getLogger());
120
+
121
+        # check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
122
+
123
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
124
+            $output->writeln("\tFile\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
125
+            ++$this->filesCounter;
126
+            $this->abortIfInterrupted();
127
+        });
128
+
129
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
130
+            $output->writeln("\tFolder\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
131
+            ++$this->foldersCounter;
132
+            $this->abortIfInterrupted();
133
+        });
134
+
135
+        $scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
136
+            $output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
137
+        });
138
+
139
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
140
+            $this->checkScanWarning($path, $output);
141
+        });
142
+
143
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
144
+            $this->checkScanWarning($path, $output);
145
+        });
146
+
147
+        try {
148
+            if ($backgroundScan) {
149
+                $scanner->backgroundScan($path);
150
+            } else {
151
+                $scanner->scan($path, $recursive, $homeOnly ? [$this, 'filterHomeMount'] : null);
152
+            }
153
+        } catch (ForbiddenException $e) {
154
+            $output->writeln("<error>Home storage for user $user not writable</error>");
155
+            $output->writeln('Make sure you\'re running the scan command only as the user the web server runs as');
156
+        } catch (InterruptedException $e) {
157
+            # exit the function if ctrl-c has been pressed
158
+            $output->writeln('Interrupted by user');
159
+        } catch (NotFoundException $e) {
160
+            $output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
161
+        } catch (\Exception $e) {
162
+            $output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
163
+            $output->writeln('<error>' . $e->getTraceAsString() . '</error>');
164
+        }
165
+    }
166
+
167
+    public function filterHomeMount(IMountPoint $mountPoint) {
168
+        // any mountpoint inside '/$user/files/'
169
+        return substr_count($mountPoint->getMountPoint(), '/') <= 3;
170
+    }
171
+
172
+    protected function execute(InputInterface $input, OutputInterface $output) {
173
+        $inputPath = $input->getOption('path');
174
+        if ($inputPath) {
175
+            $inputPath = '/' . trim($inputPath, '/');
176
+            list (, $user,) = explode('/', $inputPath, 3);
177
+            $users = [$user];
178
+        } else if ($input->getOption('all')) {
179
+            $users = $this->userManager->search('');
180
+        } else {
181
+            $users = $input->getArgument('user_id');
182
+        }
183
+
184
+        # restrict the verbosity level to VERBOSITY_VERBOSE
185
+        if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
186
+            $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
187
+        }
188
+
189
+        # check quantity of users to be process and show it on the command line
190
+        $users_total = count($users);
191
+        if ($users_total === 0) {
192
+            $output->writeln('<error>Please specify the user id to scan, --all to scan for all users or --path=...</error>');
193
+            return;
194
+        }
195
+
196
+        $this->initTools();
197
+
198
+        $user_count = 0;
199
+        foreach ($users as $user) {
200
+            if (is_object($user)) {
201
+                $user = $user->getUID();
202
+            }
203
+            $path = $inputPath ? $inputPath : '/' . $user;
204
+            ++$user_count;
205
+            if ($this->userManager->userExists($user)) {
206
+                $output->writeln("Starting scan for user $user_count out of $users_total ($user)");
207
+                $this->scanFiles($user, $path, $output, $input->getOption('unscanned'), !$input->getOption('shallow'), $input->getOption('home-only'));
208
+                $output->writeln('', OutputInterface::VERBOSITY_VERBOSE);
209
+            } else {
210
+                $output->writeln("<error>Unknown user $user_count $user</error>");
211
+                $output->writeln('', OutputInterface::VERBOSITY_VERBOSE);
212
+            }
213
+
214
+            try {
215
+                $this->abortIfInterrupted();
216
+            } catch (InterruptedException $e) {
217
+                break;
218
+            }
219
+        }
220
+
221
+        $this->presentStats($output);
222
+    }
223
+
224
+    /**
225
+     * Initialises some useful tools for the Command
226
+     */
227
+    protected function initTools() {
228
+        // Start the timer
229
+        $this->execTime = -microtime(true);
230
+        // Convert PHP errors to exceptions
231
+        set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
232
+    }
233
+
234
+    /**
235
+     * Processes PHP errors as exceptions in order to be able to keep track of problems
236
+     *
237
+     * @see https://secure.php.net/manual/en/function.set-error-handler.php
238
+     *
239
+     * @param int $severity the level of the error raised
240
+     * @param string $message
241
+     * @param string $file the filename that the error was raised in
242
+     * @param int $line the line number the error was raised
243
+     *
244
+     * @throws \ErrorException
245
+     */
246
+    public function exceptionErrorHandler($severity, $message, $file, $line) {
247
+        if (!(error_reporting() & $severity)) {
248
+            // This error code is not included in error_reporting
249
+            return;
250
+        }
251
+        throw new \ErrorException($message, 0, $severity, $file, $line);
252
+    }
253
+
254
+    /**
255
+     * @param OutputInterface $output
256
+     */
257
+    protected function presentStats(OutputInterface $output) {
258
+        // Stop the timer
259
+        $this->execTime += microtime(true);
260
+
261
+        $headers = [
262
+            'Folders', 'Files', 'Elapsed time'
263
+        ];
264
+
265
+        $this->showSummary($headers, null, $output);
266
+    }
267
+
268
+    /**
269
+     * Shows a summary of operations
270
+     *
271
+     * @param string[] $headers
272
+     * @param string[] $rows
273
+     * @param OutputInterface $output
274
+     */
275
+    protected function showSummary($headers, $rows, OutputInterface $output) {
276
+        $niceDate = $this->formatExecTime();
277
+        if (!$rows) {
278
+            $rows = [
279
+                $this->foldersCounter,
280
+                $this->filesCounter,
281
+                $niceDate,
282
+            ];
283
+        }
284
+        $table = new Table($output);
285
+        $table
286
+            ->setHeaders($headers)
287
+            ->setRows([$rows]);
288
+        $table->render();
289
+    }
290
+
291
+
292
+    /**
293
+     * Formats microtime into a human readable format
294
+     *
295
+     * @return string
296
+     */
297
+    protected function formatExecTime() {
298
+        $secs = round($this->execTime);
299
+        # convert seconds into HH:MM:SS form
300
+        return sprintf('%02d:%02d:%02d', ($secs/3600), ($secs/60%60), $secs%60);
301
+    }
302
+
303
+    /**
304
+     * @return \OCP\IDBConnection
305
+     */
306
+    protected function reconnectToDatabase(OutputInterface $output) {
307
+        /** @var Connection | IDBConnection $connection */
308
+        $connection = \OC::$server->getDatabaseConnection();
309
+        try {
310
+            $connection->close();
311
+        } catch (\Exception $ex) {
312
+            $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
313
+        }
314
+        while (!$connection->isConnected()) {
315
+            try {
316
+                $connection->connect();
317
+            } catch (\Exception $ex) {
318
+                $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
319
+                sleep(60);
320
+            }
321
+        }
322
+        return $connection;
323
+    }
324 324
 
325 325
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 		$path = basename($fullPath);
111 111
 
112 112
 		if ($normalizedPath !== $path) {
113
-			$output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
113
+			$output->writeln("\t<error>Entry \"".$fullPath.'" will not be accessible due to incompatible encoding</error>');
114 114
 		}
115 115
 	}
116 116
 
@@ -120,27 +120,27 @@  discard block
 block discarded – undo
120 120
 
121 121
 		# check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
122 122
 
123
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
123
+		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function($path) use ($output) {
124 124
 			$output->writeln("\tFile\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
125 125
 			++$this->filesCounter;
126 126
 			$this->abortIfInterrupted();
127 127
 		});
128 128
 
129
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
129
+		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function($path) use ($output) {
130 130
 			$output->writeln("\tFolder\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
131 131
 			++$this->foldersCounter;
132 132
 			$this->abortIfInterrupted();
133 133
 		});
134 134
 
135
-		$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
136
-			$output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
135
+		$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function(StorageNotAvailableException $e) use ($output) {
136
+			$output->writeln('Error while scanning, storage not available ('.$e->getMessage().')', OutputInterface::VERBOSITY_VERBOSE);
137 137
 		});
138 138
 
139
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
139
+		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function($path) use ($output) {
140 140
 			$this->checkScanWarning($path, $output);
141 141
 		});
142 142
 
143
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
143
+		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function($path) use ($output) {
144 144
 			$this->checkScanWarning($path, $output);
145 145
 		});
146 146
 
@@ -157,10 +157,10 @@  discard block
 block discarded – undo
157 157
 			# exit the function if ctrl-c has been pressed
158 158
 			$output->writeln('Interrupted by user');
159 159
 		} catch (NotFoundException $e) {
160
-			$output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
160
+			$output->writeln('<error>Path not found: '.$e->getMessage().'</error>');
161 161
 		} catch (\Exception $e) {
162
-			$output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
163
-			$output->writeln('<error>' . $e->getTraceAsString() . '</error>');
162
+			$output->writeln('<error>Exception during scan: '.$e->getMessage().'</error>');
163
+			$output->writeln('<error>'.$e->getTraceAsString().'</error>');
164 164
 		}
165 165
 	}
166 166
 
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 	protected function execute(InputInterface $input, OutputInterface $output) {
173 173
 		$inputPath = $input->getOption('path');
174 174
 		if ($inputPath) {
175
-			$inputPath = '/' . trim($inputPath, '/');
175
+			$inputPath = '/'.trim($inputPath, '/');
176 176
 			list (, $user,) = explode('/', $inputPath, 3);
177 177
 			$users = [$user];
178 178
 		} else if ($input->getOption('all')) {
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 			if (is_object($user)) {
201 201
 				$user = $user->getUID();
202 202
 			}
203
-			$path = $inputPath ? $inputPath : '/' . $user;
203
+			$path = $inputPath ? $inputPath : '/'.$user;
204 204
 			++$user_count;
205 205
 			if ($this->userManager->userExists($user)) {
206 206
 				$output->writeln("Starting scan for user $user_count out of $users_total ($user)");
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
 	protected function formatExecTime() {
298 298
 		$secs = round($this->execTime);
299 299
 		# convert seconds into HH:MM:SS form
300
-		return sprintf('%02d:%02d:%02d', ($secs/3600), ($secs/60%60), $secs%60);
300
+		return sprintf('%02d:%02d:%02d', ($secs / 3600), ($secs / 60 % 60), $secs % 60);
301 301
 	}
302 302
 
303 303
 	/**
Please login to merge, or discard this patch.
apps/files/lib/Helper.php 1 patch
Indentation   +208 added lines, -208 removed lines patch added patch discarded remove patch
@@ -40,232 +40,232 @@
 block discarded – undo
40 40
  * Helper class for manipulating file information
41 41
  */
42 42
 class Helper {
43
-	/**
44
-	 * @param string $dir
45
-	 * @return array
46
-	 * @throws \OCP\Files\NotFoundException
47
-	 */
48
-	public static function buildFileStorageStatistics($dir) {
49
-		// information about storage capacities
50
-		$storageInfo = \OC_Helper::getStorageInfo($dir);
51
-		$l = \OC::$server->getL10N('files');
52
-		$maxUploadFileSize = \OCP\Util::maxUploadFilesize($dir, $storageInfo['free']);
53
-		$maxHumanFileSize = \OCP\Util::humanFileSize($maxUploadFileSize);
54
-		$maxHumanFileSize = $l->t('Upload (max. %s)', [$maxHumanFileSize]);
43
+    /**
44
+     * @param string $dir
45
+     * @return array
46
+     * @throws \OCP\Files\NotFoundException
47
+     */
48
+    public static function buildFileStorageStatistics($dir) {
49
+        // information about storage capacities
50
+        $storageInfo = \OC_Helper::getStorageInfo($dir);
51
+        $l = \OC::$server->getL10N('files');
52
+        $maxUploadFileSize = \OCP\Util::maxUploadFilesize($dir, $storageInfo['free']);
53
+        $maxHumanFileSize = \OCP\Util::humanFileSize($maxUploadFileSize);
54
+        $maxHumanFileSize = $l->t('Upload (max. %s)', [$maxHumanFileSize]);
55 55
 
56
-		return [
57
-			'uploadMaxFilesize' => $maxUploadFileSize,
58
-			'maxHumanFilesize'  => $maxHumanFileSize,
59
-			'freeSpace' => $storageInfo['free'],
60
-			'quota' => $storageInfo['quota'],
61
-			'used' => $storageInfo['used'],
62
-			'usedSpacePercent'  => (int)$storageInfo['relative'],
63
-			'owner' => $storageInfo['owner'],
64
-			'ownerDisplayName' => $storageInfo['ownerDisplayName'],
65
-		];
66
-	}
56
+        return [
57
+            'uploadMaxFilesize' => $maxUploadFileSize,
58
+            'maxHumanFilesize'  => $maxHumanFileSize,
59
+            'freeSpace' => $storageInfo['free'],
60
+            'quota' => $storageInfo['quota'],
61
+            'used' => $storageInfo['used'],
62
+            'usedSpacePercent'  => (int)$storageInfo['relative'],
63
+            'owner' => $storageInfo['owner'],
64
+            'ownerDisplayName' => $storageInfo['ownerDisplayName'],
65
+        ];
66
+    }
67 67
 
68
-	/**
69
-	 * Determine icon for a given file
70
-	 *
71
-	 * @param \OCP\Files\FileInfo $file file info
72
-	 * @return string icon URL
73
-	 */
74
-	public static function determineIcon($file) {
75
-		if($file['type'] === 'dir') {
76
-			$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir');
77
-			// TODO: move this part to the client side, using mountType
78
-			if ($file->isShared()) {
79
-				$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-shared');
80
-			} elseif ($file->isMounted()) {
81
-				$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-external');
82
-			}
83
-		}else{
84
-			$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($file->getMimetype());
85
-		}
68
+    /**
69
+     * Determine icon for a given file
70
+     *
71
+     * @param \OCP\Files\FileInfo $file file info
72
+     * @return string icon URL
73
+     */
74
+    public static function determineIcon($file) {
75
+        if($file['type'] === 'dir') {
76
+            $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir');
77
+            // TODO: move this part to the client side, using mountType
78
+            if ($file->isShared()) {
79
+                $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-shared');
80
+            } elseif ($file->isMounted()) {
81
+                $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-external');
82
+            }
83
+        }else{
84
+            $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($file->getMimetype());
85
+        }
86 86
 
87
-		return substr($icon, 0, -3) . 'svg';
88
-	}
87
+        return substr($icon, 0, -3) . 'svg';
88
+    }
89 89
 
90
-	/**
91
-	 * Comparator function to sort files alphabetically and have
92
-	 * the directories appear first
93
-	 *
94
-	 * @param \OCP\Files\FileInfo $a file
95
-	 * @param \OCP\Files\FileInfo $b file
96
-	 * @return int -1 if $a must come before $b, 1 otherwise
97
-	 */
98
-	public static function compareFileNames(FileInfo $a, FileInfo $b) {
99
-		$aType = $a->getType();
100
-		$bType = $b->getType();
101
-		if ($aType === 'dir' and $bType !== 'dir') {
102
-			return -1;
103
-		} elseif ($aType !== 'dir' and $bType === 'dir') {
104
-			return 1;
105
-		} else {
106
-			return \OCP\Util::naturalSortCompare($a->getName(), $b->getName());
107
-		}
108
-	}
90
+    /**
91
+     * Comparator function to sort files alphabetically and have
92
+     * the directories appear first
93
+     *
94
+     * @param \OCP\Files\FileInfo $a file
95
+     * @param \OCP\Files\FileInfo $b file
96
+     * @return int -1 if $a must come before $b, 1 otherwise
97
+     */
98
+    public static function compareFileNames(FileInfo $a, FileInfo $b) {
99
+        $aType = $a->getType();
100
+        $bType = $b->getType();
101
+        if ($aType === 'dir' and $bType !== 'dir') {
102
+            return -1;
103
+        } elseif ($aType !== 'dir' and $bType === 'dir') {
104
+            return 1;
105
+        } else {
106
+            return \OCP\Util::naturalSortCompare($a->getName(), $b->getName());
107
+        }
108
+    }
109 109
 
110
-	/**
111
-	 * Comparator function to sort files by date
112
-	 *
113
-	 * @param \OCP\Files\FileInfo $a file
114
-	 * @param \OCP\Files\FileInfo $b file
115
-	 * @return int -1 if $a must come before $b, 1 otherwise
116
-	 */
117
-	public static function compareTimestamp(FileInfo $a, FileInfo $b) {
118
-		$aTime = $a->getMTime();
119
-		$bTime = $b->getMTime();
120
-		return ($aTime < $bTime) ? -1 : 1;
121
-	}
110
+    /**
111
+     * Comparator function to sort files by date
112
+     *
113
+     * @param \OCP\Files\FileInfo $a file
114
+     * @param \OCP\Files\FileInfo $b file
115
+     * @return int -1 if $a must come before $b, 1 otherwise
116
+     */
117
+    public static function compareTimestamp(FileInfo $a, FileInfo $b) {
118
+        $aTime = $a->getMTime();
119
+        $bTime = $b->getMTime();
120
+        return ($aTime < $bTime) ? -1 : 1;
121
+    }
122 122
 
123
-	/**
124
-	 * Comparator function to sort files by size
125
-	 *
126
-	 * @param \OCP\Files\FileInfo $a file
127
-	 * @param \OCP\Files\FileInfo $b file
128
-	 * @return int -1 if $a must come before $b, 1 otherwise
129
-	 */
130
-	public static function compareSize(FileInfo $a, FileInfo $b) {
131
-		$aSize = $a->getSize();
132
-		$bSize = $b->getSize();
133
-		return ($aSize < $bSize) ? -1 : 1;
134
-	}
123
+    /**
124
+     * Comparator function to sort files by size
125
+     *
126
+     * @param \OCP\Files\FileInfo $a file
127
+     * @param \OCP\Files\FileInfo $b file
128
+     * @return int -1 if $a must come before $b, 1 otherwise
129
+     */
130
+    public static function compareSize(FileInfo $a, FileInfo $b) {
131
+        $aSize = $a->getSize();
132
+        $bSize = $b->getSize();
133
+        return ($aSize < $bSize) ? -1 : 1;
134
+    }
135 135
 
136
-	/**
137
-	 * Formats the file info to be returned as JSON to the client.
138
-	 *
139
-	 * @param \OCP\Files\FileInfo $i
140
-	 * @return array formatted file info
141
-	 */
142
-	public static function formatFileInfo(FileInfo $i) {
143
-		$entry = [];
136
+    /**
137
+     * Formats the file info to be returned as JSON to the client.
138
+     *
139
+     * @param \OCP\Files\FileInfo $i
140
+     * @return array formatted file info
141
+     */
142
+    public static function formatFileInfo(FileInfo $i) {
143
+        $entry = [];
144 144
 
145
-		$entry['id'] = $i['fileid'];
146
-		$entry['parentId'] = $i['parent'];
147
-		$entry['mtime'] = $i['mtime'] * 1000;
148
-		// only pick out the needed attributes
149
-		$entry['name'] = $i->getName();
150
-		$entry['permissions'] = $i['permissions'];
151
-		$entry['mimetype'] = $i['mimetype'];
152
-		$entry['size'] = $i['size'];
153
-		$entry['type'] = $i['type'];
154
-		$entry['etag'] = $i['etag'];
155
-		if (isset($i['tags'])) {
156
-			$entry['tags'] = $i['tags'];
157
-		}
158
-		if (isset($i['displayname_owner'])) {
159
-			$entry['shareOwner'] = $i['displayname_owner'];
160
-		}
161
-		if (isset($i['is_share_mount_point'])) {
162
-			$entry['isShareMountPoint'] = $i['is_share_mount_point'];
163
-		}
164
-		$mountType = null;
165
-		$mount = $i->getMountPoint();
166
-		$mountType = $mount->getMountType();
167
-		if ($mountType !== '') {
168
-			if ($i->getInternalPath() === '') {
169
-				$mountType .= '-root';
170
-			}
171
-			$entry['mountType'] = $mountType;
172
-		}
173
-		if (isset($i['extraData'])) {
174
-			$entry['extraData'] = $i['extraData'];
175
-		}
176
-		return $entry;
177
-	}
145
+        $entry['id'] = $i['fileid'];
146
+        $entry['parentId'] = $i['parent'];
147
+        $entry['mtime'] = $i['mtime'] * 1000;
148
+        // only pick out the needed attributes
149
+        $entry['name'] = $i->getName();
150
+        $entry['permissions'] = $i['permissions'];
151
+        $entry['mimetype'] = $i['mimetype'];
152
+        $entry['size'] = $i['size'];
153
+        $entry['type'] = $i['type'];
154
+        $entry['etag'] = $i['etag'];
155
+        if (isset($i['tags'])) {
156
+            $entry['tags'] = $i['tags'];
157
+        }
158
+        if (isset($i['displayname_owner'])) {
159
+            $entry['shareOwner'] = $i['displayname_owner'];
160
+        }
161
+        if (isset($i['is_share_mount_point'])) {
162
+            $entry['isShareMountPoint'] = $i['is_share_mount_point'];
163
+        }
164
+        $mountType = null;
165
+        $mount = $i->getMountPoint();
166
+        $mountType = $mount->getMountType();
167
+        if ($mountType !== '') {
168
+            if ($i->getInternalPath() === '') {
169
+                $mountType .= '-root';
170
+            }
171
+            $entry['mountType'] = $mountType;
172
+        }
173
+        if (isset($i['extraData'])) {
174
+            $entry['extraData'] = $i['extraData'];
175
+        }
176
+        return $entry;
177
+    }
178 178
 
179
-	/**
180
-	 * Format file info for JSON
181
-	 * @param \OCP\Files\FileInfo[] $fileInfos file infos
182
-	 * @return array
183
-	 */
184
-	public static function formatFileInfos($fileInfos) {
185
-		$files = [];
186
-		foreach ($fileInfos as $i) {
187
-			$files[] = self::formatFileInfo($i);
188
-		}
179
+    /**
180
+     * Format file info for JSON
181
+     * @param \OCP\Files\FileInfo[] $fileInfos file infos
182
+     * @return array
183
+     */
184
+    public static function formatFileInfos($fileInfos) {
185
+        $files = [];
186
+        foreach ($fileInfos as $i) {
187
+            $files[] = self::formatFileInfo($i);
188
+        }
189 189
 
190
-		return $files;
191
-	}
190
+        return $files;
191
+    }
192 192
 
193
-	/**
194
-	 * Retrieves the contents of the given directory and
195
-	 * returns it as a sorted array of FileInfo.
196
-	 *
197
-	 * @param string $dir path to the directory
198
-	 * @param string $sortAttribute attribute to sort on
199
-	 * @param bool $sortDescending true for descending sort, false otherwise
200
-	 * @param string $mimetypeFilter limit returned content to this mimetype or mimepart
201
-	 * @return \OCP\Files\FileInfo[] files
202
-	 */
203
-	public static function getFiles($dir, $sortAttribute = 'name', $sortDescending = false, $mimetypeFilter = '') {
204
-		$content = \OC\Files\Filesystem::getDirectoryContent($dir, $mimetypeFilter);
193
+    /**
194
+     * Retrieves the contents of the given directory and
195
+     * returns it as a sorted array of FileInfo.
196
+     *
197
+     * @param string $dir path to the directory
198
+     * @param string $sortAttribute attribute to sort on
199
+     * @param bool $sortDescending true for descending sort, false otherwise
200
+     * @param string $mimetypeFilter limit returned content to this mimetype or mimepart
201
+     * @return \OCP\Files\FileInfo[] files
202
+     */
203
+    public static function getFiles($dir, $sortAttribute = 'name', $sortDescending = false, $mimetypeFilter = '') {
204
+        $content = \OC\Files\Filesystem::getDirectoryContent($dir, $mimetypeFilter);
205 205
 
206
-		return self::sortFiles($content, $sortAttribute, $sortDescending);
207
-	}
206
+        return self::sortFiles($content, $sortAttribute, $sortDescending);
207
+    }
208 208
 
209
-	/**
210
-	 * Populate the result set with file tags
211
-	 *
212
-	 * @param array $fileList
213
-	 * @param string $fileIdentifier identifier attribute name for values in $fileList
214
-	 * @param ITagManager $tagManager
215
-	 * @return array file list populated with tags
216
-	 */
217
-	public static function populateTags(array $fileList, $fileIdentifier = 'fileid', ITagManager $tagManager) {
218
-		$ids = [];
219
-		foreach ($fileList as $fileData) {
220
-			$ids[] = $fileData[$fileIdentifier];
221
-		}
222
-		$tagger = $tagManager->load('files');
223
-		$tags = $tagger->getTagsForObjects($ids);
209
+    /**
210
+     * Populate the result set with file tags
211
+     *
212
+     * @param array $fileList
213
+     * @param string $fileIdentifier identifier attribute name for values in $fileList
214
+     * @param ITagManager $tagManager
215
+     * @return array file list populated with tags
216
+     */
217
+    public static function populateTags(array $fileList, $fileIdentifier = 'fileid', ITagManager $tagManager) {
218
+        $ids = [];
219
+        foreach ($fileList as $fileData) {
220
+            $ids[] = $fileData[$fileIdentifier];
221
+        }
222
+        $tagger = $tagManager->load('files');
223
+        $tags = $tagger->getTagsForObjects($ids);
224 224
 
225
-		if (!is_array($tags)) {
226
-			throw new \UnexpectedValueException('$tags must be an array');
227
-		}
225
+        if (!is_array($tags)) {
226
+            throw new \UnexpectedValueException('$tags must be an array');
227
+        }
228 228
 
229
-		// Set empty tag array
230
-		foreach ($fileList as $key => $fileData) {
231
-			$fileList[$key]['tags'] = [];
232
-		}
229
+        // Set empty tag array
230
+        foreach ($fileList as $key => $fileData) {
231
+            $fileList[$key]['tags'] = [];
232
+        }
233 233
 
234
-		if (!empty($tags)) {
235
-			foreach ($tags as $fileId => $fileTags) {
234
+        if (!empty($tags)) {
235
+            foreach ($tags as $fileId => $fileTags) {
236 236
 
237
-				foreach ($fileList as $key => $fileData) {
238
-					if ($fileId !== $fileData[$fileIdentifier]) {
239
-						continue;
240
-					}
237
+                foreach ($fileList as $key => $fileData) {
238
+                    if ($fileId !== $fileData[$fileIdentifier]) {
239
+                        continue;
240
+                    }
241 241
 
242
-					$fileList[$key]['tags'] = $fileTags;
243
-				}
244
-			}
245
-		}
242
+                    $fileList[$key]['tags'] = $fileTags;
243
+                }
244
+            }
245
+        }
246 246
 
247
-		return $fileList;
248
-	}
247
+        return $fileList;
248
+    }
249 249
 
250
-	/**
251
-	 * Sort the given file info array
252
-	 *
253
-	 * @param \OCP\Files\FileInfo[] $files files to sort
254
-	 * @param string $sortAttribute attribute to sort on
255
-	 * @param bool $sortDescending true for descending sort, false otherwise
256
-	 * @return \OCP\Files\FileInfo[] sorted files
257
-	 */
258
-	public static function sortFiles($files, $sortAttribute = 'name', $sortDescending = false) {
259
-		$sortFunc = 'compareFileNames';
260
-		if ($sortAttribute === 'mtime') {
261
-			$sortFunc = 'compareTimestamp';
262
-		} else if ($sortAttribute === 'size') {
263
-			$sortFunc = 'compareSize';
264
-		}
265
-		usort($files, [Helper::class, $sortFunc]);
266
-		if ($sortDescending) {
267
-			$files = array_reverse($files);
268
-		}
269
-		return $files;
270
-	}
250
+    /**
251
+     * Sort the given file info array
252
+     *
253
+     * @param \OCP\Files\FileInfo[] $files files to sort
254
+     * @param string $sortAttribute attribute to sort on
255
+     * @param bool $sortDescending true for descending sort, false otherwise
256
+     * @return \OCP\Files\FileInfo[] sorted files
257
+     */
258
+    public static function sortFiles($files, $sortAttribute = 'name', $sortDescending = false) {
259
+        $sortFunc = 'compareFileNames';
260
+        if ($sortAttribute === 'mtime') {
261
+            $sortFunc = 'compareTimestamp';
262
+        } else if ($sortAttribute === 'size') {
263
+            $sortFunc = 'compareSize';
264
+        }
265
+        usort($files, [Helper::class, $sortFunc]);
266
+        if ($sortDescending) {
267
+            $files = array_reverse($files);
268
+        }
269
+        return $files;
270
+    }
271 271
 }
Please login to merge, or discard this patch.