Passed
Push — master ( a2ecac...2afa1c )
by Roeland
18:22 queued 11s
created
apps/settings/lib/Controller/CheckSetupController.php 2 patches
Indentation   +680 added lines, -680 removed lines patch added patch discarded remove patch
@@ -82,304 +82,304 @@  discard block
 block discarded – undo
82 82
 use Symfony\Component\EventDispatcher\GenericEvent;
83 83
 
84 84
 class CheckSetupController extends Controller {
85
-	/** @var IConfig */
86
-	private $config;
87
-	/** @var IClientService */
88
-	private $clientService;
89
-	/** @var IURLGenerator */
90
-	private $urlGenerator;
91
-	/** @var IL10N */
92
-	private $l10n;
93
-	/** @var Checker */
94
-	private $checker;
95
-	/** @var LoggerInterface */
96
-	private $logger;
97
-	/** @var EventDispatcherInterface */
98
-	private $dispatcher;
99
-	/** @var Connection */
100
-	private $db;
101
-	/** @var ILockingProvider */
102
-	private $lockingProvider;
103
-	/** @var IDateTimeFormatter */
104
-	private $dateTimeFormatter;
105
-	/** @var MemoryInfo */
106
-	private $memoryInfo;
107
-	/** @var ISecureRandom */
108
-	private $secureRandom;
109
-	/** @var IniGetWrapper */
110
-	private $iniGetWrapper;
111
-	/** @var IDBConnection */
112
-	private $connection;
113
-
114
-	public function __construct($AppName,
115
-								IRequest $request,
116
-								IConfig $config,
117
-								IClientService $clientService,
118
-								IURLGenerator $urlGenerator,
119
-								IL10N $l10n,
120
-								Checker $checker,
121
-								LoggerInterface $logger,
122
-								EventDispatcherInterface $dispatcher,
123
-								Connection $db,
124
-								ILockingProvider $lockingProvider,
125
-								IDateTimeFormatter $dateTimeFormatter,
126
-								MemoryInfo $memoryInfo,
127
-								ISecureRandom $secureRandom,
128
-								IniGetWrapper $iniGetWrapper,
129
-								IDBConnection $connection) {
130
-		parent::__construct($AppName, $request);
131
-		$this->config = $config;
132
-		$this->clientService = $clientService;
133
-		$this->urlGenerator = $urlGenerator;
134
-		$this->l10n = $l10n;
135
-		$this->checker = $checker;
136
-		$this->logger = $logger;
137
-		$this->dispatcher = $dispatcher;
138
-		$this->db = $db;
139
-		$this->lockingProvider = $lockingProvider;
140
-		$this->dateTimeFormatter = $dateTimeFormatter;
141
-		$this->memoryInfo = $memoryInfo;
142
-		$this->secureRandom = $secureRandom;
143
-		$this->iniGetWrapper = $iniGetWrapper;
144
-		$this->connection = $connection;
145
-	}
146
-
147
-	/**
148
-	 * Checks if the server can connect to the internet using HTTPS and HTTP
149
-	 * @return bool
150
-	 */
151
-	private function hasInternetConnectivityProblems(): bool {
152
-		if ($this->config->getSystemValue('has_internet_connection', true) === false) {
153
-			return false;
154
-		}
155
-
156
-		$siteArray = $this->config->getSystemValue('connectivity_check_domains', [
157
-			'www.nextcloud.com', 'www.startpage.com', 'www.eff.org', 'www.edri.org'
158
-		]);
159
-
160
-		foreach ($siteArray as $site) {
161
-			if ($this->isSiteReachable($site)) {
162
-				return false;
163
-			}
164
-		}
165
-		return true;
166
-	}
167
-
168
-	/**
169
-	 * Checks if the Nextcloud server can connect to a specific URL using both HTTPS and HTTP
170
-	 * @return bool
171
-	 */
172
-	private function isSiteReachable($sitename) {
173
-		$httpSiteName = 'http://' . $sitename . '/';
174
-		$httpsSiteName = 'https://' . $sitename . '/';
175
-
176
-		try {
177
-			$client = $this->clientService->newClient();
178
-			$client->get($httpSiteName);
179
-			$client->get($httpsSiteName);
180
-		} catch (\Exception $e) {
181
-			$this->logger->error('Cannot connect to: ' . $sitename, [
182
-				'app' => 'internet_connection_check',
183
-				'exception' => $e,
184
-			]);
185
-			return false;
186
-		}
187
-		return true;
188
-	}
189
-
190
-	/**
191
-	 * Checks whether a local memcache is installed or not
192
-	 * @return bool
193
-	 */
194
-	private function isMemcacheConfigured() {
195
-		return $this->config->getSystemValue('memcache.local', null) !== null;
196
-	}
197
-
198
-	/**
199
-	 * Whether PHP can generate "secure" pseudorandom integers
200
-	 *
201
-	 * @return bool
202
-	 */
203
-	private function isRandomnessSecure() {
204
-		try {
205
-			$this->secureRandom->generate(1);
206
-		} catch (\Exception $ex) {
207
-			return false;
208
-		}
209
-		return true;
210
-	}
211
-
212
-	/**
213
-	 * Public for the sake of unit-testing
214
-	 *
215
-	 * @return array
216
-	 */
217
-	protected function getCurlVersion() {
218
-		return curl_version();
219
-	}
220
-
221
-	/**
222
-	 * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
223
-	 * have multiple bugs which likely lead to problems in combination with
224
-	 * functionality required by ownCloud such as SNI.
225
-	 *
226
-	 * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
227
-	 * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
228
-	 * @return string
229
-	 */
230
-	private function isUsedTlsLibOutdated() {
231
-		// Don't run check when:
232
-		// 1. Server has `has_internet_connection` set to false
233
-		// 2. AppStore AND S2S is disabled
234
-		if (!$this->config->getSystemValue('has_internet_connection', true)) {
235
-			return '';
236
-		}
237
-		if (!$this->config->getSystemValue('appstoreenabled', true)
238
-			&& $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
239
-			&& $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
240
-			return '';
241
-		}
242
-
243
-		$versionString = $this->getCurlVersion();
244
-		if (isset($versionString['ssl_version'])) {
245
-			$versionString = $versionString['ssl_version'];
246
-		} else {
247
-			return '';
248
-		}
249
-
250
-		$features = $this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
251
-		if (!$this->config->getSystemValue('appstoreenabled', true)) {
252
-			$features = $this->l10n->t('Federated Cloud Sharing');
253
-		}
254
-
255
-		// Check if at least OpenSSL after 1.01d or 1.0.2b
256
-		if (strpos($versionString, 'OpenSSL/') === 0) {
257
-			$majorVersion = substr($versionString, 8, 5);
258
-			$patchRelease = substr($versionString, 13, 6);
259
-
260
-			if (($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
261
-				($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
262
-				return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['OpenSSL', $versionString, $features]);
263
-			}
264
-		}
265
-
266
-		// Check if NSS and perform heuristic check
267
-		if (strpos($versionString, 'NSS/') === 0) {
268
-			try {
269
-				$firstClient = $this->clientService->newClient();
270
-				$firstClient->get('https://nextcloud.com/');
271
-
272
-				$secondClient = $this->clientService->newClient();
273
-				$secondClient->get('https://nextcloud.com/');
274
-			} catch (ClientException $e) {
275
-				if ($e->getResponse()->getStatusCode() === 400) {
276
-					return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['NSS', $versionString, $features]);
277
-				}
278
-			} catch (\Exception $e) {
279
-				$this->logger->warning('error checking curl', [
280
-					'app' => 'settings',
281
-					'exception' => $e,
282
-				]);
283
-				return $this->l10n->t('Could not determine if TLS version of cURL is outdated or not because an error happened during the HTTPS request against https://nextcloud.com. Please check the nextcloud log file for more details.');
284
-			}
285
-		}
286
-
287
-		return '';
288
-	}
289
-
290
-	/**
291
-	 * Whether the version is outdated
292
-	 *
293
-	 * @return bool
294
-	 */
295
-	protected function isPhpOutdated(): bool {
296
-		return PHP_VERSION_ID < 70300;
297
-	}
298
-
299
-	/**
300
-	 * Whether the php version is still supported (at time of release)
301
-	 * according to: https://www.php.net/supported-versions.php
302
-	 *
303
-	 * @return array
304
-	 */
305
-	private function isPhpSupported(): array {
306
-		return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
307
-	}
308
-
309
-	/**
310
-	 * Check if the reverse proxy configuration is working as expected
311
-	 *
312
-	 * @return bool
313
-	 */
314
-	private function forwardedForHeadersWorking() {
315
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
316
-		$remoteAddress = $this->request->getHeader('REMOTE_ADDR');
317
-
318
-		if (empty($trustedProxies) && $this->request->getHeader('X-Forwarded-Host') !== '') {
319
-			return false;
320
-		}
321
-
322
-		if (\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies, true)) {
323
-			return $remoteAddress !== $this->request->getRemoteAddress();
324
-		}
325
-
326
-		// either not enabled or working correctly
327
-		return true;
328
-	}
329
-
330
-	/**
331
-	 * Checks if the correct memcache module for PHP is installed. Only
332
-	 * fails if memcached is configured and the working module is not installed.
333
-	 *
334
-	 * @return bool
335
-	 */
336
-	private function isCorrectMemcachedPHPModuleInstalled() {
337
-		if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
338
-			return true;
339
-		}
340
-
341
-		// there are two different memcached modules for PHP
342
-		// we only support memcached and not memcache
343
-		// https://code.google.com/p/memcached/wiki/PHPClientComparison
344
-		return !(!extension_loaded('memcached') && extension_loaded('memcache'));
345
-	}
346
-
347
-	/**
348
-	 * Checks if set_time_limit is not disabled.
349
-	 *
350
-	 * @return bool
351
-	 */
352
-	private function isSettimelimitAvailable() {
353
-		if (function_exists('set_time_limit')
354
-			&& strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
355
-			return true;
356
-		}
357
-
358
-		return false;
359
-	}
360
-
361
-	/**
362
-	 * @return RedirectResponse
363
-	 */
364
-	public function rescanFailedIntegrityCheck() {
365
-		$this->checker->runInstanceVerification();
366
-		return new RedirectResponse(
367
-			$this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'overview'])
368
-		);
369
-	}
370
-
371
-	/**
372
-	 * @NoCSRFRequired
373
-	 */
374
-	public function getFailedIntegrityCheckFiles(): DataDisplayResponse {
375
-		if (!$this->checker->isCodeCheckEnforced()) {
376
-			return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
377
-		}
378
-
379
-		$completeResults = $this->checker->getResults();
380
-
381
-		if (!empty($completeResults)) {
382
-			$formattedTextResponse = 'Technical information
85
+    /** @var IConfig */
86
+    private $config;
87
+    /** @var IClientService */
88
+    private $clientService;
89
+    /** @var IURLGenerator */
90
+    private $urlGenerator;
91
+    /** @var IL10N */
92
+    private $l10n;
93
+    /** @var Checker */
94
+    private $checker;
95
+    /** @var LoggerInterface */
96
+    private $logger;
97
+    /** @var EventDispatcherInterface */
98
+    private $dispatcher;
99
+    /** @var Connection */
100
+    private $db;
101
+    /** @var ILockingProvider */
102
+    private $lockingProvider;
103
+    /** @var IDateTimeFormatter */
104
+    private $dateTimeFormatter;
105
+    /** @var MemoryInfo */
106
+    private $memoryInfo;
107
+    /** @var ISecureRandom */
108
+    private $secureRandom;
109
+    /** @var IniGetWrapper */
110
+    private $iniGetWrapper;
111
+    /** @var IDBConnection */
112
+    private $connection;
113
+
114
+    public function __construct($AppName,
115
+                                IRequest $request,
116
+                                IConfig $config,
117
+                                IClientService $clientService,
118
+                                IURLGenerator $urlGenerator,
119
+                                IL10N $l10n,
120
+                                Checker $checker,
121
+                                LoggerInterface $logger,
122
+                                EventDispatcherInterface $dispatcher,
123
+                                Connection $db,
124
+                                ILockingProvider $lockingProvider,
125
+                                IDateTimeFormatter $dateTimeFormatter,
126
+                                MemoryInfo $memoryInfo,
127
+                                ISecureRandom $secureRandom,
128
+                                IniGetWrapper $iniGetWrapper,
129
+                                IDBConnection $connection) {
130
+        parent::__construct($AppName, $request);
131
+        $this->config = $config;
132
+        $this->clientService = $clientService;
133
+        $this->urlGenerator = $urlGenerator;
134
+        $this->l10n = $l10n;
135
+        $this->checker = $checker;
136
+        $this->logger = $logger;
137
+        $this->dispatcher = $dispatcher;
138
+        $this->db = $db;
139
+        $this->lockingProvider = $lockingProvider;
140
+        $this->dateTimeFormatter = $dateTimeFormatter;
141
+        $this->memoryInfo = $memoryInfo;
142
+        $this->secureRandom = $secureRandom;
143
+        $this->iniGetWrapper = $iniGetWrapper;
144
+        $this->connection = $connection;
145
+    }
146
+
147
+    /**
148
+     * Checks if the server can connect to the internet using HTTPS and HTTP
149
+     * @return bool
150
+     */
151
+    private function hasInternetConnectivityProblems(): bool {
152
+        if ($this->config->getSystemValue('has_internet_connection', true) === false) {
153
+            return false;
154
+        }
155
+
156
+        $siteArray = $this->config->getSystemValue('connectivity_check_domains', [
157
+            'www.nextcloud.com', 'www.startpage.com', 'www.eff.org', 'www.edri.org'
158
+        ]);
159
+
160
+        foreach ($siteArray as $site) {
161
+            if ($this->isSiteReachable($site)) {
162
+                return false;
163
+            }
164
+        }
165
+        return true;
166
+    }
167
+
168
+    /**
169
+     * Checks if the Nextcloud server can connect to a specific URL using both HTTPS and HTTP
170
+     * @return bool
171
+     */
172
+    private function isSiteReachable($sitename) {
173
+        $httpSiteName = 'http://' . $sitename . '/';
174
+        $httpsSiteName = 'https://' . $sitename . '/';
175
+
176
+        try {
177
+            $client = $this->clientService->newClient();
178
+            $client->get($httpSiteName);
179
+            $client->get($httpsSiteName);
180
+        } catch (\Exception $e) {
181
+            $this->logger->error('Cannot connect to: ' . $sitename, [
182
+                'app' => 'internet_connection_check',
183
+                'exception' => $e,
184
+            ]);
185
+            return false;
186
+        }
187
+        return true;
188
+    }
189
+
190
+    /**
191
+     * Checks whether a local memcache is installed or not
192
+     * @return bool
193
+     */
194
+    private function isMemcacheConfigured() {
195
+        return $this->config->getSystemValue('memcache.local', null) !== null;
196
+    }
197
+
198
+    /**
199
+     * Whether PHP can generate "secure" pseudorandom integers
200
+     *
201
+     * @return bool
202
+     */
203
+    private function isRandomnessSecure() {
204
+        try {
205
+            $this->secureRandom->generate(1);
206
+        } catch (\Exception $ex) {
207
+            return false;
208
+        }
209
+        return true;
210
+    }
211
+
212
+    /**
213
+     * Public for the sake of unit-testing
214
+     *
215
+     * @return array
216
+     */
217
+    protected function getCurlVersion() {
218
+        return curl_version();
219
+    }
220
+
221
+    /**
222
+     * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
223
+     * have multiple bugs which likely lead to problems in combination with
224
+     * functionality required by ownCloud such as SNI.
225
+     *
226
+     * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
227
+     * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
228
+     * @return string
229
+     */
230
+    private function isUsedTlsLibOutdated() {
231
+        // Don't run check when:
232
+        // 1. Server has `has_internet_connection` set to false
233
+        // 2. AppStore AND S2S is disabled
234
+        if (!$this->config->getSystemValue('has_internet_connection', true)) {
235
+            return '';
236
+        }
237
+        if (!$this->config->getSystemValue('appstoreenabled', true)
238
+            && $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
239
+            && $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
240
+            return '';
241
+        }
242
+
243
+        $versionString = $this->getCurlVersion();
244
+        if (isset($versionString['ssl_version'])) {
245
+            $versionString = $versionString['ssl_version'];
246
+        } else {
247
+            return '';
248
+        }
249
+
250
+        $features = $this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
251
+        if (!$this->config->getSystemValue('appstoreenabled', true)) {
252
+            $features = $this->l10n->t('Federated Cloud Sharing');
253
+        }
254
+
255
+        // Check if at least OpenSSL after 1.01d or 1.0.2b
256
+        if (strpos($versionString, 'OpenSSL/') === 0) {
257
+            $majorVersion = substr($versionString, 8, 5);
258
+            $patchRelease = substr($versionString, 13, 6);
259
+
260
+            if (($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
261
+                ($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
262
+                return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['OpenSSL', $versionString, $features]);
263
+            }
264
+        }
265
+
266
+        // Check if NSS and perform heuristic check
267
+        if (strpos($versionString, 'NSS/') === 0) {
268
+            try {
269
+                $firstClient = $this->clientService->newClient();
270
+                $firstClient->get('https://nextcloud.com/');
271
+
272
+                $secondClient = $this->clientService->newClient();
273
+                $secondClient->get('https://nextcloud.com/');
274
+            } catch (ClientException $e) {
275
+                if ($e->getResponse()->getStatusCode() === 400) {
276
+                    return $this->l10n->t('cURL is using an outdated %1$s version (%2$s). Please update your operating system or features such as %3$s will not work reliably.', ['NSS', $versionString, $features]);
277
+                }
278
+            } catch (\Exception $e) {
279
+                $this->logger->warning('error checking curl', [
280
+                    'app' => 'settings',
281
+                    'exception' => $e,
282
+                ]);
283
+                return $this->l10n->t('Could not determine if TLS version of cURL is outdated or not because an error happened during the HTTPS request against https://nextcloud.com. Please check the nextcloud log file for more details.');
284
+            }
285
+        }
286
+
287
+        return '';
288
+    }
289
+
290
+    /**
291
+     * Whether the version is outdated
292
+     *
293
+     * @return bool
294
+     */
295
+    protected function isPhpOutdated(): bool {
296
+        return PHP_VERSION_ID < 70300;
297
+    }
298
+
299
+    /**
300
+     * Whether the php version is still supported (at time of release)
301
+     * according to: https://www.php.net/supported-versions.php
302
+     *
303
+     * @return array
304
+     */
305
+    private function isPhpSupported(): array {
306
+        return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
307
+    }
308
+
309
+    /**
310
+     * Check if the reverse proxy configuration is working as expected
311
+     *
312
+     * @return bool
313
+     */
314
+    private function forwardedForHeadersWorking() {
315
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
316
+        $remoteAddress = $this->request->getHeader('REMOTE_ADDR');
317
+
318
+        if (empty($trustedProxies) && $this->request->getHeader('X-Forwarded-Host') !== '') {
319
+            return false;
320
+        }
321
+
322
+        if (\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies, true)) {
323
+            return $remoteAddress !== $this->request->getRemoteAddress();
324
+        }
325
+
326
+        // either not enabled or working correctly
327
+        return true;
328
+    }
329
+
330
+    /**
331
+     * Checks if the correct memcache module for PHP is installed. Only
332
+     * fails if memcached is configured and the working module is not installed.
333
+     *
334
+     * @return bool
335
+     */
336
+    private function isCorrectMemcachedPHPModuleInstalled() {
337
+        if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
338
+            return true;
339
+        }
340
+
341
+        // there are two different memcached modules for PHP
342
+        // we only support memcached and not memcache
343
+        // https://code.google.com/p/memcached/wiki/PHPClientComparison
344
+        return !(!extension_loaded('memcached') && extension_loaded('memcache'));
345
+    }
346
+
347
+    /**
348
+     * Checks if set_time_limit is not disabled.
349
+     *
350
+     * @return bool
351
+     */
352
+    private function isSettimelimitAvailable() {
353
+        if (function_exists('set_time_limit')
354
+            && strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
355
+            return true;
356
+        }
357
+
358
+        return false;
359
+    }
360
+
361
+    /**
362
+     * @return RedirectResponse
363
+     */
364
+    public function rescanFailedIntegrityCheck() {
365
+        $this->checker->runInstanceVerification();
366
+        return new RedirectResponse(
367
+            $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'overview'])
368
+        );
369
+    }
370
+
371
+    /**
372
+     * @NoCSRFRequired
373
+     */
374
+    public function getFailedIntegrityCheckFiles(): DataDisplayResponse {
375
+        if (!$this->checker->isCodeCheckEnforced()) {
376
+            return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
377
+        }
378
+
379
+        $completeResults = $this->checker->getResults();
380
+
381
+        if (!empty($completeResults)) {
382
+            $formattedTextResponse = 'Technical information
383 383
 =====================
384 384
 The following list covers which files have failed the integrity check. Please read
385 385
 the previous linked documentation to learn more about the errors and how to fix
@@ -388,389 +388,389 @@  discard block
 block discarded – undo
388 388
 Results
389 389
 =======
390 390
 ';
391
-			foreach ($completeResults as $context => $contextResult) {
392
-				$formattedTextResponse .= "- $context\n";
393
-
394
-				foreach ($contextResult as $category => $result) {
395
-					$formattedTextResponse .= "\t- $category\n";
396
-					if ($category !== 'EXCEPTION') {
397
-						foreach ($result as $key => $results) {
398
-							$formattedTextResponse .= "\t\t- $key\n";
399
-						}
400
-					} else {
401
-						foreach ($result as $key => $results) {
402
-							$formattedTextResponse .= "\t\t- $results\n";
403
-						}
404
-					}
405
-				}
406
-			}
407
-
408
-			$formattedTextResponse .= '
391
+            foreach ($completeResults as $context => $contextResult) {
392
+                $formattedTextResponse .= "- $context\n";
393
+
394
+                foreach ($contextResult as $category => $result) {
395
+                    $formattedTextResponse .= "\t- $category\n";
396
+                    if ($category !== 'EXCEPTION') {
397
+                        foreach ($result as $key => $results) {
398
+                            $formattedTextResponse .= "\t\t- $key\n";
399
+                        }
400
+                    } else {
401
+                        foreach ($result as $key => $results) {
402
+                            $formattedTextResponse .= "\t\t- $results\n";
403
+                        }
404
+                    }
405
+                }
406
+            }
407
+
408
+            $formattedTextResponse .= '
409 409
 Raw output
410 410
 ==========
411 411
 ';
412
-			$formattedTextResponse .= print_r($completeResults, true);
413
-		} else {
414
-			$formattedTextResponse = 'No errors have been found.';
415
-		}
416
-
417
-
418
-		return new DataDisplayResponse(
419
-			$formattedTextResponse,
420
-			Http::STATUS_OK,
421
-			[
422
-				'Content-Type' => 'text/plain',
423
-			]
424
-		);
425
-	}
426
-
427
-	/**
428
-	 * Checks whether a PHP opcache is properly set up
429
-	 * @return bool
430
-	 */
431
-	protected function isOpcacheProperlySetup() {
432
-		if (!$this->iniGetWrapper->getBool('opcache.enable')) {
433
-			return false;
434
-		}
435
-
436
-		if (!$this->iniGetWrapper->getBool('opcache.save_comments')) {
437
-			return false;
438
-		}
439
-
440
-		if ($this->iniGetWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
441
-			return false;
442
-		}
443
-
444
-		if ($this->iniGetWrapper->getNumeric('opcache.memory_consumption') < 128) {
445
-			return false;
446
-		}
447
-
448
-		if ($this->iniGetWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
449
-			return false;
450
-		}
451
-
452
-		return true;
453
-	}
454
-
455
-	/**
456
-	 * Check if the required FreeType functions are present
457
-	 * @return bool
458
-	 */
459
-	protected function hasFreeTypeSupport() {
460
-		return function_exists('imagettfbbox') && function_exists('imagettftext');
461
-	}
462
-
463
-	protected function hasMissingIndexes(): array {
464
-		$indexInfo = new MissingIndexInformation();
465
-		// Dispatch event so apps can also hint for pending index updates if needed
466
-		$event = new GenericEvent($indexInfo);
467
-		$this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_INDEXES_EVENT, $event);
468
-
469
-		return $indexInfo->getListOfMissingIndexes();
470
-	}
471
-
472
-	protected function hasMissingPrimaryKeys(): array {
473
-		$info = new MissingPrimaryKeyInformation();
474
-		// Dispatch event so apps can also hint for pending index updates if needed
475
-		$event = new GenericEvent($info);
476
-		$this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_PRIMARY_KEYS_EVENT, $event);
477
-
478
-		return $info->getListOfMissingPrimaryKeys();
479
-	}
480
-
481
-	protected function hasMissingColumns(): array {
482
-		$indexInfo = new MissingColumnInformation();
483
-		// Dispatch event so apps can also hint for pending index updates if needed
484
-		$event = new GenericEvent($indexInfo);
485
-		$this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_COLUMNS_EVENT, $event);
486
-
487
-		return $indexInfo->getListOfMissingColumns();
488
-	}
489
-
490
-	protected function isSqliteUsed() {
491
-		return strpos($this->config->getSystemValue('dbtype'), 'sqlite') !== false;
492
-	}
493
-
494
-	protected function isReadOnlyConfig(): bool {
495
-		return \OC_Helper::isReadOnlyConfigEnabled();
496
-	}
497
-
498
-	protected function hasValidTransactionIsolationLevel(): bool {
499
-		try {
500
-			if ($this->db->getDatabasePlatform() instanceof SqlitePlatform) {
501
-				return true;
502
-			}
503
-
504
-			return $this->db->getTransactionIsolation() === TransactionIsolationLevel::READ_COMMITTED;
505
-		} catch (Exception $e) {
506
-			// ignore
507
-		}
508
-
509
-		return true;
510
-	}
511
-
512
-	protected function hasFileinfoInstalled(): bool {
513
-		return \OC_Util::fileInfoLoaded();
514
-	}
515
-
516
-	protected function hasWorkingFileLocking(): bool {
517
-		return !($this->lockingProvider instanceof NoopLockingProvider);
518
-	}
519
-
520
-	protected function getSuggestedOverwriteCliURL(): string {
521
-		$suggestedOverwriteCliUrl = '';
522
-		if ($this->config->getSystemValue('overwrite.cli.url', '') === '') {
523
-			$suggestedOverwriteCliUrl = $this->request->getServerProtocol() . '://' . $this->request->getInsecureServerHost() . \OC::$WEBROOT;
524
-			if (!$this->config->getSystemValue('config_is_read_only', false)) {
525
-				// Set the overwrite URL when it was not set yet.
526
-				$this->config->setSystemValue('overwrite.cli.url', $suggestedOverwriteCliUrl);
527
-				$suggestedOverwriteCliUrl = '';
528
-			}
529
-		}
530
-		return $suggestedOverwriteCliUrl;
531
-	}
532
-
533
-	protected function getLastCronInfo(): array {
534
-		$lastCronRun = $this->config->getAppValue('core', 'lastcron', 0);
535
-		return [
536
-			'diffInSeconds' => time() - $lastCronRun,
537
-			'relativeTime' => $this->dateTimeFormatter->formatTimeSpan($lastCronRun),
538
-			'backgroundJobsUrl' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'server']) . '#backgroundjobs',
539
-		];
540
-	}
541
-
542
-	protected function getCronErrors() {
543
-		$errors = json_decode($this->config->getAppValue('core', 'cronErrors', ''), true);
544
-
545
-		if (is_array($errors)) {
546
-			return $errors;
547
-		}
548
-
549
-		return [];
550
-	}
551
-
552
-	protected function hasOpcacheLoaded(): bool {
553
-		return extension_loaded('Zend OPcache');
554
-	}
555
-
556
-	/**
557
-	 * Iterates through the configured app roots and
558
-	 * tests if the subdirectories are owned by the same user than the current user.
559
-	 *
560
-	 * @return array
561
-	 */
562
-	protected function getAppDirsWithDifferentOwner(): array {
563
-		$currentUser = posix_getuid();
564
-		$appDirsWithDifferentOwner = [[]];
565
-
566
-		foreach (OC::$APPSROOTS as $appRoot) {
567
-			if ($appRoot['writable'] === true) {
568
-				$appDirsWithDifferentOwner[] = $this->getAppDirsWithDifferentOwnerForAppRoot($currentUser, $appRoot);
569
-			}
570
-		}
571
-
572
-		$appDirsWithDifferentOwner = array_merge(...$appDirsWithDifferentOwner);
573
-		sort($appDirsWithDifferentOwner);
574
-
575
-		return $appDirsWithDifferentOwner;
576
-	}
577
-
578
-	/**
579
-	 * Tests if the directories for one apps directory are writable by the current user.
580
-	 *
581
-	 * @param int $currentUser The current user
582
-	 * @param array $appRoot The app root config
583
-	 * @return string[] The none writable directory paths inside the app root
584
-	 */
585
-	private function getAppDirsWithDifferentOwnerForAppRoot(int $currentUser, array $appRoot): array {
586
-		$appDirsWithDifferentOwner = [];
587
-		$appsPath = $appRoot['path'];
588
-		$appsDir = new DirectoryIterator($appRoot['path']);
589
-
590
-		foreach ($appsDir as $fileInfo) {
591
-			if ($fileInfo->isDir() && !$fileInfo->isDot()) {
592
-				$absAppPath = $appsPath . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
593
-				$appDirUser = fileowner($absAppPath);
594
-				if ($appDirUser !== $currentUser) {
595
-					$appDirsWithDifferentOwner[] = $absAppPath;
596
-				}
597
-			}
598
-		}
599
-
600
-		return $appDirsWithDifferentOwner;
601
-	}
602
-
603
-	/**
604
-	 * Checks for potential PHP modules that would improve the instance
605
-	 *
606
-	 * @return string[] A list of PHP modules that is recommended
607
-	 */
608
-	protected function hasRecommendedPHPModules(): array {
609
-		$recommendedPHPModules = [];
610
-
611
-		if (!extension_loaded('intl')) {
612
-			$recommendedPHPModules[] = 'intl';
613
-		}
614
-
615
-		if (!extension_loaded('bcmath')) {
616
-			$recommendedPHPModules[] = 'bcmath';
617
-		}
618
-
619
-		if (!extension_loaded('gmp')) {
620
-			$recommendedPHPModules[] = 'gmp';
621
-		}
622
-
623
-		if ($this->config->getAppValue('theming', 'enabled', 'no') === 'yes') {
624
-			if (!extension_loaded('imagick')) {
625
-				$recommendedPHPModules[] = 'imagick';
626
-			}
627
-		}
628
-
629
-		return $recommendedPHPModules;
630
-	}
631
-
632
-	protected function isMysqlUsedWithoutUTF8MB4(): bool {
633
-		return ($this->config->getSystemValue('dbtype', 'sqlite') === 'mysql') && ($this->config->getSystemValue('mysql.utf8mb4', false) === false);
634
-	}
635
-
636
-	protected function hasBigIntConversionPendingColumns(): array {
637
-		// copy of ConvertFilecacheBigInt::getColumnsByTable()
638
-		$tables = [
639
-			'activity' => ['activity_id', 'object_id'],
640
-			'activity_mq' => ['mail_id'],
641
-			'authtoken' => ['id'],
642
-			'bruteforce_attempts' => ['id'],
643
-			'federated_reshares' => ['share_id'],
644
-			'filecache' => ['fileid', 'storage', 'parent', 'mimetype', 'mimepart', 'mtime', 'storage_mtime'],
645
-			'filecache_extended' => ['fileid'],
646
-			'file_locks' => ['id'],
647
-			'jobs' => ['id'],
648
-			'mimetypes' => ['id'],
649
-			'mounts' => ['id', 'storage_id', 'root_id', 'mount_id'],
650
-			'share_external' => ['id', 'parent'],
651
-			'storages' => ['numeric_id'],
652
-		];
653
-
654
-		$schema = new SchemaWrapper($this->db);
655
-		$isSqlite = $this->db->getDatabasePlatform() instanceof SqlitePlatform;
656
-		$pendingColumns = [];
657
-
658
-		foreach ($tables as $tableName => $columns) {
659
-			if (!$schema->hasTable($tableName)) {
660
-				continue;
661
-			}
662
-
663
-			$table = $schema->getTable($tableName);
664
-			foreach ($columns as $columnName) {
665
-				$column = $table->getColumn($columnName);
666
-				$isAutoIncrement = $column->getAutoincrement();
667
-				$isAutoIncrementOnSqlite = $isSqlite && $isAutoIncrement;
668
-				if ($column->getType()->getName() !== Types::BIGINT && !$isAutoIncrementOnSqlite) {
669
-					$pendingColumns[] = $tableName . '.' . $columnName;
670
-				}
671
-			}
672
-		}
673
-
674
-		return $pendingColumns;
675
-	}
676
-
677
-	protected function isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed(): bool {
678
-		$objectStore = $this->config->getSystemValue('objectstore', null);
679
-		$objectStoreMultibucket = $this->config->getSystemValue('objectstore_multibucket', null);
680
-
681
-		if (!isset($objectStoreMultibucket) && !isset($objectStore)) {
682
-			return true;
683
-		}
684
-
685
-		if (isset($objectStoreMultibucket['class']) && $objectStoreMultibucket['class'] !== 'OC\\Files\\ObjectStore\\S3') {
686
-			return true;
687
-		}
688
-
689
-		if (isset($objectStore['class']) && $objectStore['class'] !== 'OC\\Files\\ObjectStore\\S3') {
690
-			return true;
691
-		}
692
-
693
-		$tempPath = sys_get_temp_dir();
694
-		if (!is_dir($tempPath)) {
695
-			$this->logger->error('Error while checking the temporary PHP path - it was not properly set to a directory. value: ' . $tempPath);
696
-			return false;
697
-		}
698
-		$freeSpaceInTemp = disk_free_space($tempPath);
699
-		if ($freeSpaceInTemp === false) {
700
-			$this->logger->error('Error while checking the available disk space of temporary PHP path - no free disk space returned. temporary path: ' . $tempPath);
701
-			return false;
702
-		}
703
-
704
-		$freeSpaceInTempInGB = $freeSpaceInTemp / 1024 / 1024 / 1024;
705
-		if ($freeSpaceInTempInGB > 50) {
706
-			return true;
707
-		}
708
-
709
-		$this->logger->warning('Checking the available space in the temporary path resulted in ' . round($freeSpaceInTempInGB, 1) . ' GB instead of the recommended 50GB. Path: ' . $tempPath);
710
-		return false;
711
-	}
712
-
713
-	protected function imageMagickLacksSVGSupport(): bool {
714
-		return extension_loaded('imagick') && count(\Imagick::queryFormats('SVG')) === 0;
715
-	}
716
-
717
-	/**
718
-	 * @return DataResponse
719
-	 */
720
-	public function check() {
721
-		$phpDefaultCharset = new PhpDefaultCharset();
722
-		$phpOutputBuffering = new PhpOutputBuffering();
723
-		$legacySSEKeyFormat = new LegacySSEKeyFormat($this->l10n, $this->config, $this->urlGenerator);
724
-		$checkUserCertificates = new CheckUserCertificates($this->l10n, $this->config, $this->urlGenerator);
725
-		$supportedDatabases = new SupportedDatabase($this->l10n, $this->connection);
726
-
727
-		return new DataResponse(
728
-			[
729
-				'isGetenvServerWorking' => !empty(getenv('PATH')),
730
-				'isReadOnlyConfig' => $this->isReadOnlyConfig(),
731
-				'hasValidTransactionIsolationLevel' => $this->hasValidTransactionIsolationLevel(),
732
-				'hasFileinfoInstalled' => $this->hasFileinfoInstalled(),
733
-				'hasWorkingFileLocking' => $this->hasWorkingFileLocking(),
734
-				'suggestedOverwriteCliURL' => $this->getSuggestedOverwriteCliURL(),
735
-				'cronInfo' => $this->getLastCronInfo(),
736
-				'cronErrors' => $this->getCronErrors(),
737
-				'serverHasInternetConnectionProblems' => $this->hasInternetConnectivityProblems(),
738
-				'isMemcacheConfigured' => $this->isMemcacheConfigured(),
739
-				'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
740
-				'isRandomnessSecure' => $this->isRandomnessSecure(),
741
-				'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
742
-				'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
743
-				'phpSupported' => $this->isPhpSupported(),
744
-				'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
745
-				'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
746
-				'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
747
-				'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
748
-				'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
749
-				'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
750
-				'hasOpcacheLoaded' => $this->hasOpcacheLoaded(),
751
-				'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
752
-				'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
753
-				'hasFreeTypeSupport' => $this->hasFreeTypeSupport(),
754
-				'missingPrimaryKeys' => $this->hasMissingPrimaryKeys(),
755
-				'missingIndexes' => $this->hasMissingIndexes(),
756
-				'missingColumns' => $this->hasMissingColumns(),
757
-				'isSqliteUsed' => $this->isSqliteUsed(),
758
-				'databaseConversionDocumentation' => $this->urlGenerator->linkToDocs('admin-db-conversion'),
759
-				'isMemoryLimitSufficient' => $this->memoryInfo->isMemoryLimitSufficient(),
760
-				'appDirsWithDifferentOwner' => $this->getAppDirsWithDifferentOwner(),
761
-				'recommendedPHPModules' => $this->hasRecommendedPHPModules(),
762
-				'pendingBigIntConversionColumns' => $this->hasBigIntConversionPendingColumns(),
763
-				'isMysqlUsedWithoutUTF8MB4' => $this->isMysqlUsedWithoutUTF8MB4(),
764
-				'isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed' => $this->isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed(),
765
-				'reverseProxyGeneratedURL' => $this->urlGenerator->getAbsoluteURL('index.php'),
766
-				'imageMagickLacksSVGSupport' => $this->imageMagickLacksSVGSupport(),
767
-				PhpDefaultCharset::class => ['pass' => $phpDefaultCharset->run(), 'description' => $phpDefaultCharset->description(), 'severity' => $phpDefaultCharset->severity()],
768
-				PhpOutputBuffering::class => ['pass' => $phpOutputBuffering->run(), 'description' => $phpOutputBuffering->description(), 'severity' => $phpOutputBuffering->severity()],
769
-				LegacySSEKeyFormat::class => ['pass' => $legacySSEKeyFormat->run(), 'description' => $legacySSEKeyFormat->description(), 'severity' => $legacySSEKeyFormat->severity(), 'linkToDocumentation' => $legacySSEKeyFormat->linkToDocumentation()],
770
-				CheckUserCertificates::class => ['pass' => $checkUserCertificates->run(), 'description' => $checkUserCertificates->description(), 'severity' => $checkUserCertificates->severity(), 'elements' => $checkUserCertificates->elements()],
771
-				'isDefaultPhoneRegionSet' => $this->config->getSystemValueString('default_phone_region', '') !== '',
772
-				SupportedDatabase::class => ['pass' => $supportedDatabases->run(), 'description' => $supportedDatabases->description(), 'severity' => $supportedDatabases->severity()],
773
-			]
774
-		);
775
-	}
412
+            $formattedTextResponse .= print_r($completeResults, true);
413
+        } else {
414
+            $formattedTextResponse = 'No errors have been found.';
415
+        }
416
+
417
+
418
+        return new DataDisplayResponse(
419
+            $formattedTextResponse,
420
+            Http::STATUS_OK,
421
+            [
422
+                'Content-Type' => 'text/plain',
423
+            ]
424
+        );
425
+    }
426
+
427
+    /**
428
+     * Checks whether a PHP opcache is properly set up
429
+     * @return bool
430
+     */
431
+    protected function isOpcacheProperlySetup() {
432
+        if (!$this->iniGetWrapper->getBool('opcache.enable')) {
433
+            return false;
434
+        }
435
+
436
+        if (!$this->iniGetWrapper->getBool('opcache.save_comments')) {
437
+            return false;
438
+        }
439
+
440
+        if ($this->iniGetWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
441
+            return false;
442
+        }
443
+
444
+        if ($this->iniGetWrapper->getNumeric('opcache.memory_consumption') < 128) {
445
+            return false;
446
+        }
447
+
448
+        if ($this->iniGetWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
449
+            return false;
450
+        }
451
+
452
+        return true;
453
+    }
454
+
455
+    /**
456
+     * Check if the required FreeType functions are present
457
+     * @return bool
458
+     */
459
+    protected function hasFreeTypeSupport() {
460
+        return function_exists('imagettfbbox') && function_exists('imagettftext');
461
+    }
462
+
463
+    protected function hasMissingIndexes(): array {
464
+        $indexInfo = new MissingIndexInformation();
465
+        // Dispatch event so apps can also hint for pending index updates if needed
466
+        $event = new GenericEvent($indexInfo);
467
+        $this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_INDEXES_EVENT, $event);
468
+
469
+        return $indexInfo->getListOfMissingIndexes();
470
+    }
471
+
472
+    protected function hasMissingPrimaryKeys(): array {
473
+        $info = new MissingPrimaryKeyInformation();
474
+        // Dispatch event so apps can also hint for pending index updates if needed
475
+        $event = new GenericEvent($info);
476
+        $this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_PRIMARY_KEYS_EVENT, $event);
477
+
478
+        return $info->getListOfMissingPrimaryKeys();
479
+    }
480
+
481
+    protected function hasMissingColumns(): array {
482
+        $indexInfo = new MissingColumnInformation();
483
+        // Dispatch event so apps can also hint for pending index updates if needed
484
+        $event = new GenericEvent($indexInfo);
485
+        $this->dispatcher->dispatch(IDBConnection::CHECK_MISSING_COLUMNS_EVENT, $event);
486
+
487
+        return $indexInfo->getListOfMissingColumns();
488
+    }
489
+
490
+    protected function isSqliteUsed() {
491
+        return strpos($this->config->getSystemValue('dbtype'), 'sqlite') !== false;
492
+    }
493
+
494
+    protected function isReadOnlyConfig(): bool {
495
+        return \OC_Helper::isReadOnlyConfigEnabled();
496
+    }
497
+
498
+    protected function hasValidTransactionIsolationLevel(): bool {
499
+        try {
500
+            if ($this->db->getDatabasePlatform() instanceof SqlitePlatform) {
501
+                return true;
502
+            }
503
+
504
+            return $this->db->getTransactionIsolation() === TransactionIsolationLevel::READ_COMMITTED;
505
+        } catch (Exception $e) {
506
+            // ignore
507
+        }
508
+
509
+        return true;
510
+    }
511
+
512
+    protected function hasFileinfoInstalled(): bool {
513
+        return \OC_Util::fileInfoLoaded();
514
+    }
515
+
516
+    protected function hasWorkingFileLocking(): bool {
517
+        return !($this->lockingProvider instanceof NoopLockingProvider);
518
+    }
519
+
520
+    protected function getSuggestedOverwriteCliURL(): string {
521
+        $suggestedOverwriteCliUrl = '';
522
+        if ($this->config->getSystemValue('overwrite.cli.url', '') === '') {
523
+            $suggestedOverwriteCliUrl = $this->request->getServerProtocol() . '://' . $this->request->getInsecureServerHost() . \OC::$WEBROOT;
524
+            if (!$this->config->getSystemValue('config_is_read_only', false)) {
525
+                // Set the overwrite URL when it was not set yet.
526
+                $this->config->setSystemValue('overwrite.cli.url', $suggestedOverwriteCliUrl);
527
+                $suggestedOverwriteCliUrl = '';
528
+            }
529
+        }
530
+        return $suggestedOverwriteCliUrl;
531
+    }
532
+
533
+    protected function getLastCronInfo(): array {
534
+        $lastCronRun = $this->config->getAppValue('core', 'lastcron', 0);
535
+        return [
536
+            'diffInSeconds' => time() - $lastCronRun,
537
+            'relativeTime' => $this->dateTimeFormatter->formatTimeSpan($lastCronRun),
538
+            'backgroundJobsUrl' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'server']) . '#backgroundjobs',
539
+        ];
540
+    }
541
+
542
+    protected function getCronErrors() {
543
+        $errors = json_decode($this->config->getAppValue('core', 'cronErrors', ''), true);
544
+
545
+        if (is_array($errors)) {
546
+            return $errors;
547
+        }
548
+
549
+        return [];
550
+    }
551
+
552
+    protected function hasOpcacheLoaded(): bool {
553
+        return extension_loaded('Zend OPcache');
554
+    }
555
+
556
+    /**
557
+     * Iterates through the configured app roots and
558
+     * tests if the subdirectories are owned by the same user than the current user.
559
+     *
560
+     * @return array
561
+     */
562
+    protected function getAppDirsWithDifferentOwner(): array {
563
+        $currentUser = posix_getuid();
564
+        $appDirsWithDifferentOwner = [[]];
565
+
566
+        foreach (OC::$APPSROOTS as $appRoot) {
567
+            if ($appRoot['writable'] === true) {
568
+                $appDirsWithDifferentOwner[] = $this->getAppDirsWithDifferentOwnerForAppRoot($currentUser, $appRoot);
569
+            }
570
+        }
571
+
572
+        $appDirsWithDifferentOwner = array_merge(...$appDirsWithDifferentOwner);
573
+        sort($appDirsWithDifferentOwner);
574
+
575
+        return $appDirsWithDifferentOwner;
576
+    }
577
+
578
+    /**
579
+     * Tests if the directories for one apps directory are writable by the current user.
580
+     *
581
+     * @param int $currentUser The current user
582
+     * @param array $appRoot The app root config
583
+     * @return string[] The none writable directory paths inside the app root
584
+     */
585
+    private function getAppDirsWithDifferentOwnerForAppRoot(int $currentUser, array $appRoot): array {
586
+        $appDirsWithDifferentOwner = [];
587
+        $appsPath = $appRoot['path'];
588
+        $appsDir = new DirectoryIterator($appRoot['path']);
589
+
590
+        foreach ($appsDir as $fileInfo) {
591
+            if ($fileInfo->isDir() && !$fileInfo->isDot()) {
592
+                $absAppPath = $appsPath . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
593
+                $appDirUser = fileowner($absAppPath);
594
+                if ($appDirUser !== $currentUser) {
595
+                    $appDirsWithDifferentOwner[] = $absAppPath;
596
+                }
597
+            }
598
+        }
599
+
600
+        return $appDirsWithDifferentOwner;
601
+    }
602
+
603
+    /**
604
+     * Checks for potential PHP modules that would improve the instance
605
+     *
606
+     * @return string[] A list of PHP modules that is recommended
607
+     */
608
+    protected function hasRecommendedPHPModules(): array {
609
+        $recommendedPHPModules = [];
610
+
611
+        if (!extension_loaded('intl')) {
612
+            $recommendedPHPModules[] = 'intl';
613
+        }
614
+
615
+        if (!extension_loaded('bcmath')) {
616
+            $recommendedPHPModules[] = 'bcmath';
617
+        }
618
+
619
+        if (!extension_loaded('gmp')) {
620
+            $recommendedPHPModules[] = 'gmp';
621
+        }
622
+
623
+        if ($this->config->getAppValue('theming', 'enabled', 'no') === 'yes') {
624
+            if (!extension_loaded('imagick')) {
625
+                $recommendedPHPModules[] = 'imagick';
626
+            }
627
+        }
628
+
629
+        return $recommendedPHPModules;
630
+    }
631
+
632
+    protected function isMysqlUsedWithoutUTF8MB4(): bool {
633
+        return ($this->config->getSystemValue('dbtype', 'sqlite') === 'mysql') && ($this->config->getSystemValue('mysql.utf8mb4', false) === false);
634
+    }
635
+
636
+    protected function hasBigIntConversionPendingColumns(): array {
637
+        // copy of ConvertFilecacheBigInt::getColumnsByTable()
638
+        $tables = [
639
+            'activity' => ['activity_id', 'object_id'],
640
+            'activity_mq' => ['mail_id'],
641
+            'authtoken' => ['id'],
642
+            'bruteforce_attempts' => ['id'],
643
+            'federated_reshares' => ['share_id'],
644
+            'filecache' => ['fileid', 'storage', 'parent', 'mimetype', 'mimepart', 'mtime', 'storage_mtime'],
645
+            'filecache_extended' => ['fileid'],
646
+            'file_locks' => ['id'],
647
+            'jobs' => ['id'],
648
+            'mimetypes' => ['id'],
649
+            'mounts' => ['id', 'storage_id', 'root_id', 'mount_id'],
650
+            'share_external' => ['id', 'parent'],
651
+            'storages' => ['numeric_id'],
652
+        ];
653
+
654
+        $schema = new SchemaWrapper($this->db);
655
+        $isSqlite = $this->db->getDatabasePlatform() instanceof SqlitePlatform;
656
+        $pendingColumns = [];
657
+
658
+        foreach ($tables as $tableName => $columns) {
659
+            if (!$schema->hasTable($tableName)) {
660
+                continue;
661
+            }
662
+
663
+            $table = $schema->getTable($tableName);
664
+            foreach ($columns as $columnName) {
665
+                $column = $table->getColumn($columnName);
666
+                $isAutoIncrement = $column->getAutoincrement();
667
+                $isAutoIncrementOnSqlite = $isSqlite && $isAutoIncrement;
668
+                if ($column->getType()->getName() !== Types::BIGINT && !$isAutoIncrementOnSqlite) {
669
+                    $pendingColumns[] = $tableName . '.' . $columnName;
670
+                }
671
+            }
672
+        }
673
+
674
+        return $pendingColumns;
675
+    }
676
+
677
+    protected function isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed(): bool {
678
+        $objectStore = $this->config->getSystemValue('objectstore', null);
679
+        $objectStoreMultibucket = $this->config->getSystemValue('objectstore_multibucket', null);
680
+
681
+        if (!isset($objectStoreMultibucket) && !isset($objectStore)) {
682
+            return true;
683
+        }
684
+
685
+        if (isset($objectStoreMultibucket['class']) && $objectStoreMultibucket['class'] !== 'OC\\Files\\ObjectStore\\S3') {
686
+            return true;
687
+        }
688
+
689
+        if (isset($objectStore['class']) && $objectStore['class'] !== 'OC\\Files\\ObjectStore\\S3') {
690
+            return true;
691
+        }
692
+
693
+        $tempPath = sys_get_temp_dir();
694
+        if (!is_dir($tempPath)) {
695
+            $this->logger->error('Error while checking the temporary PHP path - it was not properly set to a directory. value: ' . $tempPath);
696
+            return false;
697
+        }
698
+        $freeSpaceInTemp = disk_free_space($tempPath);
699
+        if ($freeSpaceInTemp === false) {
700
+            $this->logger->error('Error while checking the available disk space of temporary PHP path - no free disk space returned. temporary path: ' . $tempPath);
701
+            return false;
702
+        }
703
+
704
+        $freeSpaceInTempInGB = $freeSpaceInTemp / 1024 / 1024 / 1024;
705
+        if ($freeSpaceInTempInGB > 50) {
706
+            return true;
707
+        }
708
+
709
+        $this->logger->warning('Checking the available space in the temporary path resulted in ' . round($freeSpaceInTempInGB, 1) . ' GB instead of the recommended 50GB. Path: ' . $tempPath);
710
+        return false;
711
+    }
712
+
713
+    protected function imageMagickLacksSVGSupport(): bool {
714
+        return extension_loaded('imagick') && count(\Imagick::queryFormats('SVG')) === 0;
715
+    }
716
+
717
+    /**
718
+     * @return DataResponse
719
+     */
720
+    public function check() {
721
+        $phpDefaultCharset = new PhpDefaultCharset();
722
+        $phpOutputBuffering = new PhpOutputBuffering();
723
+        $legacySSEKeyFormat = new LegacySSEKeyFormat($this->l10n, $this->config, $this->urlGenerator);
724
+        $checkUserCertificates = new CheckUserCertificates($this->l10n, $this->config, $this->urlGenerator);
725
+        $supportedDatabases = new SupportedDatabase($this->l10n, $this->connection);
726
+
727
+        return new DataResponse(
728
+            [
729
+                'isGetenvServerWorking' => !empty(getenv('PATH')),
730
+                'isReadOnlyConfig' => $this->isReadOnlyConfig(),
731
+                'hasValidTransactionIsolationLevel' => $this->hasValidTransactionIsolationLevel(),
732
+                'hasFileinfoInstalled' => $this->hasFileinfoInstalled(),
733
+                'hasWorkingFileLocking' => $this->hasWorkingFileLocking(),
734
+                'suggestedOverwriteCliURL' => $this->getSuggestedOverwriteCliURL(),
735
+                'cronInfo' => $this->getLastCronInfo(),
736
+                'cronErrors' => $this->getCronErrors(),
737
+                'serverHasInternetConnectionProblems' => $this->hasInternetConnectivityProblems(),
738
+                'isMemcacheConfigured' => $this->isMemcacheConfigured(),
739
+                'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
740
+                'isRandomnessSecure' => $this->isRandomnessSecure(),
741
+                'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
742
+                'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
743
+                'phpSupported' => $this->isPhpSupported(),
744
+                'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
745
+                'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
746
+                'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
747
+                'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
748
+                'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
749
+                'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
750
+                'hasOpcacheLoaded' => $this->hasOpcacheLoaded(),
751
+                'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
752
+                'isSettimelimitAvailable' => $this->isSettimelimitAvailable(),
753
+                'hasFreeTypeSupport' => $this->hasFreeTypeSupport(),
754
+                'missingPrimaryKeys' => $this->hasMissingPrimaryKeys(),
755
+                'missingIndexes' => $this->hasMissingIndexes(),
756
+                'missingColumns' => $this->hasMissingColumns(),
757
+                'isSqliteUsed' => $this->isSqliteUsed(),
758
+                'databaseConversionDocumentation' => $this->urlGenerator->linkToDocs('admin-db-conversion'),
759
+                'isMemoryLimitSufficient' => $this->memoryInfo->isMemoryLimitSufficient(),
760
+                'appDirsWithDifferentOwner' => $this->getAppDirsWithDifferentOwner(),
761
+                'recommendedPHPModules' => $this->hasRecommendedPHPModules(),
762
+                'pendingBigIntConversionColumns' => $this->hasBigIntConversionPendingColumns(),
763
+                'isMysqlUsedWithoutUTF8MB4' => $this->isMysqlUsedWithoutUTF8MB4(),
764
+                'isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed' => $this->isEnoughTempSpaceAvailableIfS3PrimaryStorageIsUsed(),
765
+                'reverseProxyGeneratedURL' => $this->urlGenerator->getAbsoluteURL('index.php'),
766
+                'imageMagickLacksSVGSupport' => $this->imageMagickLacksSVGSupport(),
767
+                PhpDefaultCharset::class => ['pass' => $phpDefaultCharset->run(), 'description' => $phpDefaultCharset->description(), 'severity' => $phpDefaultCharset->severity()],
768
+                PhpOutputBuffering::class => ['pass' => $phpOutputBuffering->run(), 'description' => $phpOutputBuffering->description(), 'severity' => $phpOutputBuffering->severity()],
769
+                LegacySSEKeyFormat::class => ['pass' => $legacySSEKeyFormat->run(), 'description' => $legacySSEKeyFormat->description(), 'severity' => $legacySSEKeyFormat->severity(), 'linkToDocumentation' => $legacySSEKeyFormat->linkToDocumentation()],
770
+                CheckUserCertificates::class => ['pass' => $checkUserCertificates->run(), 'description' => $checkUserCertificates->description(), 'severity' => $checkUserCertificates->severity(), 'elements' => $checkUserCertificates->elements()],
771
+                'isDefaultPhoneRegionSet' => $this->config->getSystemValueString('default_phone_region', '') !== '',
772
+                SupportedDatabase::class => ['pass' => $supportedDatabases->run(), 'description' => $supportedDatabases->description(), 'severity' => $supportedDatabases->severity()],
773
+            ]
774
+        );
775
+    }
776 776
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -170,15 +170,15 @@  discard block
 block discarded – undo
170 170
 	 * @return bool
171 171
 	 */
172 172
 	private function isSiteReachable($sitename) {
173
-		$httpSiteName = 'http://' . $sitename . '/';
174
-		$httpsSiteName = 'https://' . $sitename . '/';
173
+		$httpSiteName = 'http://'.$sitename.'/';
174
+		$httpsSiteName = 'https://'.$sitename.'/';
175 175
 
176 176
 		try {
177 177
 			$client = $this->clientService->newClient();
178 178
 			$client->get($httpSiteName);
179 179
 			$client->get($httpsSiteName);
180 180
 		} catch (\Exception $e) {
181
-			$this->logger->error('Cannot connect to: ' . $sitename, [
181
+			$this->logger->error('Cannot connect to: '.$sitename, [
182 182
 				'app' => 'internet_connection_check',
183 183
 				'exception' => $e,
184 184
 			]);
@@ -520,7 +520,7 @@  discard block
 block discarded – undo
520 520
 	protected function getSuggestedOverwriteCliURL(): string {
521 521
 		$suggestedOverwriteCliUrl = '';
522 522
 		if ($this->config->getSystemValue('overwrite.cli.url', '') === '') {
523
-			$suggestedOverwriteCliUrl = $this->request->getServerProtocol() . '://' . $this->request->getInsecureServerHost() . \OC::$WEBROOT;
523
+			$suggestedOverwriteCliUrl = $this->request->getServerProtocol().'://'.$this->request->getInsecureServerHost().\OC::$WEBROOT;
524 524
 			if (!$this->config->getSystemValue('config_is_read_only', false)) {
525 525
 				// Set the overwrite URL when it was not set yet.
526 526
 				$this->config->setSystemValue('overwrite.cli.url', $suggestedOverwriteCliUrl);
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
 		return [
536 536
 			'diffInSeconds' => time() - $lastCronRun,
537 537
 			'relativeTime' => $this->dateTimeFormatter->formatTimeSpan($lastCronRun),
538
-			'backgroundJobsUrl' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'server']) . '#backgroundjobs',
538
+			'backgroundJobsUrl' => $this->urlGenerator->linkToRoute('settings.AdminSettings.index', ['section' => 'server']).'#backgroundjobs',
539 539
 		];
540 540
 	}
541 541
 
@@ -589,7 +589,7 @@  discard block
 block discarded – undo
589 589
 
590 590
 		foreach ($appsDir as $fileInfo) {
591 591
 			if ($fileInfo->isDir() && !$fileInfo->isDot()) {
592
-				$absAppPath = $appsPath . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
592
+				$absAppPath = $appsPath.DIRECTORY_SEPARATOR.$fileInfo->getFilename();
593 593
 				$appDirUser = fileowner($absAppPath);
594 594
 				if ($appDirUser !== $currentUser) {
595 595
 					$appDirsWithDifferentOwner[] = $absAppPath;
@@ -666,7 +666,7 @@  discard block
 block discarded – undo
666 666
 				$isAutoIncrement = $column->getAutoincrement();
667 667
 				$isAutoIncrementOnSqlite = $isSqlite && $isAutoIncrement;
668 668
 				if ($column->getType()->getName() !== Types::BIGINT && !$isAutoIncrementOnSqlite) {
669
-					$pendingColumns[] = $tableName . '.' . $columnName;
669
+					$pendingColumns[] = $tableName.'.'.$columnName;
670 670
 				}
671 671
 			}
672 672
 		}
@@ -692,12 +692,12 @@  discard block
 block discarded – undo
692 692
 
693 693
 		$tempPath = sys_get_temp_dir();
694 694
 		if (!is_dir($tempPath)) {
695
-			$this->logger->error('Error while checking the temporary PHP path - it was not properly set to a directory. value: ' . $tempPath);
695
+			$this->logger->error('Error while checking the temporary PHP path - it was not properly set to a directory. value: '.$tempPath);
696 696
 			return false;
697 697
 		}
698 698
 		$freeSpaceInTemp = disk_free_space($tempPath);
699 699
 		if ($freeSpaceInTemp === false) {
700
-			$this->logger->error('Error while checking the available disk space of temporary PHP path - no free disk space returned. temporary path: ' . $tempPath);
700
+			$this->logger->error('Error while checking the available disk space of temporary PHP path - no free disk space returned. temporary path: '.$tempPath);
701 701
 			return false;
702 702
 		}
703 703
 
@@ -706,7 +706,7 @@  discard block
 block discarded – undo
706 706
 			return true;
707 707
 		}
708 708
 
709
-		$this->logger->warning('Checking the available space in the temporary path resulted in ' . round($freeSpaceInTempInGB, 1) . ' GB instead of the recommended 50GB. Path: ' . $tempPath);
709
+		$this->logger->warning('Checking the available space in the temporary path resulted in '.round($freeSpaceInTempInGB, 1).' GB instead of the recommended 50GB. Path: '.$tempPath);
710 710
 		return false;
711 711
 	}
712 712
 
Please login to merge, or discard this patch.
apps/settings/lib/Controller/AuthSettingsController.php 1 patch
Indentation   +243 added lines, -243 removed lines patch added patch discarded remove patch
@@ -55,247 +55,247 @@
 block discarded – undo
55 55
 
56 56
 class AuthSettingsController extends Controller {
57 57
 
58
-	/** @var IProvider */
59
-	private $tokenProvider;
60
-
61
-	/** @var ISession */
62
-	private $session;
63
-
64
-	/** IUserSession */
65
-	private $userSession;
66
-
67
-	/** @var string */
68
-	private $uid;
69
-
70
-	/** @var ISecureRandom */
71
-	private $random;
72
-
73
-	/** @var IManager */
74
-	private $activityManager;
75
-
76
-	/** @var RemoteWipe */
77
-	private $remoteWipe;
78
-
79
-	/** @var LoggerInterface */
80
-	private $logger;
81
-
82
-	/**
83
-	 * @param string $appName
84
-	 * @param IRequest $request
85
-	 * @param IProvider $tokenProvider
86
-	 * @param ISession $session
87
-	 * @param ISecureRandom $random
88
-	 * @param string|null $userId
89
-	 * @param IUserSession $userSession
90
-	 * @param IManager $activityManager
91
-	 * @param RemoteWipe $remoteWipe
92
-	 * @param LoggerInterface $logger
93
-	 */
94
-	public function __construct(string $appName,
95
-								IRequest $request,
96
-								IProvider $tokenProvider,
97
-								ISession $session,
98
-								ISecureRandom $random,
99
-								?string $userId,
100
-								IUserSession $userSession,
101
-								IManager $activityManager,
102
-								RemoteWipe $remoteWipe,
103
-								LoggerInterface $logger) {
104
-		parent::__construct($appName, $request);
105
-		$this->tokenProvider = $tokenProvider;
106
-		$this->uid = $userId;
107
-		$this->userSession = $userSession;
108
-		$this->session = $session;
109
-		$this->random = $random;
110
-		$this->activityManager = $activityManager;
111
-		$this->remoteWipe = $remoteWipe;
112
-		$this->logger = $logger;
113
-	}
114
-
115
-	/**
116
-	 * @NoAdminRequired
117
-	 * @NoSubAdminRequired
118
-	 * @PasswordConfirmationRequired
119
-	 *
120
-	 * @param string $name
121
-	 * @return JSONResponse
122
-	 */
123
-	public function create($name) {
124
-		try {
125
-			$sessionId = $this->session->getId();
126
-		} catch (SessionNotAvailableException $ex) {
127
-			return $this->getServiceNotAvailableResponse();
128
-		}
129
-		if ($this->userSession->getImpersonatingUserID() !== null) {
130
-			return $this->getServiceNotAvailableResponse();
131
-		}
132
-
133
-		try {
134
-			$sessionToken = $this->tokenProvider->getToken($sessionId);
135
-			$loginName = $sessionToken->getLoginName();
136
-			try {
137
-				$password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
138
-			} catch (PasswordlessTokenException $ex) {
139
-				$password = null;
140
-			}
141
-		} catch (InvalidTokenException $ex) {
142
-			return $this->getServiceNotAvailableResponse();
143
-		}
144
-
145
-		$token = $this->generateRandomDeviceToken();
146
-		$deviceToken = $this->tokenProvider->generateToken($token, $this->uid, $loginName, $password, $name, IToken::PERMANENT_TOKEN);
147
-		$tokenData = $deviceToken->jsonSerialize();
148
-		$tokenData['canDelete'] = true;
149
-		$tokenData['canRename'] = true;
150
-
151
-		$this->publishActivity(Provider::APP_TOKEN_CREATED, $deviceToken->getId(), ['name' => $deviceToken->getName()]);
152
-
153
-		return new JSONResponse([
154
-			'token' => $token,
155
-			'loginName' => $loginName,
156
-			'deviceToken' => $tokenData,
157
-		]);
158
-	}
159
-
160
-	/**
161
-	 * @return JSONResponse
162
-	 */
163
-	private function getServiceNotAvailableResponse() {
164
-		$resp = new JSONResponse();
165
-		$resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
166
-		return $resp;
167
-	}
168
-
169
-	/**
170
-	 * Return a 25 digit device password
171
-	 *
172
-	 * Example: AbCdE-fGhJk-MnPqR-sTwXy-23456
173
-	 *
174
-	 * @return string
175
-	 */
176
-	private function generateRandomDeviceToken() {
177
-		$groups = [];
178
-		for ($i = 0; $i < 5; $i++) {
179
-			$groups[] = $this->random->generate(5, ISecureRandom::CHAR_HUMAN_READABLE);
180
-		}
181
-		return implode('-', $groups);
182
-	}
183
-
184
-	/**
185
-	 * @NoAdminRequired
186
-	 * @NoSubAdminRequired
187
-	 *
188
-	 * @param int $id
189
-	 * @return array|JSONResponse
190
-	 */
191
-	public function destroy($id) {
192
-		try {
193
-			$token = $this->findTokenByIdAndUser($id);
194
-		} catch (WipeTokenException $e) {
195
-			//continue as we can destroy tokens in wipe
196
-			$token = $e->getToken();
197
-		} catch (InvalidTokenException $e) {
198
-			return new JSONResponse([], Http::STATUS_NOT_FOUND);
199
-		}
200
-
201
-		$this->tokenProvider->invalidateTokenById($this->uid, $token->getId());
202
-		$this->publishActivity(Provider::APP_TOKEN_DELETED, $token->getId(), ['name' => $token->getName()]);
203
-		return [];
204
-	}
205
-
206
-	/**
207
-	 * @NoAdminRequired
208
-	 * @NoSubAdminRequired
209
-	 *
210
-	 * @param int $id
211
-	 * @param array $scope
212
-	 * @param string $name
213
-	 * @return array|JSONResponse
214
-	 */
215
-	public function update($id, array $scope, string $name) {
216
-		try {
217
-			$token = $this->findTokenByIdAndUser($id);
218
-		} catch (InvalidTokenException $e) {
219
-			return new JSONResponse([], Http::STATUS_NOT_FOUND);
220
-		}
221
-
222
-		$currentName = $token->getName();
223
-
224
-		if ($scope !== $token->getScopeAsArray()) {
225
-			$token->setScope(['filesystem' => $scope['filesystem']]);
226
-			$this->publishActivity($scope['filesystem'] ? Provider::APP_TOKEN_FILESYSTEM_GRANTED : Provider::APP_TOKEN_FILESYSTEM_REVOKED, $token->getId(), ['name' => $currentName]);
227
-		}
228
-
229
-		if ($token instanceof INamedToken && $name !== $currentName) {
230
-			$token->setName($name);
231
-			$this->publishActivity(Provider::APP_TOKEN_RENAMED, $token->getId(), ['name' => $currentName, 'newName' => $name]);
232
-		}
233
-
234
-		$this->tokenProvider->updateToken($token);
235
-		return [];
236
-	}
237
-
238
-	/**
239
-	 * @param string $subject
240
-	 * @param int $id
241
-	 * @param array $parameters
242
-	 */
243
-	private function publishActivity(string $subject, int $id, array $parameters = []): void {
244
-		$event = $this->activityManager->generateEvent();
245
-		$event->setApp('settings')
246
-			->setType('security')
247
-			->setAffectedUser($this->uid)
248
-			->setAuthor($this->uid)
249
-			->setSubject($subject, $parameters)
250
-			->setObject('app_token', $id, 'App Password');
251
-
252
-		try {
253
-			$this->activityManager->publish($event);
254
-		} catch (BadMethodCallException $e) {
255
-			$this->logger->warning('could not publish activity', ['exception' => $e]);
256
-		}
257
-	}
258
-
259
-	/**
260
-	 * Find a token by given id and check if uid for current session belongs to this token
261
-	 *
262
-	 * @param int $id
263
-	 * @return IToken
264
-	 * @throws InvalidTokenException
265
-	 */
266
-	private function findTokenByIdAndUser(int $id): IToken {
267
-		try {
268
-			$token = $this->tokenProvider->getTokenById($id);
269
-		} catch (ExpiredTokenException $e) {
270
-			$token = $e->getToken();
271
-		}
272
-		if ($token->getUID() !== $this->uid) {
273
-			throw new InvalidTokenException('This token does not belong to you!');
274
-		}
275
-		return $token;
276
-	}
277
-
278
-	/**
279
-	 * @NoAdminRequired
280
-	 * @NoSubAdminRequired
281
-	 * @PasswordConfirmationRequired
282
-	 *
283
-	 * @param int $id
284
-	 * @return JSONResponse
285
-	 * @throws InvalidTokenException
286
-	 * @throws \OC\Authentication\Exceptions\ExpiredTokenException
287
-	 */
288
-	public function wipe(int $id): JSONResponse {
289
-		try {
290
-			$token = $this->findTokenByIdAndUser($id);
291
-		} catch (InvalidTokenException $e) {
292
-			return new JSONResponse([], Http::STATUS_NOT_FOUND);
293
-		}
294
-
295
-		if (!$this->remoteWipe->markTokenForWipe($token)) {
296
-			return new JSONResponse([], Http::STATUS_BAD_REQUEST);
297
-		}
298
-
299
-		return new JSONResponse([]);
300
-	}
58
+    /** @var IProvider */
59
+    private $tokenProvider;
60
+
61
+    /** @var ISession */
62
+    private $session;
63
+
64
+    /** IUserSession */
65
+    private $userSession;
66
+
67
+    /** @var string */
68
+    private $uid;
69
+
70
+    /** @var ISecureRandom */
71
+    private $random;
72
+
73
+    /** @var IManager */
74
+    private $activityManager;
75
+
76
+    /** @var RemoteWipe */
77
+    private $remoteWipe;
78
+
79
+    /** @var LoggerInterface */
80
+    private $logger;
81
+
82
+    /**
83
+     * @param string $appName
84
+     * @param IRequest $request
85
+     * @param IProvider $tokenProvider
86
+     * @param ISession $session
87
+     * @param ISecureRandom $random
88
+     * @param string|null $userId
89
+     * @param IUserSession $userSession
90
+     * @param IManager $activityManager
91
+     * @param RemoteWipe $remoteWipe
92
+     * @param LoggerInterface $logger
93
+     */
94
+    public function __construct(string $appName,
95
+                                IRequest $request,
96
+                                IProvider $tokenProvider,
97
+                                ISession $session,
98
+                                ISecureRandom $random,
99
+                                ?string $userId,
100
+                                IUserSession $userSession,
101
+                                IManager $activityManager,
102
+                                RemoteWipe $remoteWipe,
103
+                                LoggerInterface $logger) {
104
+        parent::__construct($appName, $request);
105
+        $this->tokenProvider = $tokenProvider;
106
+        $this->uid = $userId;
107
+        $this->userSession = $userSession;
108
+        $this->session = $session;
109
+        $this->random = $random;
110
+        $this->activityManager = $activityManager;
111
+        $this->remoteWipe = $remoteWipe;
112
+        $this->logger = $logger;
113
+    }
114
+
115
+    /**
116
+     * @NoAdminRequired
117
+     * @NoSubAdminRequired
118
+     * @PasswordConfirmationRequired
119
+     *
120
+     * @param string $name
121
+     * @return JSONResponse
122
+     */
123
+    public function create($name) {
124
+        try {
125
+            $sessionId = $this->session->getId();
126
+        } catch (SessionNotAvailableException $ex) {
127
+            return $this->getServiceNotAvailableResponse();
128
+        }
129
+        if ($this->userSession->getImpersonatingUserID() !== null) {
130
+            return $this->getServiceNotAvailableResponse();
131
+        }
132
+
133
+        try {
134
+            $sessionToken = $this->tokenProvider->getToken($sessionId);
135
+            $loginName = $sessionToken->getLoginName();
136
+            try {
137
+                $password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
138
+            } catch (PasswordlessTokenException $ex) {
139
+                $password = null;
140
+            }
141
+        } catch (InvalidTokenException $ex) {
142
+            return $this->getServiceNotAvailableResponse();
143
+        }
144
+
145
+        $token = $this->generateRandomDeviceToken();
146
+        $deviceToken = $this->tokenProvider->generateToken($token, $this->uid, $loginName, $password, $name, IToken::PERMANENT_TOKEN);
147
+        $tokenData = $deviceToken->jsonSerialize();
148
+        $tokenData['canDelete'] = true;
149
+        $tokenData['canRename'] = true;
150
+
151
+        $this->publishActivity(Provider::APP_TOKEN_CREATED, $deviceToken->getId(), ['name' => $deviceToken->getName()]);
152
+
153
+        return new JSONResponse([
154
+            'token' => $token,
155
+            'loginName' => $loginName,
156
+            'deviceToken' => $tokenData,
157
+        ]);
158
+    }
159
+
160
+    /**
161
+     * @return JSONResponse
162
+     */
163
+    private function getServiceNotAvailableResponse() {
164
+        $resp = new JSONResponse();
165
+        $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
166
+        return $resp;
167
+    }
168
+
169
+    /**
170
+     * Return a 25 digit device password
171
+     *
172
+     * Example: AbCdE-fGhJk-MnPqR-sTwXy-23456
173
+     *
174
+     * @return string
175
+     */
176
+    private function generateRandomDeviceToken() {
177
+        $groups = [];
178
+        for ($i = 0; $i < 5; $i++) {
179
+            $groups[] = $this->random->generate(5, ISecureRandom::CHAR_HUMAN_READABLE);
180
+        }
181
+        return implode('-', $groups);
182
+    }
183
+
184
+    /**
185
+     * @NoAdminRequired
186
+     * @NoSubAdminRequired
187
+     *
188
+     * @param int $id
189
+     * @return array|JSONResponse
190
+     */
191
+    public function destroy($id) {
192
+        try {
193
+            $token = $this->findTokenByIdAndUser($id);
194
+        } catch (WipeTokenException $e) {
195
+            //continue as we can destroy tokens in wipe
196
+            $token = $e->getToken();
197
+        } catch (InvalidTokenException $e) {
198
+            return new JSONResponse([], Http::STATUS_NOT_FOUND);
199
+        }
200
+
201
+        $this->tokenProvider->invalidateTokenById($this->uid, $token->getId());
202
+        $this->publishActivity(Provider::APP_TOKEN_DELETED, $token->getId(), ['name' => $token->getName()]);
203
+        return [];
204
+    }
205
+
206
+    /**
207
+     * @NoAdminRequired
208
+     * @NoSubAdminRequired
209
+     *
210
+     * @param int $id
211
+     * @param array $scope
212
+     * @param string $name
213
+     * @return array|JSONResponse
214
+     */
215
+    public function update($id, array $scope, string $name) {
216
+        try {
217
+            $token = $this->findTokenByIdAndUser($id);
218
+        } catch (InvalidTokenException $e) {
219
+            return new JSONResponse([], Http::STATUS_NOT_FOUND);
220
+        }
221
+
222
+        $currentName = $token->getName();
223
+
224
+        if ($scope !== $token->getScopeAsArray()) {
225
+            $token->setScope(['filesystem' => $scope['filesystem']]);
226
+            $this->publishActivity($scope['filesystem'] ? Provider::APP_TOKEN_FILESYSTEM_GRANTED : Provider::APP_TOKEN_FILESYSTEM_REVOKED, $token->getId(), ['name' => $currentName]);
227
+        }
228
+
229
+        if ($token instanceof INamedToken && $name !== $currentName) {
230
+            $token->setName($name);
231
+            $this->publishActivity(Provider::APP_TOKEN_RENAMED, $token->getId(), ['name' => $currentName, 'newName' => $name]);
232
+        }
233
+
234
+        $this->tokenProvider->updateToken($token);
235
+        return [];
236
+    }
237
+
238
+    /**
239
+     * @param string $subject
240
+     * @param int $id
241
+     * @param array $parameters
242
+     */
243
+    private function publishActivity(string $subject, int $id, array $parameters = []): void {
244
+        $event = $this->activityManager->generateEvent();
245
+        $event->setApp('settings')
246
+            ->setType('security')
247
+            ->setAffectedUser($this->uid)
248
+            ->setAuthor($this->uid)
249
+            ->setSubject($subject, $parameters)
250
+            ->setObject('app_token', $id, 'App Password');
251
+
252
+        try {
253
+            $this->activityManager->publish($event);
254
+        } catch (BadMethodCallException $e) {
255
+            $this->logger->warning('could not publish activity', ['exception' => $e]);
256
+        }
257
+    }
258
+
259
+    /**
260
+     * Find a token by given id and check if uid for current session belongs to this token
261
+     *
262
+     * @param int $id
263
+     * @return IToken
264
+     * @throws InvalidTokenException
265
+     */
266
+    private function findTokenByIdAndUser(int $id): IToken {
267
+        try {
268
+            $token = $this->tokenProvider->getTokenById($id);
269
+        } catch (ExpiredTokenException $e) {
270
+            $token = $e->getToken();
271
+        }
272
+        if ($token->getUID() !== $this->uid) {
273
+            throw new InvalidTokenException('This token does not belong to you!');
274
+        }
275
+        return $token;
276
+    }
277
+
278
+    /**
279
+     * @NoAdminRequired
280
+     * @NoSubAdminRequired
281
+     * @PasswordConfirmationRequired
282
+     *
283
+     * @param int $id
284
+     * @return JSONResponse
285
+     * @throws InvalidTokenException
286
+     * @throws \OC\Authentication\Exceptions\ExpiredTokenException
287
+     */
288
+    public function wipe(int $id): JSONResponse {
289
+        try {
290
+            $token = $this->findTokenByIdAndUser($id);
291
+        } catch (InvalidTokenException $e) {
292
+            return new JSONResponse([], Http::STATUS_NOT_FOUND);
293
+        }
294
+
295
+        if (!$this->remoteWipe->markTokenForWipe($token)) {
296
+            return new JSONResponse([], Http::STATUS_BAD_REQUEST);
297
+        }
298
+
299
+        return new JSONResponse([]);
300
+    }
301 301
 }
Please login to merge, or discard this patch.
apps/settings/lib/Controller/AppSettingsController.php 1 patch
Indentation   +500 added lines, -500 removed lines patch added patch discarded remove patch
@@ -56,504 +56,504 @@
 block discarded – undo
56 56
 
57 57
 class AppSettingsController extends Controller {
58 58
 
59
-	/** @var \OCP\IL10N */
60
-	private $l10n;
61
-	/** @var IConfig */
62
-	private $config;
63
-	/** @var INavigationManager */
64
-	private $navigationManager;
65
-	/** @var IAppManager */
66
-	private $appManager;
67
-	/** @var CategoryFetcher */
68
-	private $categoryFetcher;
69
-	/** @var AppFetcher */
70
-	private $appFetcher;
71
-	/** @var IFactory */
72
-	private $l10nFactory;
73
-	/** @var BundleFetcher */
74
-	private $bundleFetcher;
75
-	/** @var Installer */
76
-	private $installer;
77
-	/** @var IURLGenerator */
78
-	private $urlGenerator;
79
-	/** @var LoggerInterface */
80
-	private $logger;
81
-
82
-	/** @var array */
83
-	private $allApps = [];
84
-
85
-	/**
86
-	 * @param string $appName
87
-	 * @param IRequest $request
88
-	 * @param IL10N $l10n
89
-	 * @param IConfig $config
90
-	 * @param INavigationManager $navigationManager
91
-	 * @param IAppManager $appManager
92
-	 * @param CategoryFetcher $categoryFetcher
93
-	 * @param AppFetcher $appFetcher
94
-	 * @param IFactory $l10nFactory
95
-	 * @param BundleFetcher $bundleFetcher
96
-	 * @param Installer $installer
97
-	 * @param IURLGenerator $urlGenerator
98
-	 * @param LoggerInterface $logger
99
-	 */
100
-	public function __construct(string $appName,
101
-								IRequest $request,
102
-								IL10N $l10n,
103
-								IConfig $config,
104
-								INavigationManager $navigationManager,
105
-								IAppManager $appManager,
106
-								CategoryFetcher $categoryFetcher,
107
-								AppFetcher $appFetcher,
108
-								IFactory $l10nFactory,
109
-								BundleFetcher $bundleFetcher,
110
-								Installer $installer,
111
-								IURLGenerator $urlGenerator,
112
-								LoggerInterface $logger) {
113
-		parent::__construct($appName, $request);
114
-		$this->l10n = $l10n;
115
-		$this->config = $config;
116
-		$this->navigationManager = $navigationManager;
117
-		$this->appManager = $appManager;
118
-		$this->categoryFetcher = $categoryFetcher;
119
-		$this->appFetcher = $appFetcher;
120
-		$this->l10nFactory = $l10nFactory;
121
-		$this->bundleFetcher = $bundleFetcher;
122
-		$this->installer = $installer;
123
-		$this->urlGenerator = $urlGenerator;
124
-		$this->logger = $logger;
125
-	}
126
-
127
-	/**
128
-	 * @NoCSRFRequired
129
-	 *
130
-	 * @return TemplateResponse
131
-	 */
132
-	public function viewApps(): TemplateResponse {
133
-		\OC_Util::addScript('settings', 'apps');
134
-		$params = [];
135
-		$params['appstoreEnabled'] = $this->config->getSystemValue('appstoreenabled', true) === true;
136
-		$params['updateCount'] = count($this->getAppsWithUpdates());
137
-		$params['developerDocumentation'] = $this->urlGenerator->linkToDocs('developer-manual');
138
-		$params['bundles'] = $this->getBundles();
139
-		$this->navigationManager->setActiveEntry('core_apps');
140
-
141
-		$templateResponse = new TemplateResponse('settings', 'settings-vue', ['serverData' => $params]);
142
-		$policy = new ContentSecurityPolicy();
143
-		$policy->addAllowedImageDomain('https://usercontent.apps.nextcloud.com');
144
-		$templateResponse->setContentSecurityPolicy($policy);
145
-
146
-		return $templateResponse;
147
-	}
148
-
149
-	private function getAppsWithUpdates() {
150
-		$appClass = new \OC_App();
151
-		$apps = $appClass->listAllApps();
152
-		foreach ($apps as $key => $app) {
153
-			$newVersion = $this->installer->isUpdateAvailable($app['id']);
154
-			if ($newVersion === false) {
155
-				unset($apps[$key]);
156
-			}
157
-		}
158
-		return $apps;
159
-	}
160
-
161
-	private function getBundles() {
162
-		$result = [];
163
-		$bundles = $this->bundleFetcher->getBundles();
164
-		foreach ($bundles as $bundle) {
165
-			$result[] = [
166
-				'name' => $bundle->getName(),
167
-				'id' => $bundle->getIdentifier(),
168
-				'appIdentifiers' => $bundle->getAppIdentifiers()
169
-			];
170
-		}
171
-		return $result;
172
-	}
173
-
174
-	/**
175
-	 * Get all available categories
176
-	 *
177
-	 * @return JSONResponse
178
-	 */
179
-	public function listCategories(): JSONResponse {
180
-		return new JSONResponse($this->getAllCategories());
181
-	}
182
-
183
-	private function getAllCategories() {
184
-		$currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
185
-
186
-		$formattedCategories = [];
187
-		$categories = $this->categoryFetcher->get();
188
-		foreach ($categories as $category) {
189
-			$formattedCategories[] = [
190
-				'id' => $category['id'],
191
-				'ident' => $category['id'],
192
-				'displayName' => isset($category['translations'][$currentLanguage]['name']) ? $category['translations'][$currentLanguage]['name'] : $category['translations']['en']['name'],
193
-			];
194
-		}
195
-
196
-		return $formattedCategories;
197
-	}
198
-
199
-	private function fetchApps() {
200
-		$appClass = new \OC_App();
201
-		$apps = $appClass->listAllApps();
202
-		foreach ($apps as $app) {
203
-			$app['installed'] = true;
204
-			$this->allApps[$app['id']] = $app;
205
-		}
206
-
207
-		$apps = $this->getAppsForCategory('');
208
-		foreach ($apps as $app) {
209
-			$app['appstore'] = true;
210
-			if (!array_key_exists($app['id'], $this->allApps)) {
211
-				$this->allApps[$app['id']] = $app;
212
-			} else {
213
-				$this->allApps[$app['id']] = array_merge($app, $this->allApps[$app['id']]);
214
-			}
215
-		}
216
-
217
-		// add bundle information
218
-		$bundles = $this->bundleFetcher->getBundles();
219
-		foreach ($bundles as $bundle) {
220
-			foreach ($bundle->getAppIdentifiers() as $identifier) {
221
-				foreach ($this->allApps as &$app) {
222
-					if ($app['id'] === $identifier) {
223
-						$app['bundleIds'][] = $bundle->getIdentifier();
224
-						continue;
225
-					}
226
-				}
227
-			}
228
-		}
229
-	}
230
-
231
-	private function getAllApps() {
232
-		return $this->allApps;
233
-	}
234
-	/**
235
-	 * Get all available apps in a category
236
-	 *
237
-	 * @param string $category
238
-	 * @return JSONResponse
239
-	 * @throws \Exception
240
-	 */
241
-	public function listApps(): JSONResponse {
242
-		$this->fetchApps();
243
-		$apps = $this->getAllApps();
244
-
245
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n);
246
-
247
-		// Extend existing app details
248
-		$apps = array_map(function ($appData) use ($dependencyAnalyzer) {
249
-			if (isset($appData['appstoreData'])) {
250
-				$appstoreData = $appData['appstoreData'];
251
-				$appData['screenshot'] = isset($appstoreData['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/' . base64_encode($appstoreData['screenshots'][0]['url']) : '';
252
-				$appData['category'] = $appstoreData['categories'];
253
-				$appData['releases'] = $appstoreData['releases'];
254
-			}
255
-
256
-			$newVersion = $this->installer->isUpdateAvailable($appData['id']);
257
-			if ($newVersion) {
258
-				$appData['update'] = $newVersion;
259
-			}
260
-
261
-			// fix groups to be an array
262
-			$groups = [];
263
-			if (is_string($appData['groups'])) {
264
-				$groups = json_decode($appData['groups']);
265
-			}
266
-			$appData['groups'] = $groups;
267
-			$appData['canUnInstall'] = !$appData['active'] && $appData['removable'];
268
-
269
-			// fix licence vs license
270
-			if (isset($appData['license']) && !isset($appData['licence'])) {
271
-				$appData['licence'] = $appData['license'];
272
-			}
273
-
274
-			$ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
275
-			if (!is_array($ignoreMaxApps)) {
276
-				$this->logger->warning('The value given for app_install_overwrite is not an array. Ignoring...');
277
-				$ignoreMaxApps = [];
278
-			}
279
-			$ignoreMax = in_array($appData['id'], $ignoreMaxApps);
280
-
281
-			// analyse dependencies
282
-			$missing = $dependencyAnalyzer->analyze($appData, $ignoreMax);
283
-			$appData['canInstall'] = empty($missing);
284
-			$appData['missingDependencies'] = $missing;
285
-
286
-			$appData['missingMinOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['min-version']);
287
-			$appData['missingMaxOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['max-version']);
288
-			$appData['isCompatible'] = $dependencyAnalyzer->isMarkedCompatible($appData);
289
-
290
-			return $appData;
291
-		}, $apps);
292
-
293
-		usort($apps, [$this, 'sortApps']);
294
-
295
-		return new JSONResponse(['apps' => $apps, 'status' => 'success']);
296
-	}
297
-
298
-	/**
299
-	 * Get all apps for a category from the app store
300
-	 *
301
-	 * @param string $requestedCategory
302
-	 * @return array
303
-	 * @throws \Exception
304
-	 */
305
-	private function getAppsForCategory($requestedCategory = ''): array {
306
-		$versionParser = new VersionParser();
307
-		$formattedApps = [];
308
-		$apps = $this->appFetcher->get();
309
-		foreach ($apps as $app) {
310
-			// Skip all apps not in the requested category
311
-			if ($requestedCategory !== '') {
312
-				$isInCategory = false;
313
-				foreach ($app['categories'] as $category) {
314
-					if ($category === $requestedCategory) {
315
-						$isInCategory = true;
316
-					}
317
-				}
318
-				if (!$isInCategory) {
319
-					continue;
320
-				}
321
-			}
322
-
323
-			if (!isset($app['releases'][0]['rawPlatformVersionSpec'])) {
324
-				continue;
325
-			}
326
-			$nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
327
-			$nextCloudVersionDependencies = [];
328
-			if ($nextCloudVersion->getMinimumVersion() !== '') {
329
-				$nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
330
-			}
331
-			if ($nextCloudVersion->getMaximumVersion() !== '') {
332
-				$nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
333
-			}
334
-			$phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
335
-			$existsLocally = \OC_App::getAppPath($app['id']) !== false;
336
-			$phpDependencies = [];
337
-			if ($phpVersion->getMinimumVersion() !== '') {
338
-				$phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
339
-			}
340
-			if ($phpVersion->getMaximumVersion() !== '') {
341
-				$phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
342
-			}
343
-			if (isset($app['releases'][0]['minIntSize'])) {
344
-				$phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
345
-			}
346
-			$authors = '';
347
-			foreach ($app['authors'] as $key => $author) {
348
-				$authors .= $author['name'];
349
-				if ($key !== count($app['authors']) - 1) {
350
-					$authors .= ', ';
351
-				}
352
-			}
353
-
354
-			$currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
355
-			$enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
356
-			$groups = null;
357
-			if ($enabledValue !== 'no' && $enabledValue !== 'yes') {
358
-				$groups = $enabledValue;
359
-			}
360
-
361
-			$currentVersion = '';
362
-			if ($this->appManager->isInstalled($app['id'])) {
363
-				$currentVersion = $this->appManager->getAppVersion($app['id']);
364
-			} else {
365
-				$currentLanguage = $app['releases'][0]['version'];
366
-			}
367
-
368
-			$formattedApps[] = [
369
-				'id' => $app['id'],
370
-				'name' => isset($app['translations'][$currentLanguage]['name']) ? $app['translations'][$currentLanguage]['name'] : $app['translations']['en']['name'],
371
-				'description' => isset($app['translations'][$currentLanguage]['description']) ? $app['translations'][$currentLanguage]['description'] : $app['translations']['en']['description'],
372
-				'summary' => isset($app['translations'][$currentLanguage]['summary']) ? $app['translations'][$currentLanguage]['summary'] : $app['translations']['en']['summary'],
373
-				'license' => $app['releases'][0]['licenses'],
374
-				'author' => $authors,
375
-				'shipped' => false,
376
-				'version' => $currentVersion,
377
-				'default_enable' => '',
378
-				'types' => [],
379
-				'documentation' => [
380
-					'admin' => $app['adminDocs'],
381
-					'user' => $app['userDocs'],
382
-					'developer' => $app['developerDocs']
383
-				],
384
-				'website' => $app['website'],
385
-				'bugs' => $app['issueTracker'],
386
-				'detailpage' => $app['website'],
387
-				'dependencies' => array_merge(
388
-					$nextCloudVersionDependencies,
389
-					$phpDependencies
390
-				),
391
-				'level' => ($app['isFeatured'] === true) ? 200 : 100,
392
-				'missingMaxOwnCloudVersion' => false,
393
-				'missingMinOwnCloudVersion' => false,
394
-				'canInstall' => true,
395
-				'screenshot' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($app['screenshots'][0]['url']) : '',
396
-				'score' => $app['ratingOverall'],
397
-				'ratingNumOverall' => $app['ratingNumOverall'],
398
-				'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5,
399
-				'removable' => $existsLocally,
400
-				'active' => $this->appManager->isEnabledForUser($app['id']),
401
-				'needsDownload' => !$existsLocally,
402
-				'groups' => $groups,
403
-				'fromAppStore' => true,
404
-				'appstoreData' => $app,
405
-			];
406
-		}
407
-
408
-		return $formattedApps;
409
-	}
410
-
411
-	/**
412
-	 * @PasswordConfirmationRequired
413
-	 *
414
-	 * @param string $appId
415
-	 * @param array $groups
416
-	 * @return JSONResponse
417
-	 */
418
-	public function enableApp(string $appId, array $groups = []): JSONResponse {
419
-		return $this->enableApps([$appId], $groups);
420
-	}
421
-
422
-	/**
423
-	 * Enable one or more apps
424
-	 *
425
-	 * apps will be enabled for specific groups only if $groups is defined
426
-	 *
427
-	 * @PasswordConfirmationRequired
428
-	 * @param array $appIds
429
-	 * @param array $groups
430
-	 * @return JSONResponse
431
-	 */
432
-	public function enableApps(array $appIds, array $groups = []): JSONResponse {
433
-		try {
434
-			$updateRequired = false;
435
-
436
-			foreach ($appIds as $appId) {
437
-				$appId = OC_App::cleanAppId($appId);
438
-
439
-				// Check if app is already downloaded
440
-				/** @var Installer $installer */
441
-				$installer = \OC::$server->query(Installer::class);
442
-				$isDownloaded = $installer->isDownloaded($appId);
443
-
444
-				if (!$isDownloaded) {
445
-					$installer->downloadApp($appId);
446
-				}
447
-
448
-				$installer->installApp($appId);
449
-
450
-				if (count($groups) > 0) {
451
-					$this->appManager->enableAppForGroups($appId, $this->getGroupList($groups));
452
-				} else {
453
-					$this->appManager->enableApp($appId);
454
-				}
455
-				if (\OC_App::shouldUpgrade($appId)) {
456
-					$updateRequired = true;
457
-				}
458
-			}
459
-			return new JSONResponse(['data' => ['update_required' => $updateRequired]]);
460
-		} catch (\Exception $e) {
461
-			$this->logger->error('could not enable apps', ['exception' => $e]);
462
-			return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
463
-		}
464
-	}
465
-
466
-	private function getGroupList(array $groups) {
467
-		$groupManager = \OC::$server->getGroupManager();
468
-		$groupsList = [];
469
-		foreach ($groups as $group) {
470
-			$groupItem = $groupManager->get($group);
471
-			if ($groupItem instanceof \OCP\IGroup) {
472
-				$groupsList[] = $groupManager->get($group);
473
-			}
474
-		}
475
-		return $groupsList;
476
-	}
477
-
478
-	/**
479
-	 * @PasswordConfirmationRequired
480
-	 *
481
-	 * @param string $appId
482
-	 * @return JSONResponse
483
-	 */
484
-	public function disableApp(string $appId): JSONResponse {
485
-		return $this->disableApps([$appId]);
486
-	}
487
-
488
-	/**
489
-	 * @PasswordConfirmationRequired
490
-	 *
491
-	 * @param array $appIds
492
-	 * @return JSONResponse
493
-	 */
494
-	public function disableApps(array $appIds): JSONResponse {
495
-		try {
496
-			foreach ($appIds as $appId) {
497
-				$appId = OC_App::cleanAppId($appId);
498
-				$this->appManager->disableApp($appId);
499
-			}
500
-			return new JSONResponse([]);
501
-		} catch (\Exception $e) {
502
-			$this->logger->error('could not disable app', ['exception' => $e]);
503
-			return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
504
-		}
505
-	}
506
-
507
-	/**
508
-	 * @PasswordConfirmationRequired
509
-	 *
510
-	 * @param string $appId
511
-	 * @return JSONResponse
512
-	 */
513
-	public function uninstallApp(string $appId): JSONResponse {
514
-		$appId = OC_App::cleanAppId($appId);
515
-		$result = $this->installer->removeApp($appId);
516
-		if ($result !== false) {
517
-			$this->appManager->clearAppsCache();
518
-			return new JSONResponse(['data' => ['appid' => $appId]]);
519
-		}
520
-		return new JSONResponse(['data' => ['message' => $this->l10n->t('Couldn\'t remove app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
521
-	}
522
-
523
-	/**
524
-	 * @param string $appId
525
-	 * @return JSONResponse
526
-	 */
527
-	public function updateApp(string $appId): JSONResponse {
528
-		$appId = OC_App::cleanAppId($appId);
529
-
530
-		$this->config->setSystemValue('maintenance', true);
531
-		try {
532
-			$result = $this->installer->updateAppstoreApp($appId);
533
-			$this->config->setSystemValue('maintenance', false);
534
-		} catch (\Exception $ex) {
535
-			$this->config->setSystemValue('maintenance', false);
536
-			return new JSONResponse(['data' => ['message' => $ex->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
537
-		}
538
-
539
-		if ($result !== false) {
540
-			return new JSONResponse(['data' => ['appid' => $appId]]);
541
-		}
542
-		return new JSONResponse(['data' => ['message' => $this->l10n->t('Couldn\'t update app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
543
-	}
544
-
545
-	private function sortApps($a, $b) {
546
-		$a = (string)$a['name'];
547
-		$b = (string)$b['name'];
548
-		if ($a === $b) {
549
-			return 0;
550
-		}
551
-		return ($a < $b) ? -1 : 1;
552
-	}
553
-
554
-	public function force(string $appId): JSONResponse {
555
-		$appId = OC_App::cleanAppId($appId);
556
-		$this->appManager->ignoreNextcloudRequirementForApp($appId);
557
-		return new JSONResponse();
558
-	}
59
+    /** @var \OCP\IL10N */
60
+    private $l10n;
61
+    /** @var IConfig */
62
+    private $config;
63
+    /** @var INavigationManager */
64
+    private $navigationManager;
65
+    /** @var IAppManager */
66
+    private $appManager;
67
+    /** @var CategoryFetcher */
68
+    private $categoryFetcher;
69
+    /** @var AppFetcher */
70
+    private $appFetcher;
71
+    /** @var IFactory */
72
+    private $l10nFactory;
73
+    /** @var BundleFetcher */
74
+    private $bundleFetcher;
75
+    /** @var Installer */
76
+    private $installer;
77
+    /** @var IURLGenerator */
78
+    private $urlGenerator;
79
+    /** @var LoggerInterface */
80
+    private $logger;
81
+
82
+    /** @var array */
83
+    private $allApps = [];
84
+
85
+    /**
86
+     * @param string $appName
87
+     * @param IRequest $request
88
+     * @param IL10N $l10n
89
+     * @param IConfig $config
90
+     * @param INavigationManager $navigationManager
91
+     * @param IAppManager $appManager
92
+     * @param CategoryFetcher $categoryFetcher
93
+     * @param AppFetcher $appFetcher
94
+     * @param IFactory $l10nFactory
95
+     * @param BundleFetcher $bundleFetcher
96
+     * @param Installer $installer
97
+     * @param IURLGenerator $urlGenerator
98
+     * @param LoggerInterface $logger
99
+     */
100
+    public function __construct(string $appName,
101
+                                IRequest $request,
102
+                                IL10N $l10n,
103
+                                IConfig $config,
104
+                                INavigationManager $navigationManager,
105
+                                IAppManager $appManager,
106
+                                CategoryFetcher $categoryFetcher,
107
+                                AppFetcher $appFetcher,
108
+                                IFactory $l10nFactory,
109
+                                BundleFetcher $bundleFetcher,
110
+                                Installer $installer,
111
+                                IURLGenerator $urlGenerator,
112
+                                LoggerInterface $logger) {
113
+        parent::__construct($appName, $request);
114
+        $this->l10n = $l10n;
115
+        $this->config = $config;
116
+        $this->navigationManager = $navigationManager;
117
+        $this->appManager = $appManager;
118
+        $this->categoryFetcher = $categoryFetcher;
119
+        $this->appFetcher = $appFetcher;
120
+        $this->l10nFactory = $l10nFactory;
121
+        $this->bundleFetcher = $bundleFetcher;
122
+        $this->installer = $installer;
123
+        $this->urlGenerator = $urlGenerator;
124
+        $this->logger = $logger;
125
+    }
126
+
127
+    /**
128
+     * @NoCSRFRequired
129
+     *
130
+     * @return TemplateResponse
131
+     */
132
+    public function viewApps(): TemplateResponse {
133
+        \OC_Util::addScript('settings', 'apps');
134
+        $params = [];
135
+        $params['appstoreEnabled'] = $this->config->getSystemValue('appstoreenabled', true) === true;
136
+        $params['updateCount'] = count($this->getAppsWithUpdates());
137
+        $params['developerDocumentation'] = $this->urlGenerator->linkToDocs('developer-manual');
138
+        $params['bundles'] = $this->getBundles();
139
+        $this->navigationManager->setActiveEntry('core_apps');
140
+
141
+        $templateResponse = new TemplateResponse('settings', 'settings-vue', ['serverData' => $params]);
142
+        $policy = new ContentSecurityPolicy();
143
+        $policy->addAllowedImageDomain('https://usercontent.apps.nextcloud.com');
144
+        $templateResponse->setContentSecurityPolicy($policy);
145
+
146
+        return $templateResponse;
147
+    }
148
+
149
+    private function getAppsWithUpdates() {
150
+        $appClass = new \OC_App();
151
+        $apps = $appClass->listAllApps();
152
+        foreach ($apps as $key => $app) {
153
+            $newVersion = $this->installer->isUpdateAvailable($app['id']);
154
+            if ($newVersion === false) {
155
+                unset($apps[$key]);
156
+            }
157
+        }
158
+        return $apps;
159
+    }
160
+
161
+    private function getBundles() {
162
+        $result = [];
163
+        $bundles = $this->bundleFetcher->getBundles();
164
+        foreach ($bundles as $bundle) {
165
+            $result[] = [
166
+                'name' => $bundle->getName(),
167
+                'id' => $bundle->getIdentifier(),
168
+                'appIdentifiers' => $bundle->getAppIdentifiers()
169
+            ];
170
+        }
171
+        return $result;
172
+    }
173
+
174
+    /**
175
+     * Get all available categories
176
+     *
177
+     * @return JSONResponse
178
+     */
179
+    public function listCategories(): JSONResponse {
180
+        return new JSONResponse($this->getAllCategories());
181
+    }
182
+
183
+    private function getAllCategories() {
184
+        $currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
185
+
186
+        $formattedCategories = [];
187
+        $categories = $this->categoryFetcher->get();
188
+        foreach ($categories as $category) {
189
+            $formattedCategories[] = [
190
+                'id' => $category['id'],
191
+                'ident' => $category['id'],
192
+                'displayName' => isset($category['translations'][$currentLanguage]['name']) ? $category['translations'][$currentLanguage]['name'] : $category['translations']['en']['name'],
193
+            ];
194
+        }
195
+
196
+        return $formattedCategories;
197
+    }
198
+
199
+    private function fetchApps() {
200
+        $appClass = new \OC_App();
201
+        $apps = $appClass->listAllApps();
202
+        foreach ($apps as $app) {
203
+            $app['installed'] = true;
204
+            $this->allApps[$app['id']] = $app;
205
+        }
206
+
207
+        $apps = $this->getAppsForCategory('');
208
+        foreach ($apps as $app) {
209
+            $app['appstore'] = true;
210
+            if (!array_key_exists($app['id'], $this->allApps)) {
211
+                $this->allApps[$app['id']] = $app;
212
+            } else {
213
+                $this->allApps[$app['id']] = array_merge($app, $this->allApps[$app['id']]);
214
+            }
215
+        }
216
+
217
+        // add bundle information
218
+        $bundles = $this->bundleFetcher->getBundles();
219
+        foreach ($bundles as $bundle) {
220
+            foreach ($bundle->getAppIdentifiers() as $identifier) {
221
+                foreach ($this->allApps as &$app) {
222
+                    if ($app['id'] === $identifier) {
223
+                        $app['bundleIds'][] = $bundle->getIdentifier();
224
+                        continue;
225
+                    }
226
+                }
227
+            }
228
+        }
229
+    }
230
+
231
+    private function getAllApps() {
232
+        return $this->allApps;
233
+    }
234
+    /**
235
+     * Get all available apps in a category
236
+     *
237
+     * @param string $category
238
+     * @return JSONResponse
239
+     * @throws \Exception
240
+     */
241
+    public function listApps(): JSONResponse {
242
+        $this->fetchApps();
243
+        $apps = $this->getAllApps();
244
+
245
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n);
246
+
247
+        // Extend existing app details
248
+        $apps = array_map(function ($appData) use ($dependencyAnalyzer) {
249
+            if (isset($appData['appstoreData'])) {
250
+                $appstoreData = $appData['appstoreData'];
251
+                $appData['screenshot'] = isset($appstoreData['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/' . base64_encode($appstoreData['screenshots'][0]['url']) : '';
252
+                $appData['category'] = $appstoreData['categories'];
253
+                $appData['releases'] = $appstoreData['releases'];
254
+            }
255
+
256
+            $newVersion = $this->installer->isUpdateAvailable($appData['id']);
257
+            if ($newVersion) {
258
+                $appData['update'] = $newVersion;
259
+            }
260
+
261
+            // fix groups to be an array
262
+            $groups = [];
263
+            if (is_string($appData['groups'])) {
264
+                $groups = json_decode($appData['groups']);
265
+            }
266
+            $appData['groups'] = $groups;
267
+            $appData['canUnInstall'] = !$appData['active'] && $appData['removable'];
268
+
269
+            // fix licence vs license
270
+            if (isset($appData['license']) && !isset($appData['licence'])) {
271
+                $appData['licence'] = $appData['license'];
272
+            }
273
+
274
+            $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
275
+            if (!is_array($ignoreMaxApps)) {
276
+                $this->logger->warning('The value given for app_install_overwrite is not an array. Ignoring...');
277
+                $ignoreMaxApps = [];
278
+            }
279
+            $ignoreMax = in_array($appData['id'], $ignoreMaxApps);
280
+
281
+            // analyse dependencies
282
+            $missing = $dependencyAnalyzer->analyze($appData, $ignoreMax);
283
+            $appData['canInstall'] = empty($missing);
284
+            $appData['missingDependencies'] = $missing;
285
+
286
+            $appData['missingMinOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['min-version']);
287
+            $appData['missingMaxOwnCloudVersion'] = !isset($appData['dependencies']['nextcloud']['@attributes']['max-version']);
288
+            $appData['isCompatible'] = $dependencyAnalyzer->isMarkedCompatible($appData);
289
+
290
+            return $appData;
291
+        }, $apps);
292
+
293
+        usort($apps, [$this, 'sortApps']);
294
+
295
+        return new JSONResponse(['apps' => $apps, 'status' => 'success']);
296
+    }
297
+
298
+    /**
299
+     * Get all apps for a category from the app store
300
+     *
301
+     * @param string $requestedCategory
302
+     * @return array
303
+     * @throws \Exception
304
+     */
305
+    private function getAppsForCategory($requestedCategory = ''): array {
306
+        $versionParser = new VersionParser();
307
+        $formattedApps = [];
308
+        $apps = $this->appFetcher->get();
309
+        foreach ($apps as $app) {
310
+            // Skip all apps not in the requested category
311
+            if ($requestedCategory !== '') {
312
+                $isInCategory = false;
313
+                foreach ($app['categories'] as $category) {
314
+                    if ($category === $requestedCategory) {
315
+                        $isInCategory = true;
316
+                    }
317
+                }
318
+                if (!$isInCategory) {
319
+                    continue;
320
+                }
321
+            }
322
+
323
+            if (!isset($app['releases'][0]['rawPlatformVersionSpec'])) {
324
+                continue;
325
+            }
326
+            $nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
327
+            $nextCloudVersionDependencies = [];
328
+            if ($nextCloudVersion->getMinimumVersion() !== '') {
329
+                $nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
330
+            }
331
+            if ($nextCloudVersion->getMaximumVersion() !== '') {
332
+                $nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
333
+            }
334
+            $phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
335
+            $existsLocally = \OC_App::getAppPath($app['id']) !== false;
336
+            $phpDependencies = [];
337
+            if ($phpVersion->getMinimumVersion() !== '') {
338
+                $phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
339
+            }
340
+            if ($phpVersion->getMaximumVersion() !== '') {
341
+                $phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
342
+            }
343
+            if (isset($app['releases'][0]['minIntSize'])) {
344
+                $phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
345
+            }
346
+            $authors = '';
347
+            foreach ($app['authors'] as $key => $author) {
348
+                $authors .= $author['name'];
349
+                if ($key !== count($app['authors']) - 1) {
350
+                    $authors .= ', ';
351
+                }
352
+            }
353
+
354
+            $currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
355
+            $enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
356
+            $groups = null;
357
+            if ($enabledValue !== 'no' && $enabledValue !== 'yes') {
358
+                $groups = $enabledValue;
359
+            }
360
+
361
+            $currentVersion = '';
362
+            if ($this->appManager->isInstalled($app['id'])) {
363
+                $currentVersion = $this->appManager->getAppVersion($app['id']);
364
+            } else {
365
+                $currentLanguage = $app['releases'][0]['version'];
366
+            }
367
+
368
+            $formattedApps[] = [
369
+                'id' => $app['id'],
370
+                'name' => isset($app['translations'][$currentLanguage]['name']) ? $app['translations'][$currentLanguage]['name'] : $app['translations']['en']['name'],
371
+                'description' => isset($app['translations'][$currentLanguage]['description']) ? $app['translations'][$currentLanguage]['description'] : $app['translations']['en']['description'],
372
+                'summary' => isset($app['translations'][$currentLanguage]['summary']) ? $app['translations'][$currentLanguage]['summary'] : $app['translations']['en']['summary'],
373
+                'license' => $app['releases'][0]['licenses'],
374
+                'author' => $authors,
375
+                'shipped' => false,
376
+                'version' => $currentVersion,
377
+                'default_enable' => '',
378
+                'types' => [],
379
+                'documentation' => [
380
+                    'admin' => $app['adminDocs'],
381
+                    'user' => $app['userDocs'],
382
+                    'developer' => $app['developerDocs']
383
+                ],
384
+                'website' => $app['website'],
385
+                'bugs' => $app['issueTracker'],
386
+                'detailpage' => $app['website'],
387
+                'dependencies' => array_merge(
388
+                    $nextCloudVersionDependencies,
389
+                    $phpDependencies
390
+                ),
391
+                'level' => ($app['isFeatured'] === true) ? 200 : 100,
392
+                'missingMaxOwnCloudVersion' => false,
393
+                'missingMinOwnCloudVersion' => false,
394
+                'canInstall' => true,
395
+                'screenshot' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($app['screenshots'][0]['url']) : '',
396
+                'score' => $app['ratingOverall'],
397
+                'ratingNumOverall' => $app['ratingNumOverall'],
398
+                'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5,
399
+                'removable' => $existsLocally,
400
+                'active' => $this->appManager->isEnabledForUser($app['id']),
401
+                'needsDownload' => !$existsLocally,
402
+                'groups' => $groups,
403
+                'fromAppStore' => true,
404
+                'appstoreData' => $app,
405
+            ];
406
+        }
407
+
408
+        return $formattedApps;
409
+    }
410
+
411
+    /**
412
+     * @PasswordConfirmationRequired
413
+     *
414
+     * @param string $appId
415
+     * @param array $groups
416
+     * @return JSONResponse
417
+     */
418
+    public function enableApp(string $appId, array $groups = []): JSONResponse {
419
+        return $this->enableApps([$appId], $groups);
420
+    }
421
+
422
+    /**
423
+     * Enable one or more apps
424
+     *
425
+     * apps will be enabled for specific groups only if $groups is defined
426
+     *
427
+     * @PasswordConfirmationRequired
428
+     * @param array $appIds
429
+     * @param array $groups
430
+     * @return JSONResponse
431
+     */
432
+    public function enableApps(array $appIds, array $groups = []): JSONResponse {
433
+        try {
434
+            $updateRequired = false;
435
+
436
+            foreach ($appIds as $appId) {
437
+                $appId = OC_App::cleanAppId($appId);
438
+
439
+                // Check if app is already downloaded
440
+                /** @var Installer $installer */
441
+                $installer = \OC::$server->query(Installer::class);
442
+                $isDownloaded = $installer->isDownloaded($appId);
443
+
444
+                if (!$isDownloaded) {
445
+                    $installer->downloadApp($appId);
446
+                }
447
+
448
+                $installer->installApp($appId);
449
+
450
+                if (count($groups) > 0) {
451
+                    $this->appManager->enableAppForGroups($appId, $this->getGroupList($groups));
452
+                } else {
453
+                    $this->appManager->enableApp($appId);
454
+                }
455
+                if (\OC_App::shouldUpgrade($appId)) {
456
+                    $updateRequired = true;
457
+                }
458
+            }
459
+            return new JSONResponse(['data' => ['update_required' => $updateRequired]]);
460
+        } catch (\Exception $e) {
461
+            $this->logger->error('could not enable apps', ['exception' => $e]);
462
+            return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
463
+        }
464
+    }
465
+
466
+    private function getGroupList(array $groups) {
467
+        $groupManager = \OC::$server->getGroupManager();
468
+        $groupsList = [];
469
+        foreach ($groups as $group) {
470
+            $groupItem = $groupManager->get($group);
471
+            if ($groupItem instanceof \OCP\IGroup) {
472
+                $groupsList[] = $groupManager->get($group);
473
+            }
474
+        }
475
+        return $groupsList;
476
+    }
477
+
478
+    /**
479
+     * @PasswordConfirmationRequired
480
+     *
481
+     * @param string $appId
482
+     * @return JSONResponse
483
+     */
484
+    public function disableApp(string $appId): JSONResponse {
485
+        return $this->disableApps([$appId]);
486
+    }
487
+
488
+    /**
489
+     * @PasswordConfirmationRequired
490
+     *
491
+     * @param array $appIds
492
+     * @return JSONResponse
493
+     */
494
+    public function disableApps(array $appIds): JSONResponse {
495
+        try {
496
+            foreach ($appIds as $appId) {
497
+                $appId = OC_App::cleanAppId($appId);
498
+                $this->appManager->disableApp($appId);
499
+            }
500
+            return new JSONResponse([]);
501
+        } catch (\Exception $e) {
502
+            $this->logger->error('could not disable app', ['exception' => $e]);
503
+            return new JSONResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
504
+        }
505
+    }
506
+
507
+    /**
508
+     * @PasswordConfirmationRequired
509
+     *
510
+     * @param string $appId
511
+     * @return JSONResponse
512
+     */
513
+    public function uninstallApp(string $appId): JSONResponse {
514
+        $appId = OC_App::cleanAppId($appId);
515
+        $result = $this->installer->removeApp($appId);
516
+        if ($result !== false) {
517
+            $this->appManager->clearAppsCache();
518
+            return new JSONResponse(['data' => ['appid' => $appId]]);
519
+        }
520
+        return new JSONResponse(['data' => ['message' => $this->l10n->t('Couldn\'t remove app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
521
+    }
522
+
523
+    /**
524
+     * @param string $appId
525
+     * @return JSONResponse
526
+     */
527
+    public function updateApp(string $appId): JSONResponse {
528
+        $appId = OC_App::cleanAppId($appId);
529
+
530
+        $this->config->setSystemValue('maintenance', true);
531
+        try {
532
+            $result = $this->installer->updateAppstoreApp($appId);
533
+            $this->config->setSystemValue('maintenance', false);
534
+        } catch (\Exception $ex) {
535
+            $this->config->setSystemValue('maintenance', false);
536
+            return new JSONResponse(['data' => ['message' => $ex->getMessage()]], Http::STATUS_INTERNAL_SERVER_ERROR);
537
+        }
538
+
539
+        if ($result !== false) {
540
+            return new JSONResponse(['data' => ['appid' => $appId]]);
541
+        }
542
+        return new JSONResponse(['data' => ['message' => $this->l10n->t('Couldn\'t update app.')]], Http::STATUS_INTERNAL_SERVER_ERROR);
543
+    }
544
+
545
+    private function sortApps($a, $b) {
546
+        $a = (string)$a['name'];
547
+        $b = (string)$b['name'];
548
+        if ($a === $b) {
549
+            return 0;
550
+        }
551
+        return ($a < $b) ? -1 : 1;
552
+    }
553
+
554
+    public function force(string $appId): JSONResponse {
555
+        $appId = OC_App::cleanAppId($appId);
556
+        $this->appManager->ignoreNextcloudRequirementForApp($appId);
557
+        return new JSONResponse();
558
+    }
559 559
 }
Please login to merge, or discard this patch.