Passed
Push — master ( aeb32e...81302f )
by Christoph
15:20 queued 10s
created
lib/private/Installer.php 1 patch
Indentation   +578 added lines, -578 removed lines patch added patch discarded remove patch
@@ -59,582 +59,582 @@
 block discarded – undo
59 59
  * This class provides the functionality needed to install, update and remove apps
60 60
  */
61 61
 class Installer {
62
-	/** @var AppFetcher */
63
-	private $appFetcher;
64
-	/** @var IClientService */
65
-	private $clientService;
66
-	/** @var ITempManager */
67
-	private $tempManager;
68
-	/** @var ILogger */
69
-	private $logger;
70
-	/** @var IConfig */
71
-	private $config;
72
-	/** @var array - for caching the result of app fetcher */
73
-	private $apps = null;
74
-	/** @var bool|null - for caching the result of the ready status */
75
-	private $isInstanceReadyForUpdates = null;
76
-	/** @var bool */
77
-	private $isCLI;
78
-
79
-	/**
80
-	 * @param AppFetcher $appFetcher
81
-	 * @param IClientService $clientService
82
-	 * @param ITempManager $tempManager
83
-	 * @param ILogger $logger
84
-	 * @param IConfig $config
85
-	 */
86
-	public function __construct(
87
-		AppFetcher $appFetcher,
88
-		IClientService $clientService,
89
-		ITempManager $tempManager,
90
-		ILogger $logger,
91
-		IConfig $config,
92
-		bool $isCLI
93
-	) {
94
-		$this->appFetcher = $appFetcher;
95
-		$this->clientService = $clientService;
96
-		$this->tempManager = $tempManager;
97
-		$this->logger = $logger;
98
-		$this->config = $config;
99
-		$this->isCLI = $isCLI;
100
-	}
101
-
102
-	/**
103
-	 * Installs an app that is located in one of the app folders already
104
-	 *
105
-	 * @param string $appId App to install
106
-	 * @param bool $forceEnable
107
-	 * @throws \Exception
108
-	 * @return string app ID
109
-	 */
110
-	public function installApp(string $appId, bool $forceEnable = false): string {
111
-		$app = \OC_App::findAppInDirectories($appId);
112
-		if ($app === false) {
113
-			throw new \Exception('App not found in any app directory');
114
-		}
115
-
116
-		$basedir = $app['path'].'/'.$appId;
117
-		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
118
-
119
-		$l = \OC::$server->getL10N('core');
120
-
121
-		if (!is_array($info)) {
122
-			throw new \Exception(
123
-				$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
124
-					[$appId]
125
-				)
126
-			);
127
-		}
128
-
129
-		$ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
130
-		$ignoreMax = $forceEnable || in_array($appId, $ignoreMaxApps, true);
131
-
132
-		$version = implode('.', \OCP\Util::getVersion());
133
-		if (!\OC_App::isAppCompatible($version, $info, $ignoreMax)) {
134
-			throw new \Exception(
135
-				// TODO $l
136
-				$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
137
-					[$info['name']]
138
-				)
139
-			);
140
-		}
141
-
142
-		// check for required dependencies
143
-		\OC_App::checkAppDependencies($this->config, $l, $info, $ignoreMax);
144
-		/** @var Coordinator $coordinator */
145
-		$coordinator = \OC::$server->get(Coordinator::class);
146
-		$coordinator->runLazyRegistration($appId);
147
-		\OC_App::registerAutoloading($appId, $basedir);
148
-
149
-		$previousVersion = $this->config->getAppValue($info['id'], 'installed_version', false);
150
-		if ($previousVersion) {
151
-			OC_App::executeRepairSteps($appId, $info['repair-steps']['pre-migration']);
152
-		}
153
-
154
-		//install the database
155
-		if (is_file($basedir.'/appinfo/database.xml')) {
156
-			if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
157
-				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
158
-			} else {
159
-				OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
160
-			}
161
-		} else {
162
-			$ms = new \OC\DB\MigrationService($info['id'], \OC::$server->get(Connection::class));
163
-			$ms->migrate('latest', true);
164
-		}
165
-		if ($previousVersion) {
166
-			OC_App::executeRepairSteps($appId, $info['repair-steps']['post-migration']);
167
-		}
168
-
169
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
170
-
171
-		//run appinfo/install.php
172
-		self::includeAppScript($basedir . '/appinfo/install.php');
173
-
174
-		$appData = OC_App::getAppInfo($appId);
175
-		OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
176
-
177
-		//set the installed version
178
-		\OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
179
-		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
180
-
181
-		//set remote/public handlers
182
-		foreach ($info['remote'] as $name => $path) {
183
-			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
184
-		}
185
-		foreach ($info['public'] as $name => $path) {
186
-			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
187
-		}
188
-
189
-		OC_App::setAppTypes($info['id']);
190
-
191
-		return $info['id'];
192
-	}
193
-
194
-	/**
195
-	 * Updates the specified app from the appstore
196
-	 *
197
-	 * @param string $appId
198
-	 * @param bool [$allowUnstable] Allow unstable releases
199
-	 * @return bool
200
-	 */
201
-	public function updateAppstoreApp($appId, $allowUnstable = false) {
202
-		if ($this->isUpdateAvailable($appId, $allowUnstable)) {
203
-			try {
204
-				$this->downloadApp($appId, $allowUnstable);
205
-			} catch (\Exception $e) {
206
-				$this->logger->logException($e, [
207
-					'level' => ILogger::ERROR,
208
-					'app' => 'core',
209
-				]);
210
-				return false;
211
-			}
212
-			return OC_App::updateApp($appId);
213
-		}
214
-
215
-		return false;
216
-	}
217
-
218
-	/**
219
-	 * Downloads an app and puts it into the app directory
220
-	 *
221
-	 * @param string $appId
222
-	 * @param bool [$allowUnstable]
223
-	 *
224
-	 * @throws \Exception If the installation was not successful
225
-	 */
226
-	public function downloadApp($appId, $allowUnstable = false) {
227
-		$appId = strtolower($appId);
228
-
229
-		$apps = $this->appFetcher->get($allowUnstable);
230
-		foreach ($apps as $app) {
231
-			if ($app['id'] === $appId) {
232
-				// Load the certificate
233
-				$certificate = new X509();
234
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
235
-				$loadedCertificate = $certificate->loadX509($app['certificate']);
236
-
237
-				// Verify if the certificate has been revoked
238
-				$crl = new X509();
239
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
240
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
241
-				if ($crl->validateSignature() !== true) {
242
-					throw new \Exception('Could not validate CRL signature');
243
-				}
244
-				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
245
-				$revoked = $crl->getRevoked($csn);
246
-				if ($revoked !== false) {
247
-					throw new \Exception(
248
-						sprintf(
249
-							'Certificate "%s" has been revoked',
250
-							$csn
251
-						)
252
-					);
253
-				}
254
-
255
-				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
256
-				if ($certificate->validateSignature() !== true) {
257
-					throw new \Exception(
258
-						sprintf(
259
-							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
260
-							$appId
261
-						)
262
-					);
263
-				}
264
-
265
-				// Verify if the certificate is issued for the requested app id
266
-				$certInfo = openssl_x509_parse($app['certificate']);
267
-				if (!isset($certInfo['subject']['CN'])) {
268
-					throw new \Exception(
269
-						sprintf(
270
-							'App with id %s has a cert with no CN',
271
-							$appId
272
-						)
273
-					);
274
-				}
275
-				if ($certInfo['subject']['CN'] !== $appId) {
276
-					throw new \Exception(
277
-						sprintf(
278
-							'App with id %s has a cert issued to %s',
279
-							$appId,
280
-							$certInfo['subject']['CN']
281
-						)
282
-					);
283
-				}
284
-
285
-				// Download the release
286
-				$tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
287
-				$timeout = $this->isCLI ? 0 : 120;
288
-				$client = $this->clientService->newClient();
289
-				$client->get($app['releases'][0]['download'], ['save_to' => $tempFile, 'timeout' => $timeout]);
290
-
291
-				// Check if the signature actually matches the downloaded content
292
-				$certificate = openssl_get_publickey($app['certificate']);
293
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
294
-				openssl_free_key($certificate);
295
-
296
-				if ($verified === true) {
297
-					// Seems to match, let's proceed
298
-					$extractDir = $this->tempManager->getTemporaryFolder();
299
-					$archive = new TAR($tempFile);
300
-
301
-					if ($archive) {
302
-						if (!$archive->extract($extractDir)) {
303
-							$errorMessage = 'Could not extract app ' . $appId;
304
-
305
-							$archiveError = $archive->getError();
306
-							if ($archiveError instanceof \PEAR_Error) {
307
-								$errorMessage .= ': ' . $archiveError->getMessage();
308
-							}
309
-
310
-							throw new \Exception($errorMessage);
311
-						}
312
-						$allFiles = scandir($extractDir);
313
-						$folders = array_diff($allFiles, ['.', '..']);
314
-						$folders = array_values($folders);
315
-
316
-						if (count($folders) > 1) {
317
-							throw new \Exception(
318
-								sprintf(
319
-									'Extracted app %s has more than 1 folder',
320
-									$appId
321
-								)
322
-							);
323
-						}
324
-
325
-						// Check if appinfo/info.xml has the same app ID as well
326
-						$loadEntities = libxml_disable_entity_loader(false);
327
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
328
-						libxml_disable_entity_loader($loadEntities);
329
-						if ((string)$xml->id !== $appId) {
330
-							throw new \Exception(
331
-								sprintf(
332
-									'App for id %s has a wrong app ID in info.xml: %s',
333
-									$appId,
334
-									(string)$xml->id
335
-								)
336
-							);
337
-						}
338
-
339
-						// Check if the version is lower than before
340
-						$currentVersion = OC_App::getAppVersion($appId);
341
-						$newVersion = (string)$xml->version;
342
-						if (version_compare($currentVersion, $newVersion) === 1) {
343
-							throw new \Exception(
344
-								sprintf(
345
-									'App for id %s has version %s and tried to update to lower version %s',
346
-									$appId,
347
-									$currentVersion,
348
-									$newVersion
349
-								)
350
-							);
351
-						}
352
-
353
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
354
-						// Remove old app with the ID if existent
355
-						OC_Helper::rmdirr($baseDir);
356
-						// Move to app folder
357
-						if (@mkdir($baseDir)) {
358
-							$extractDir .= '/' . $folders[0];
359
-							OC_Helper::copyr($extractDir, $baseDir);
360
-						}
361
-						OC_Helper::copyr($extractDir, $baseDir);
362
-						OC_Helper::rmdirr($extractDir);
363
-						return;
364
-					} else {
365
-						throw new \Exception(
366
-							sprintf(
367
-								'Could not extract app with ID %s to %s',
368
-								$appId,
369
-								$extractDir
370
-							)
371
-						);
372
-					}
373
-				} else {
374
-					// Signature does not match
375
-					throw new \Exception(
376
-						sprintf(
377
-							'App with id %s has invalid signature',
378
-							$appId
379
-						)
380
-					);
381
-				}
382
-			}
383
-		}
384
-
385
-		throw new \Exception(
386
-			sprintf(
387
-				'Could not download app %s',
388
-				$appId
389
-			)
390
-		);
391
-	}
392
-
393
-	/**
394
-	 * Check if an update for the app is available
395
-	 *
396
-	 * @param string $appId
397
-	 * @param bool $allowUnstable
398
-	 * @return string|false false or the version number of the update
399
-	 */
400
-	public function isUpdateAvailable($appId, $allowUnstable = false) {
401
-		if ($this->isInstanceReadyForUpdates === null) {
402
-			$installPath = OC_App::getInstallPath();
403
-			if ($installPath === false || $installPath === null) {
404
-				$this->isInstanceReadyForUpdates = false;
405
-			} else {
406
-				$this->isInstanceReadyForUpdates = true;
407
-			}
408
-		}
409
-
410
-		if ($this->isInstanceReadyForUpdates === false) {
411
-			return false;
412
-		}
413
-
414
-		if ($this->isInstalledFromGit($appId) === true) {
415
-			return false;
416
-		}
417
-
418
-		if ($this->apps === null) {
419
-			$this->apps = $this->appFetcher->get($allowUnstable);
420
-		}
421
-
422
-		foreach ($this->apps as $app) {
423
-			if ($app['id'] === $appId) {
424
-				$currentVersion = OC_App::getAppVersion($appId);
425
-
426
-				if (!isset($app['releases'][0]['version'])) {
427
-					return false;
428
-				}
429
-				$newestVersion = $app['releases'][0]['version'];
430
-				if ($currentVersion !== '0' && version_compare($newestVersion, $currentVersion, '>')) {
431
-					return $newestVersion;
432
-				} else {
433
-					return false;
434
-				}
435
-			}
436
-		}
437
-
438
-		return false;
439
-	}
440
-
441
-	/**
442
-	 * Check if app has been installed from git
443
-	 * @param string $name name of the application to remove
444
-	 * @return boolean
445
-	 *
446
-	 * The function will check if the path contains a .git folder
447
-	 */
448
-	private function isInstalledFromGit($appId) {
449
-		$app = \OC_App::findAppInDirectories($appId);
450
-		if ($app === false) {
451
-			return false;
452
-		}
453
-		$basedir = $app['path'].'/'.$appId;
454
-		return file_exists($basedir.'/.git/');
455
-	}
456
-
457
-	/**
458
-	 * Check if app is already downloaded
459
-	 * @param string $name name of the application to remove
460
-	 * @return boolean
461
-	 *
462
-	 * The function will check if the app is already downloaded in the apps repository
463
-	 */
464
-	public function isDownloaded($name) {
465
-		foreach (\OC::$APPSROOTS as $dir) {
466
-			$dirToTest = $dir['path'];
467
-			$dirToTest .= '/';
468
-			$dirToTest .= $name;
469
-			$dirToTest .= '/';
470
-
471
-			if (is_dir($dirToTest)) {
472
-				return true;
473
-			}
474
-		}
475
-
476
-		return false;
477
-	}
478
-
479
-	/**
480
-	 * Removes an app
481
-	 * @param string $appId ID of the application to remove
482
-	 * @return boolean
483
-	 *
484
-	 *
485
-	 * This function works as follows
486
-	 *   -# call uninstall repair steps
487
-	 *   -# removing the files
488
-	 *
489
-	 * The function will not delete preferences, tables and the configuration,
490
-	 * this has to be done by the function oc_app_uninstall().
491
-	 */
492
-	public function removeApp($appId) {
493
-		if ($this->isDownloaded($appId)) {
494
-			if (\OC::$server->getAppManager()->isShipped($appId)) {
495
-				return false;
496
-			}
497
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
498
-			OC_Helper::rmdirr($appDir);
499
-			return true;
500
-		} else {
501
-			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', ILogger::ERROR);
502
-
503
-			return false;
504
-		}
505
-	}
506
-
507
-	/**
508
-	 * Installs the app within the bundle and marks the bundle as installed
509
-	 *
510
-	 * @param Bundle $bundle
511
-	 * @throws \Exception If app could not get installed
512
-	 */
513
-	public function installAppBundle(Bundle $bundle) {
514
-		$appIds = $bundle->getAppIdentifiers();
515
-		foreach ($appIds as $appId) {
516
-			if (!$this->isDownloaded($appId)) {
517
-				$this->downloadApp($appId);
518
-			}
519
-			$this->installApp($appId);
520
-			$app = new OC_App();
521
-			$app->enable($appId);
522
-		}
523
-		$bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
524
-		$bundles[] = $bundle->getIdentifier();
525
-		$this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
526
-	}
527
-
528
-	/**
529
-	 * Installs shipped apps
530
-	 *
531
-	 * This function installs all apps found in the 'apps' directory that should be enabled by default;
532
-	 * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
533
-	 *                         working ownCloud at the end instead of an aborted update.
534
-	 * @return array Array of error messages (appid => Exception)
535
-	 */
536
-	public static function installShippedApps($softErrors = false) {
537
-		$appManager = \OC::$server->getAppManager();
538
-		$config = \OC::$server->getConfig();
539
-		$errors = [];
540
-		foreach (\OC::$APPSROOTS as $app_dir) {
541
-			if ($dir = opendir($app_dir['path'])) {
542
-				while (false !== ($filename = readdir($dir))) {
543
-					if ($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) {
544
-						if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
545
-							if ($config->getAppValue($filename, "installed_version", null) === null) {
546
-								$info = OC_App::getAppInfo($filename);
547
-								$enabled = isset($info['default_enable']);
548
-								if (($enabled || in_array($filename, $appManager->getAlwaysEnabledApps()))
549
-									  && $config->getAppValue($filename, 'enabled') !== 'no') {
550
-									if ($softErrors) {
551
-										try {
552
-											Installer::installShippedApp($filename);
553
-										} catch (HintException $e) {
554
-											if ($e->getPrevious() instanceof TableExistsException) {
555
-												$errors[$filename] = $e;
556
-												continue;
557
-											}
558
-											throw $e;
559
-										}
560
-									} else {
561
-										Installer::installShippedApp($filename);
562
-									}
563
-									$config->setAppValue($filename, 'enabled', 'yes');
564
-								}
565
-							}
566
-						}
567
-					}
568
-				}
569
-				closedir($dir);
570
-			}
571
-		}
572
-
573
-		return $errors;
574
-	}
575
-
576
-	/**
577
-	 * install an app already placed in the app folder
578
-	 * @param string $app id of the app to install
579
-	 * @return integer
580
-	 */
581
-	public static function installShippedApp($app) {
582
-		//install the database
583
-		$appPath = OC_App::getAppPath($app);
584
-		\OC_App::registerAutoloading($app, $appPath);
585
-
586
-		if (is_file("$appPath/appinfo/database.xml")) {
587
-			try {
588
-				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
589
-			} catch (TableExistsException $e) {
590
-				throw new HintException(
591
-					'Failed to enable app ' . $app,
592
-					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
593
-					0, $e
594
-				);
595
-			}
596
-		} else {
597
-			$ms = new \OC\DB\MigrationService($app, \OC::$server->get(Connection::class));
598
-			$ms->migrate('latest', true);
599
-		}
600
-
601
-		//run appinfo/install.php
602
-		self::includeAppScript("$appPath/appinfo/install.php");
603
-
604
-		$info = OC_App::getAppInfo($app);
605
-		if (is_null($info)) {
606
-			return false;
607
-		}
608
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
609
-
610
-		OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
611
-
612
-		$config = \OC::$server->getConfig();
613
-
614
-		$config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
615
-		if (array_key_exists('ocsid', $info)) {
616
-			$config->setAppValue($app, 'ocsid', $info['ocsid']);
617
-		}
618
-
619
-		//set remote/public handlers
620
-		foreach ($info['remote'] as $name => $path) {
621
-			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
622
-		}
623
-		foreach ($info['public'] as $name => $path) {
624
-			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
625
-		}
626
-
627
-		OC_App::setAppTypes($info['id']);
628
-
629
-		return $info['id'];
630
-	}
631
-
632
-	/**
633
-	 * @param string $script
634
-	 */
635
-	private static function includeAppScript($script) {
636
-		if (file_exists($script)) {
637
-			include $script;
638
-		}
639
-	}
62
+    /** @var AppFetcher */
63
+    private $appFetcher;
64
+    /** @var IClientService */
65
+    private $clientService;
66
+    /** @var ITempManager */
67
+    private $tempManager;
68
+    /** @var ILogger */
69
+    private $logger;
70
+    /** @var IConfig */
71
+    private $config;
72
+    /** @var array - for caching the result of app fetcher */
73
+    private $apps = null;
74
+    /** @var bool|null - for caching the result of the ready status */
75
+    private $isInstanceReadyForUpdates = null;
76
+    /** @var bool */
77
+    private $isCLI;
78
+
79
+    /**
80
+     * @param AppFetcher $appFetcher
81
+     * @param IClientService $clientService
82
+     * @param ITempManager $tempManager
83
+     * @param ILogger $logger
84
+     * @param IConfig $config
85
+     */
86
+    public function __construct(
87
+        AppFetcher $appFetcher,
88
+        IClientService $clientService,
89
+        ITempManager $tempManager,
90
+        ILogger $logger,
91
+        IConfig $config,
92
+        bool $isCLI
93
+    ) {
94
+        $this->appFetcher = $appFetcher;
95
+        $this->clientService = $clientService;
96
+        $this->tempManager = $tempManager;
97
+        $this->logger = $logger;
98
+        $this->config = $config;
99
+        $this->isCLI = $isCLI;
100
+    }
101
+
102
+    /**
103
+     * Installs an app that is located in one of the app folders already
104
+     *
105
+     * @param string $appId App to install
106
+     * @param bool $forceEnable
107
+     * @throws \Exception
108
+     * @return string app ID
109
+     */
110
+    public function installApp(string $appId, bool $forceEnable = false): string {
111
+        $app = \OC_App::findAppInDirectories($appId);
112
+        if ($app === false) {
113
+            throw new \Exception('App not found in any app directory');
114
+        }
115
+
116
+        $basedir = $app['path'].'/'.$appId;
117
+        $info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
118
+
119
+        $l = \OC::$server->getL10N('core');
120
+
121
+        if (!is_array($info)) {
122
+            throw new \Exception(
123
+                $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
124
+                    [$appId]
125
+                )
126
+            );
127
+        }
128
+
129
+        $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
130
+        $ignoreMax = $forceEnable || in_array($appId, $ignoreMaxApps, true);
131
+
132
+        $version = implode('.', \OCP\Util::getVersion());
133
+        if (!\OC_App::isAppCompatible($version, $info, $ignoreMax)) {
134
+            throw new \Exception(
135
+                // TODO $l
136
+                $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
137
+                    [$info['name']]
138
+                )
139
+            );
140
+        }
141
+
142
+        // check for required dependencies
143
+        \OC_App::checkAppDependencies($this->config, $l, $info, $ignoreMax);
144
+        /** @var Coordinator $coordinator */
145
+        $coordinator = \OC::$server->get(Coordinator::class);
146
+        $coordinator->runLazyRegistration($appId);
147
+        \OC_App::registerAutoloading($appId, $basedir);
148
+
149
+        $previousVersion = $this->config->getAppValue($info['id'], 'installed_version', false);
150
+        if ($previousVersion) {
151
+            OC_App::executeRepairSteps($appId, $info['repair-steps']['pre-migration']);
152
+        }
153
+
154
+        //install the database
155
+        if (is_file($basedir.'/appinfo/database.xml')) {
156
+            if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
157
+                OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
158
+            } else {
159
+                OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
160
+            }
161
+        } else {
162
+            $ms = new \OC\DB\MigrationService($info['id'], \OC::$server->get(Connection::class));
163
+            $ms->migrate('latest', true);
164
+        }
165
+        if ($previousVersion) {
166
+            OC_App::executeRepairSteps($appId, $info['repair-steps']['post-migration']);
167
+        }
168
+
169
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
170
+
171
+        //run appinfo/install.php
172
+        self::includeAppScript($basedir . '/appinfo/install.php');
173
+
174
+        $appData = OC_App::getAppInfo($appId);
175
+        OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
176
+
177
+        //set the installed version
178
+        \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
179
+        \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
180
+
181
+        //set remote/public handlers
182
+        foreach ($info['remote'] as $name => $path) {
183
+            \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
184
+        }
185
+        foreach ($info['public'] as $name => $path) {
186
+            \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
187
+        }
188
+
189
+        OC_App::setAppTypes($info['id']);
190
+
191
+        return $info['id'];
192
+    }
193
+
194
+    /**
195
+     * Updates the specified app from the appstore
196
+     *
197
+     * @param string $appId
198
+     * @param bool [$allowUnstable] Allow unstable releases
199
+     * @return bool
200
+     */
201
+    public function updateAppstoreApp($appId, $allowUnstable = false) {
202
+        if ($this->isUpdateAvailable($appId, $allowUnstable)) {
203
+            try {
204
+                $this->downloadApp($appId, $allowUnstable);
205
+            } catch (\Exception $e) {
206
+                $this->logger->logException($e, [
207
+                    'level' => ILogger::ERROR,
208
+                    'app' => 'core',
209
+                ]);
210
+                return false;
211
+            }
212
+            return OC_App::updateApp($appId);
213
+        }
214
+
215
+        return false;
216
+    }
217
+
218
+    /**
219
+     * Downloads an app and puts it into the app directory
220
+     *
221
+     * @param string $appId
222
+     * @param bool [$allowUnstable]
223
+     *
224
+     * @throws \Exception If the installation was not successful
225
+     */
226
+    public function downloadApp($appId, $allowUnstable = false) {
227
+        $appId = strtolower($appId);
228
+
229
+        $apps = $this->appFetcher->get($allowUnstable);
230
+        foreach ($apps as $app) {
231
+            if ($app['id'] === $appId) {
232
+                // Load the certificate
233
+                $certificate = new X509();
234
+                $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
235
+                $loadedCertificate = $certificate->loadX509($app['certificate']);
236
+
237
+                // Verify if the certificate has been revoked
238
+                $crl = new X509();
239
+                $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
240
+                $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
241
+                if ($crl->validateSignature() !== true) {
242
+                    throw new \Exception('Could not validate CRL signature');
243
+                }
244
+                $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
245
+                $revoked = $crl->getRevoked($csn);
246
+                if ($revoked !== false) {
247
+                    throw new \Exception(
248
+                        sprintf(
249
+                            'Certificate "%s" has been revoked',
250
+                            $csn
251
+                        )
252
+                    );
253
+                }
254
+
255
+                // Verify if the certificate has been issued by the Nextcloud Code Authority CA
256
+                if ($certificate->validateSignature() !== true) {
257
+                    throw new \Exception(
258
+                        sprintf(
259
+                            'App with id %s has a certificate not issued by a trusted Code Signing Authority',
260
+                            $appId
261
+                        )
262
+                    );
263
+                }
264
+
265
+                // Verify if the certificate is issued for the requested app id
266
+                $certInfo = openssl_x509_parse($app['certificate']);
267
+                if (!isset($certInfo['subject']['CN'])) {
268
+                    throw new \Exception(
269
+                        sprintf(
270
+                            'App with id %s has a cert with no CN',
271
+                            $appId
272
+                        )
273
+                    );
274
+                }
275
+                if ($certInfo['subject']['CN'] !== $appId) {
276
+                    throw new \Exception(
277
+                        sprintf(
278
+                            'App with id %s has a cert issued to %s',
279
+                            $appId,
280
+                            $certInfo['subject']['CN']
281
+                        )
282
+                    );
283
+                }
284
+
285
+                // Download the release
286
+                $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
287
+                $timeout = $this->isCLI ? 0 : 120;
288
+                $client = $this->clientService->newClient();
289
+                $client->get($app['releases'][0]['download'], ['save_to' => $tempFile, 'timeout' => $timeout]);
290
+
291
+                // Check if the signature actually matches the downloaded content
292
+                $certificate = openssl_get_publickey($app['certificate']);
293
+                $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
294
+                openssl_free_key($certificate);
295
+
296
+                if ($verified === true) {
297
+                    // Seems to match, let's proceed
298
+                    $extractDir = $this->tempManager->getTemporaryFolder();
299
+                    $archive = new TAR($tempFile);
300
+
301
+                    if ($archive) {
302
+                        if (!$archive->extract($extractDir)) {
303
+                            $errorMessage = 'Could not extract app ' . $appId;
304
+
305
+                            $archiveError = $archive->getError();
306
+                            if ($archiveError instanceof \PEAR_Error) {
307
+                                $errorMessage .= ': ' . $archiveError->getMessage();
308
+                            }
309
+
310
+                            throw new \Exception($errorMessage);
311
+                        }
312
+                        $allFiles = scandir($extractDir);
313
+                        $folders = array_diff($allFiles, ['.', '..']);
314
+                        $folders = array_values($folders);
315
+
316
+                        if (count($folders) > 1) {
317
+                            throw new \Exception(
318
+                                sprintf(
319
+                                    'Extracted app %s has more than 1 folder',
320
+                                    $appId
321
+                                )
322
+                            );
323
+                        }
324
+
325
+                        // Check if appinfo/info.xml has the same app ID as well
326
+                        $loadEntities = libxml_disable_entity_loader(false);
327
+                        $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
328
+                        libxml_disable_entity_loader($loadEntities);
329
+                        if ((string)$xml->id !== $appId) {
330
+                            throw new \Exception(
331
+                                sprintf(
332
+                                    'App for id %s has a wrong app ID in info.xml: %s',
333
+                                    $appId,
334
+                                    (string)$xml->id
335
+                                )
336
+                            );
337
+                        }
338
+
339
+                        // Check if the version is lower than before
340
+                        $currentVersion = OC_App::getAppVersion($appId);
341
+                        $newVersion = (string)$xml->version;
342
+                        if (version_compare($currentVersion, $newVersion) === 1) {
343
+                            throw new \Exception(
344
+                                sprintf(
345
+                                    'App for id %s has version %s and tried to update to lower version %s',
346
+                                    $appId,
347
+                                    $currentVersion,
348
+                                    $newVersion
349
+                                )
350
+                            );
351
+                        }
352
+
353
+                        $baseDir = OC_App::getInstallPath() . '/' . $appId;
354
+                        // Remove old app with the ID if existent
355
+                        OC_Helper::rmdirr($baseDir);
356
+                        // Move to app folder
357
+                        if (@mkdir($baseDir)) {
358
+                            $extractDir .= '/' . $folders[0];
359
+                            OC_Helper::copyr($extractDir, $baseDir);
360
+                        }
361
+                        OC_Helper::copyr($extractDir, $baseDir);
362
+                        OC_Helper::rmdirr($extractDir);
363
+                        return;
364
+                    } else {
365
+                        throw new \Exception(
366
+                            sprintf(
367
+                                'Could not extract app with ID %s to %s',
368
+                                $appId,
369
+                                $extractDir
370
+                            )
371
+                        );
372
+                    }
373
+                } else {
374
+                    // Signature does not match
375
+                    throw new \Exception(
376
+                        sprintf(
377
+                            'App with id %s has invalid signature',
378
+                            $appId
379
+                        )
380
+                    );
381
+                }
382
+            }
383
+        }
384
+
385
+        throw new \Exception(
386
+            sprintf(
387
+                'Could not download app %s',
388
+                $appId
389
+            )
390
+        );
391
+    }
392
+
393
+    /**
394
+     * Check if an update for the app is available
395
+     *
396
+     * @param string $appId
397
+     * @param bool $allowUnstable
398
+     * @return string|false false or the version number of the update
399
+     */
400
+    public function isUpdateAvailable($appId, $allowUnstable = false) {
401
+        if ($this->isInstanceReadyForUpdates === null) {
402
+            $installPath = OC_App::getInstallPath();
403
+            if ($installPath === false || $installPath === null) {
404
+                $this->isInstanceReadyForUpdates = false;
405
+            } else {
406
+                $this->isInstanceReadyForUpdates = true;
407
+            }
408
+        }
409
+
410
+        if ($this->isInstanceReadyForUpdates === false) {
411
+            return false;
412
+        }
413
+
414
+        if ($this->isInstalledFromGit($appId) === true) {
415
+            return false;
416
+        }
417
+
418
+        if ($this->apps === null) {
419
+            $this->apps = $this->appFetcher->get($allowUnstable);
420
+        }
421
+
422
+        foreach ($this->apps as $app) {
423
+            if ($app['id'] === $appId) {
424
+                $currentVersion = OC_App::getAppVersion($appId);
425
+
426
+                if (!isset($app['releases'][0]['version'])) {
427
+                    return false;
428
+                }
429
+                $newestVersion = $app['releases'][0]['version'];
430
+                if ($currentVersion !== '0' && version_compare($newestVersion, $currentVersion, '>')) {
431
+                    return $newestVersion;
432
+                } else {
433
+                    return false;
434
+                }
435
+            }
436
+        }
437
+
438
+        return false;
439
+    }
440
+
441
+    /**
442
+     * Check if app has been installed from git
443
+     * @param string $name name of the application to remove
444
+     * @return boolean
445
+     *
446
+     * The function will check if the path contains a .git folder
447
+     */
448
+    private function isInstalledFromGit($appId) {
449
+        $app = \OC_App::findAppInDirectories($appId);
450
+        if ($app === false) {
451
+            return false;
452
+        }
453
+        $basedir = $app['path'].'/'.$appId;
454
+        return file_exists($basedir.'/.git/');
455
+    }
456
+
457
+    /**
458
+     * Check if app is already downloaded
459
+     * @param string $name name of the application to remove
460
+     * @return boolean
461
+     *
462
+     * The function will check if the app is already downloaded in the apps repository
463
+     */
464
+    public function isDownloaded($name) {
465
+        foreach (\OC::$APPSROOTS as $dir) {
466
+            $dirToTest = $dir['path'];
467
+            $dirToTest .= '/';
468
+            $dirToTest .= $name;
469
+            $dirToTest .= '/';
470
+
471
+            if (is_dir($dirToTest)) {
472
+                return true;
473
+            }
474
+        }
475
+
476
+        return false;
477
+    }
478
+
479
+    /**
480
+     * Removes an app
481
+     * @param string $appId ID of the application to remove
482
+     * @return boolean
483
+     *
484
+     *
485
+     * This function works as follows
486
+     *   -# call uninstall repair steps
487
+     *   -# removing the files
488
+     *
489
+     * The function will not delete preferences, tables and the configuration,
490
+     * this has to be done by the function oc_app_uninstall().
491
+     */
492
+    public function removeApp($appId) {
493
+        if ($this->isDownloaded($appId)) {
494
+            if (\OC::$server->getAppManager()->isShipped($appId)) {
495
+                return false;
496
+            }
497
+            $appDir = OC_App::getInstallPath() . '/' . $appId;
498
+            OC_Helper::rmdirr($appDir);
499
+            return true;
500
+        } else {
501
+            \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', ILogger::ERROR);
502
+
503
+            return false;
504
+        }
505
+    }
506
+
507
+    /**
508
+     * Installs the app within the bundle and marks the bundle as installed
509
+     *
510
+     * @param Bundle $bundle
511
+     * @throws \Exception If app could not get installed
512
+     */
513
+    public function installAppBundle(Bundle $bundle) {
514
+        $appIds = $bundle->getAppIdentifiers();
515
+        foreach ($appIds as $appId) {
516
+            if (!$this->isDownloaded($appId)) {
517
+                $this->downloadApp($appId);
518
+            }
519
+            $this->installApp($appId);
520
+            $app = new OC_App();
521
+            $app->enable($appId);
522
+        }
523
+        $bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
524
+        $bundles[] = $bundle->getIdentifier();
525
+        $this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
526
+    }
527
+
528
+    /**
529
+     * Installs shipped apps
530
+     *
531
+     * This function installs all apps found in the 'apps' directory that should be enabled by default;
532
+     * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
533
+     *                         working ownCloud at the end instead of an aborted update.
534
+     * @return array Array of error messages (appid => Exception)
535
+     */
536
+    public static function installShippedApps($softErrors = false) {
537
+        $appManager = \OC::$server->getAppManager();
538
+        $config = \OC::$server->getConfig();
539
+        $errors = [];
540
+        foreach (\OC::$APPSROOTS as $app_dir) {
541
+            if ($dir = opendir($app_dir['path'])) {
542
+                while (false !== ($filename = readdir($dir))) {
543
+                    if ($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) {
544
+                        if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
545
+                            if ($config->getAppValue($filename, "installed_version", null) === null) {
546
+                                $info = OC_App::getAppInfo($filename);
547
+                                $enabled = isset($info['default_enable']);
548
+                                if (($enabled || in_array($filename, $appManager->getAlwaysEnabledApps()))
549
+                                      && $config->getAppValue($filename, 'enabled') !== 'no') {
550
+                                    if ($softErrors) {
551
+                                        try {
552
+                                            Installer::installShippedApp($filename);
553
+                                        } catch (HintException $e) {
554
+                                            if ($e->getPrevious() instanceof TableExistsException) {
555
+                                                $errors[$filename] = $e;
556
+                                                continue;
557
+                                            }
558
+                                            throw $e;
559
+                                        }
560
+                                    } else {
561
+                                        Installer::installShippedApp($filename);
562
+                                    }
563
+                                    $config->setAppValue($filename, 'enabled', 'yes');
564
+                                }
565
+                            }
566
+                        }
567
+                    }
568
+                }
569
+                closedir($dir);
570
+            }
571
+        }
572
+
573
+        return $errors;
574
+    }
575
+
576
+    /**
577
+     * install an app already placed in the app folder
578
+     * @param string $app id of the app to install
579
+     * @return integer
580
+     */
581
+    public static function installShippedApp($app) {
582
+        //install the database
583
+        $appPath = OC_App::getAppPath($app);
584
+        \OC_App::registerAutoloading($app, $appPath);
585
+
586
+        if (is_file("$appPath/appinfo/database.xml")) {
587
+            try {
588
+                OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
589
+            } catch (TableExistsException $e) {
590
+                throw new HintException(
591
+                    'Failed to enable app ' . $app,
592
+                    'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
593
+                    0, $e
594
+                );
595
+            }
596
+        } else {
597
+            $ms = new \OC\DB\MigrationService($app, \OC::$server->get(Connection::class));
598
+            $ms->migrate('latest', true);
599
+        }
600
+
601
+        //run appinfo/install.php
602
+        self::includeAppScript("$appPath/appinfo/install.php");
603
+
604
+        $info = OC_App::getAppInfo($app);
605
+        if (is_null($info)) {
606
+            return false;
607
+        }
608
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
609
+
610
+        OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
611
+
612
+        $config = \OC::$server->getConfig();
613
+
614
+        $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
615
+        if (array_key_exists('ocsid', $info)) {
616
+            $config->setAppValue($app, 'ocsid', $info['ocsid']);
617
+        }
618
+
619
+        //set remote/public handlers
620
+        foreach ($info['remote'] as $name => $path) {
621
+            $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
622
+        }
623
+        foreach ($info['public'] as $name => $path) {
624
+            $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
625
+        }
626
+
627
+        OC_App::setAppTypes($info['id']);
628
+
629
+        return $info['id'];
630
+    }
631
+
632
+    /**
633
+     * @param string $script
634
+     */
635
+    private static function includeAppScript($script) {
636
+        if (file_exists($script)) {
637
+            include $script;
638
+        }
639
+    }
640 640
 }
Please login to merge, or discard this patch.
lib/private/AppConfig.php 1 patch
Indentation   +313 added lines, -313 removed lines patch added patch discarded remove patch
@@ -44,327 +44,327 @@
 block discarded – undo
44 44
  */
45 45
 class AppConfig implements IAppConfig {
46 46
 
47
-	/** @var array[] */
48
-	protected $sensitiveValues = [
49
-		'external' => [
50
-			'/^sites$/',
51
-		],
52
-		'spreed' => [
53
-			'/^bridge_bot_password/',
54
-			'/^signaling_servers$/',
55
-			'/^signaling_ticket_secret$/',
56
-			'/^stun_servers$/',
57
-			'/^turn_servers$/',
58
-			'/^turn_server_secret$/',
59
-		],
60
-		'theming' => [
61
-			'/^imprintUrl$/',
62
-			'/^privacyUrl$/',
63
-			'/^slogan$/',
64
-			'/^url$/',
65
-		],
66
-		'user_ldap' => [
67
-			'/^(s..)?ldap_agent_password$/',
68
-		],
69
-	];
70
-
71
-	/** @var Connection */
72
-	protected $conn;
73
-
74
-	/** @var array[] */
75
-	private $cache = [];
76
-
77
-	/** @var bool */
78
-	private $configLoaded = false;
79
-
80
-	/**
81
-	 * @param Connection $conn
82
-	 */
83
-	public function __construct(Connection $conn) {
84
-		$this->conn = $conn;
85
-	}
86
-
87
-	/**
88
-	 * @param string $app
89
-	 * @return array
90
-	 */
91
-	private function getAppValues($app) {
92
-		$this->loadConfigValues();
93
-
94
-		if (isset($this->cache[$app])) {
95
-			return $this->cache[$app];
96
-		}
97
-
98
-		return [];
99
-	}
100
-
101
-	/**
102
-	 * Get all apps using the config
103
-	 *
104
-	 * @return array an array of app ids
105
-	 *
106
-	 * This function returns a list of all apps that have at least one
107
-	 * entry in the appconfig table.
108
-	 */
109
-	public function getApps() {
110
-		$this->loadConfigValues();
111
-
112
-		return $this->getSortedKeys($this->cache);
113
-	}
114
-
115
-	/**
116
-	 * Get the available keys for an app
117
-	 *
118
-	 * @param string $app the app we are looking for
119
-	 * @return array an array of key names
120
-	 *
121
-	 * This function gets all keys of an app. Please note that the values are
122
-	 * not returned.
123
-	 */
124
-	public function getKeys($app) {
125
-		$this->loadConfigValues();
126
-
127
-		if (isset($this->cache[$app])) {
128
-			return $this->getSortedKeys($this->cache[$app]);
129
-		}
130
-
131
-		return [];
132
-	}
133
-
134
-	public function getSortedKeys($data) {
135
-		$keys = array_keys($data);
136
-		sort($keys);
137
-		return $keys;
138
-	}
139
-
140
-	/**
141
-	 * Gets the config value
142
-	 *
143
-	 * @param string $app app
144
-	 * @param string $key key
145
-	 * @param string $default = null, default value if the key does not exist
146
-	 * @return string the value or $default
147
-	 *
148
-	 * This function gets a value from the appconfig table. If the key does
149
-	 * not exist the default value will be returned
150
-	 */
151
-	public function getValue($app, $key, $default = null) {
152
-		$this->loadConfigValues();
153
-
154
-		if ($this->hasKey($app, $key)) {
155
-			return $this->cache[$app][$key];
156
-		}
157
-
158
-		return $default;
159
-	}
160
-
161
-	/**
162
-	 * check if a key is set in the appconfig
163
-	 *
164
-	 * @param string $app
165
-	 * @param string $key
166
-	 * @return bool
167
-	 */
168
-	public function hasKey($app, $key) {
169
-		$this->loadConfigValues();
170
-
171
-		return isset($this->cache[$app][$key]);
172
-	}
173
-
174
-	/**
175
-	 * Sets a value. If the key did not exist before it will be created.
176
-	 *
177
-	 * @param string $app app
178
-	 * @param string $key key
179
-	 * @param string|float|int $value value
180
-	 * @return bool True if the value was inserted or updated, false if the value was the same
181
-	 */
182
-	public function setValue($app, $key, $value) {
183
-		if (!$this->hasKey($app, $key)) {
184
-			$inserted = (bool) $this->conn->insertIfNotExist('*PREFIX*appconfig', [
185
-				'appid' => $app,
186
-				'configkey' => $key,
187
-				'configvalue' => $value,
188
-			], [
189
-				'appid',
190
-				'configkey',
191
-			]);
192
-
193
-			if ($inserted) {
194
-				if (!isset($this->cache[$app])) {
195
-					$this->cache[$app] = [];
196
-				}
197
-
198
-				$this->cache[$app][$key] = $value;
199
-				return true;
200
-			}
201
-		}
202
-
203
-		$sql = $this->conn->getQueryBuilder();
204
-		$sql->update('appconfig')
205
-			->set('configvalue', $sql->createNamedParameter($value))
206
-			->where($sql->expr()->eq('appid', $sql->createNamedParameter($app)))
207
-			->andWhere($sql->expr()->eq('configkey', $sql->createNamedParameter($key)));
208
-
209
-		/*
47
+    /** @var array[] */
48
+    protected $sensitiveValues = [
49
+        'external' => [
50
+            '/^sites$/',
51
+        ],
52
+        'spreed' => [
53
+            '/^bridge_bot_password/',
54
+            '/^signaling_servers$/',
55
+            '/^signaling_ticket_secret$/',
56
+            '/^stun_servers$/',
57
+            '/^turn_servers$/',
58
+            '/^turn_server_secret$/',
59
+        ],
60
+        'theming' => [
61
+            '/^imprintUrl$/',
62
+            '/^privacyUrl$/',
63
+            '/^slogan$/',
64
+            '/^url$/',
65
+        ],
66
+        'user_ldap' => [
67
+            '/^(s..)?ldap_agent_password$/',
68
+        ],
69
+    ];
70
+
71
+    /** @var Connection */
72
+    protected $conn;
73
+
74
+    /** @var array[] */
75
+    private $cache = [];
76
+
77
+    /** @var bool */
78
+    private $configLoaded = false;
79
+
80
+    /**
81
+     * @param Connection $conn
82
+     */
83
+    public function __construct(Connection $conn) {
84
+        $this->conn = $conn;
85
+    }
86
+
87
+    /**
88
+     * @param string $app
89
+     * @return array
90
+     */
91
+    private function getAppValues($app) {
92
+        $this->loadConfigValues();
93
+
94
+        if (isset($this->cache[$app])) {
95
+            return $this->cache[$app];
96
+        }
97
+
98
+        return [];
99
+    }
100
+
101
+    /**
102
+     * Get all apps using the config
103
+     *
104
+     * @return array an array of app ids
105
+     *
106
+     * This function returns a list of all apps that have at least one
107
+     * entry in the appconfig table.
108
+     */
109
+    public function getApps() {
110
+        $this->loadConfigValues();
111
+
112
+        return $this->getSortedKeys($this->cache);
113
+    }
114
+
115
+    /**
116
+     * Get the available keys for an app
117
+     *
118
+     * @param string $app the app we are looking for
119
+     * @return array an array of key names
120
+     *
121
+     * This function gets all keys of an app. Please note that the values are
122
+     * not returned.
123
+     */
124
+    public function getKeys($app) {
125
+        $this->loadConfigValues();
126
+
127
+        if (isset($this->cache[$app])) {
128
+            return $this->getSortedKeys($this->cache[$app]);
129
+        }
130
+
131
+        return [];
132
+    }
133
+
134
+    public function getSortedKeys($data) {
135
+        $keys = array_keys($data);
136
+        sort($keys);
137
+        return $keys;
138
+    }
139
+
140
+    /**
141
+     * Gets the config value
142
+     *
143
+     * @param string $app app
144
+     * @param string $key key
145
+     * @param string $default = null, default value if the key does not exist
146
+     * @return string the value or $default
147
+     *
148
+     * This function gets a value from the appconfig table. If the key does
149
+     * not exist the default value will be returned
150
+     */
151
+    public function getValue($app, $key, $default = null) {
152
+        $this->loadConfigValues();
153
+
154
+        if ($this->hasKey($app, $key)) {
155
+            return $this->cache[$app][$key];
156
+        }
157
+
158
+        return $default;
159
+    }
160
+
161
+    /**
162
+     * check if a key is set in the appconfig
163
+     *
164
+     * @param string $app
165
+     * @param string $key
166
+     * @return bool
167
+     */
168
+    public function hasKey($app, $key) {
169
+        $this->loadConfigValues();
170
+
171
+        return isset($this->cache[$app][$key]);
172
+    }
173
+
174
+    /**
175
+     * Sets a value. If the key did not exist before it will be created.
176
+     *
177
+     * @param string $app app
178
+     * @param string $key key
179
+     * @param string|float|int $value value
180
+     * @return bool True if the value was inserted or updated, false if the value was the same
181
+     */
182
+    public function setValue($app, $key, $value) {
183
+        if (!$this->hasKey($app, $key)) {
184
+            $inserted = (bool) $this->conn->insertIfNotExist('*PREFIX*appconfig', [
185
+                'appid' => $app,
186
+                'configkey' => $key,
187
+                'configvalue' => $value,
188
+            ], [
189
+                'appid',
190
+                'configkey',
191
+            ]);
192
+
193
+            if ($inserted) {
194
+                if (!isset($this->cache[$app])) {
195
+                    $this->cache[$app] = [];
196
+                }
197
+
198
+                $this->cache[$app][$key] = $value;
199
+                return true;
200
+            }
201
+        }
202
+
203
+        $sql = $this->conn->getQueryBuilder();
204
+        $sql->update('appconfig')
205
+            ->set('configvalue', $sql->createNamedParameter($value))
206
+            ->where($sql->expr()->eq('appid', $sql->createNamedParameter($app)))
207
+            ->andWhere($sql->expr()->eq('configkey', $sql->createNamedParameter($key)));
208
+
209
+        /*
210 210
 		 * Only limit to the existing value for non-Oracle DBs:
211 211
 		 * http://docs.oracle.com/cd/E11882_01/server.112/e26088/conditions002.htm#i1033286
212 212
 		 * > Large objects (LOBs) are not supported in comparison conditions.
213 213
 		 */
214
-		if (!($this->conn instanceof OracleConnection)) {
214
+        if (!($this->conn instanceof OracleConnection)) {
215 215
 
216
-			/*
216
+            /*
217 217
 			 * Only update the value when it is not the same
218 218
 			 * Note that NULL requires some special handling. Since comparing
219 219
 			 * against null can have special results.
220 220
 			 */
221 221
 
222
-			if ($value === null) {
223
-				$sql->andWhere(
224
-					$sql->expr()->isNotNull('configvalue')
225
-				);
226
-			} else {
227
-				$sql->andWhere(
228
-					$sql->expr()->orX(
229
-						$sql->expr()->isNull('configvalue'),
230
-						$sql->expr()->neq('configvalue', $sql->createNamedParameter($value))
231
-					)
232
-				);
233
-			}
234
-		}
235
-
236
-		$changedRow = (bool) $sql->execute();
237
-
238
-		$this->cache[$app][$key] = $value;
239
-
240
-		return $changedRow;
241
-	}
242
-
243
-	/**
244
-	 * Deletes a key
245
-	 *
246
-	 * @param string $app app
247
-	 * @param string $key key
248
-	 * @return boolean
249
-	 */
250
-	public function deleteKey($app, $key) {
251
-		$this->loadConfigValues();
252
-
253
-		$sql = $this->conn->getQueryBuilder();
254
-		$sql->delete('appconfig')
255
-			->where($sql->expr()->eq('appid', $sql->createParameter('app')))
256
-			->andWhere($sql->expr()->eq('configkey', $sql->createParameter('configkey')))
257
-			->setParameter('app', $app)
258
-			->setParameter('configkey', $key);
259
-		$sql->execute();
260
-
261
-		unset($this->cache[$app][$key]);
262
-		return false;
263
-	}
264
-
265
-	/**
266
-	 * Remove app from appconfig
267
-	 *
268
-	 * @param string $app app
269
-	 * @return boolean
270
-	 *
271
-	 * Removes all keys in appconfig belonging to the app.
272
-	 */
273
-	public function deleteApp($app) {
274
-		$this->loadConfigValues();
275
-
276
-		$sql = $this->conn->getQueryBuilder();
277
-		$sql->delete('appconfig')
278
-			->where($sql->expr()->eq('appid', $sql->createParameter('app')))
279
-			->setParameter('app', $app);
280
-		$sql->execute();
281
-
282
-		unset($this->cache[$app]);
283
-		return false;
284
-	}
285
-
286
-	/**
287
-	 * get multiple values, either the app or key can be used as wildcard by setting it to false
288
-	 *
289
-	 * @param string|false $app
290
-	 * @param string|false $key
291
-	 * @return array|false
292
-	 */
293
-	public function getValues($app, $key) {
294
-		if (($app !== false) === ($key !== false)) {
295
-			return false;
296
-		}
297
-
298
-		if ($key === false) {
299
-			return $this->getAppValues($app);
300
-		} else {
301
-			$appIds = $this->getApps();
302
-			$values = array_map(function ($appId) use ($key) {
303
-				return isset($this->cache[$appId][$key]) ? $this->cache[$appId][$key] : null;
304
-			}, $appIds);
305
-			$result = array_combine($appIds, $values);
306
-
307
-			return array_filter($result);
308
-		}
309
-	}
310
-
311
-	/**
312
-	 * get all values of the app or and filters out sensitive data
313
-	 *
314
-	 * @param string $app
315
-	 * @return array
316
-	 */
317
-	public function getFilteredValues($app) {
318
-		$values = $this->getValues($app, false);
319
-
320
-		if (isset($this->sensitiveValues[$app])) {
321
-			foreach ($this->sensitiveValues[$app] as $sensitiveKeyExp) {
322
-				$sensitiveKeys = preg_grep($sensitiveKeyExp, array_keys($values));
323
-				foreach ($sensitiveKeys as $sensitiveKey) {
324
-					$values[$sensitiveKey] = IConfig::SENSITIVE_VALUE;
325
-				}
326
-			}
327
-		}
328
-
329
-		return $values;
330
-	}
331
-
332
-	/**
333
-	 * Load all the app config values
334
-	 */
335
-	protected function loadConfigValues() {
336
-		if ($this->configLoaded) {
337
-			return;
338
-		}
339
-
340
-		$this->cache = [];
341
-
342
-		$sql = $this->conn->getQueryBuilder();
343
-		$sql->select('*')
344
-			->from('appconfig');
345
-		$result = $sql->execute();
346
-
347
-		// we are going to store the result in memory anyway
348
-		$rows = $result->fetchAll();
349
-		foreach ($rows as $row) {
350
-			if (!isset($this->cache[$row['appid']])) {
351
-				$this->cache[(string)$row['appid']] = [];
352
-			}
353
-
354
-			$this->cache[(string)$row['appid']][(string)$row['configkey']] = (string)$row['configvalue'];
355
-		}
356
-		$result->closeCursor();
357
-
358
-		$this->configLoaded = true;
359
-	}
360
-
361
-	/**
362
-	 * Clear all the cached app config values
363
-	 *
364
-	 * WARNING: do not use this - this is only for usage with the SCSSCacher to
365
-	 * clear the memory cache of the app config
366
-	 */
367
-	public function clearCachedConfig() {
368
-		$this->configLoaded = false;
369
-	}
222
+            if ($value === null) {
223
+                $sql->andWhere(
224
+                    $sql->expr()->isNotNull('configvalue')
225
+                );
226
+            } else {
227
+                $sql->andWhere(
228
+                    $sql->expr()->orX(
229
+                        $sql->expr()->isNull('configvalue'),
230
+                        $sql->expr()->neq('configvalue', $sql->createNamedParameter($value))
231
+                    )
232
+                );
233
+            }
234
+        }
235
+
236
+        $changedRow = (bool) $sql->execute();
237
+
238
+        $this->cache[$app][$key] = $value;
239
+
240
+        return $changedRow;
241
+    }
242
+
243
+    /**
244
+     * Deletes a key
245
+     *
246
+     * @param string $app app
247
+     * @param string $key key
248
+     * @return boolean
249
+     */
250
+    public function deleteKey($app, $key) {
251
+        $this->loadConfigValues();
252
+
253
+        $sql = $this->conn->getQueryBuilder();
254
+        $sql->delete('appconfig')
255
+            ->where($sql->expr()->eq('appid', $sql->createParameter('app')))
256
+            ->andWhere($sql->expr()->eq('configkey', $sql->createParameter('configkey')))
257
+            ->setParameter('app', $app)
258
+            ->setParameter('configkey', $key);
259
+        $sql->execute();
260
+
261
+        unset($this->cache[$app][$key]);
262
+        return false;
263
+    }
264
+
265
+    /**
266
+     * Remove app from appconfig
267
+     *
268
+     * @param string $app app
269
+     * @return boolean
270
+     *
271
+     * Removes all keys in appconfig belonging to the app.
272
+     */
273
+    public function deleteApp($app) {
274
+        $this->loadConfigValues();
275
+
276
+        $sql = $this->conn->getQueryBuilder();
277
+        $sql->delete('appconfig')
278
+            ->where($sql->expr()->eq('appid', $sql->createParameter('app')))
279
+            ->setParameter('app', $app);
280
+        $sql->execute();
281
+
282
+        unset($this->cache[$app]);
283
+        return false;
284
+    }
285
+
286
+    /**
287
+     * get multiple values, either the app or key can be used as wildcard by setting it to false
288
+     *
289
+     * @param string|false $app
290
+     * @param string|false $key
291
+     * @return array|false
292
+     */
293
+    public function getValues($app, $key) {
294
+        if (($app !== false) === ($key !== false)) {
295
+            return false;
296
+        }
297
+
298
+        if ($key === false) {
299
+            return $this->getAppValues($app);
300
+        } else {
301
+            $appIds = $this->getApps();
302
+            $values = array_map(function ($appId) use ($key) {
303
+                return isset($this->cache[$appId][$key]) ? $this->cache[$appId][$key] : null;
304
+            }, $appIds);
305
+            $result = array_combine($appIds, $values);
306
+
307
+            return array_filter($result);
308
+        }
309
+    }
310
+
311
+    /**
312
+     * get all values of the app or and filters out sensitive data
313
+     *
314
+     * @param string $app
315
+     * @return array
316
+     */
317
+    public function getFilteredValues($app) {
318
+        $values = $this->getValues($app, false);
319
+
320
+        if (isset($this->sensitiveValues[$app])) {
321
+            foreach ($this->sensitiveValues[$app] as $sensitiveKeyExp) {
322
+                $sensitiveKeys = preg_grep($sensitiveKeyExp, array_keys($values));
323
+                foreach ($sensitiveKeys as $sensitiveKey) {
324
+                    $values[$sensitiveKey] = IConfig::SENSITIVE_VALUE;
325
+                }
326
+            }
327
+        }
328
+
329
+        return $values;
330
+    }
331
+
332
+    /**
333
+     * Load all the app config values
334
+     */
335
+    protected function loadConfigValues() {
336
+        if ($this->configLoaded) {
337
+            return;
338
+        }
339
+
340
+        $this->cache = [];
341
+
342
+        $sql = $this->conn->getQueryBuilder();
343
+        $sql->select('*')
344
+            ->from('appconfig');
345
+        $result = $sql->execute();
346
+
347
+        // we are going to store the result in memory anyway
348
+        $rows = $result->fetchAll();
349
+        foreach ($rows as $row) {
350
+            if (!isset($this->cache[$row['appid']])) {
351
+                $this->cache[(string)$row['appid']] = [];
352
+            }
353
+
354
+            $this->cache[(string)$row['appid']][(string)$row['configkey']] = (string)$row['configvalue'];
355
+        }
356
+        $result->closeCursor();
357
+
358
+        $this->configLoaded = true;
359
+    }
360
+
361
+    /**
362
+     * Clear all the cached app config values
363
+     *
364
+     * WARNING: do not use this - this is only for usage with the SCSSCacher to
365
+     * clear the memory cache of the app config
366
+     */
367
+    public function clearCachedConfig() {
368
+        $this->configLoaded = false;
369
+    }
370 370
 }
Please login to merge, or discard this patch.
lib/private/legacy/OC_DB_StatementWrapper.php 1 patch
Indentation   +83 added lines, -83 removed lines patch added patch discarded remove patch
@@ -40,98 +40,98 @@
 block discarded – undo
40 40
  * @method array fetchAll(integer $fetchMode = null);
41 41
  */
42 42
 class OC_DB_StatementWrapper {
43
-	/** @var IPreparedStatement */
44
-	private $statement = null;
43
+    /** @var IPreparedStatement */
44
+    private $statement = null;
45 45
 
46
-	/** @var bool */
47
-	private $isManipulation = false;
46
+    /** @var bool */
47
+    private $isManipulation = false;
48 48
 
49
-	/** @var array */
50
-	private $lastArguments = [];
49
+    /** @var array */
50
+    private $lastArguments = [];
51 51
 
52
-	/**
53
-	 * @param IPreparedStatement $statement
54
-	 * @param boolean $isManipulation
55
-	 */
56
-	public function __construct(IPreparedStatement $statement, $isManipulation) {
57
-		$this->statement = $statement;
58
-		$this->isManipulation = $isManipulation;
59
-	}
52
+    /**
53
+     * @param IPreparedStatement $statement
54
+     * @param boolean $isManipulation
55
+     */
56
+    public function __construct(IPreparedStatement $statement, $isManipulation) {
57
+        $this->statement = $statement;
58
+        $this->isManipulation = $isManipulation;
59
+    }
60 60
 
61
-	/**
62
-	 * pass all other function directly to the \Doctrine\DBAL\Driver\Statement
63
-	 */
64
-	public function __call($name,$arguments) {
65
-		return call_user_func_array([$this->statement,$name], $arguments);
66
-	}
61
+    /**
62
+     * pass all other function directly to the \Doctrine\DBAL\Driver\Statement
63
+     */
64
+    public function __call($name,$arguments) {
65
+        return call_user_func_array([$this->statement,$name], $arguments);
66
+    }
67 67
 
68
-	/**
69
-	 * make execute return the result instead of a bool
70
-	 *
71
-	 * @param mixed[] $input
72
-	 * @return \OC_DB_StatementWrapper|int|bool
73
-	 * @deprecated
74
-	 */
75
-	public function execute($input = []) {
76
-		$this->lastArguments = $input;
77
-		try {
78
-			if (count($input) > 0) {
79
-				$result = $this->statement->execute($input);
80
-			} else {
81
-				$result = $this->statement->execute();
82
-			}
83
-		} catch (\Doctrine\DBAL\Exception $e) {
84
-			return false;
85
-		}
68
+    /**
69
+     * make execute return the result instead of a bool
70
+     *
71
+     * @param mixed[] $input
72
+     * @return \OC_DB_StatementWrapper|int|bool
73
+     * @deprecated
74
+     */
75
+    public function execute($input = []) {
76
+        $this->lastArguments = $input;
77
+        try {
78
+            if (count($input) > 0) {
79
+                $result = $this->statement->execute($input);
80
+            } else {
81
+                $result = $this->statement->execute();
82
+            }
83
+        } catch (\Doctrine\DBAL\Exception $e) {
84
+            return false;
85
+        }
86 86
 
87
-		if ($this->isManipulation) {
88
-			return $this->statement->rowCount();
89
-		}
87
+        if ($this->isManipulation) {
88
+            return $this->statement->rowCount();
89
+        }
90 90
 
91
-		return $this;
92
-	}
91
+        return $this;
92
+    }
93 93
 
94
-	/**
95
-	 * provide an alias for fetch
96
-	 *
97
-	 * @return mixed
98
-	 * @deprecated
99
-	 */
100
-	public function fetchRow() {
101
-		return $this->statement->fetch();
102
-	}
94
+    /**
95
+     * provide an alias for fetch
96
+     *
97
+     * @return mixed
98
+     * @deprecated
99
+     */
100
+    public function fetchRow() {
101
+        return $this->statement->fetch();
102
+    }
103 103
 
104
-	/**
105
-	 * Provide a simple fetchOne.
106
-	 *
107
-	 * fetch single column from the next row
108
-	 * @return string
109
-	 * @deprecated
110
-	 */
111
-	public function fetchOne() {
112
-		return $this->statement->fetchOne();
113
-	}
104
+    /**
105
+     * Provide a simple fetchOne.
106
+     *
107
+     * fetch single column from the next row
108
+     * @return string
109
+     * @deprecated
110
+     */
111
+    public function fetchOne() {
112
+        return $this->statement->fetchOne();
113
+    }
114 114
 
115
-	/**
116
-	 * Closes the cursor, enabling the statement to be executed again.
117
-	 *
118
-	 * @deprecated Use Result::free() instead.
119
-	 */
120
-	public function closeCursor(): void {
121
-		$this->statement->closeCursor();
122
-	}
115
+    /**
116
+     * Closes the cursor, enabling the statement to be executed again.
117
+     *
118
+     * @deprecated Use Result::free() instead.
119
+     */
120
+    public function closeCursor(): void {
121
+        $this->statement->closeCursor();
122
+    }
123 123
 
124
-	/**
125
-	 * Binds a PHP variable to a corresponding named or question mark placeholder in the
126
-	 * SQL statement that was use to prepare the statement.
127
-	 *
128
-	 * @param mixed $column Either the placeholder name or the 1-indexed placeholder index
129
-	 * @param mixed $variable The variable to bind
130
-	 * @param integer|null $type one of the  PDO::PARAM_* constants
131
-	 * @param integer|null $length max length when using an OUT bind
132
-	 * @return boolean
133
-	 */
134
-	public function bindParam($column, &$variable, $type = null, $length = null) {
135
-		return $this->statement->bindParam($column, $variable, $type, $length);
136
-	}
124
+    /**
125
+     * Binds a PHP variable to a corresponding named or question mark placeholder in the
126
+     * SQL statement that was use to prepare the statement.
127
+     *
128
+     * @param mixed $column Either the placeholder name or the 1-indexed placeholder index
129
+     * @param mixed $variable The variable to bind
130
+     * @param integer|null $type one of the  PDO::PARAM_* constants
131
+     * @param integer|null $length max length when using an OUT bind
132
+     * @return boolean
133
+     */
134
+    public function bindParam($column, &$variable, $type = null, $length = null) {
135
+        return $this->statement->bindParam($column, $variable, $type, $length);
136
+    }
137 137
 }
Please login to merge, or discard this patch.
lib/private/legacy/OC_Util.php 1 patch
Indentation   +1411 added lines, -1411 removed lines patch added patch discarded remove patch
@@ -73,1420 +73,1420 @@
 block discarded – undo
73 73
 use OCP\IUserSession;
74 74
 
75 75
 class OC_Util {
76
-	public static $scripts = [];
77
-	public static $styles = [];
78
-	public static $headers = [];
79
-	private static $rootMounted = false;
80
-	private static $fsSetup = false;
81
-
82
-	/** @var array Local cache of version.php */
83
-	private static $versionCache = null;
84
-
85
-	protected static function getAppManager() {
86
-		return \OC::$server->getAppManager();
87
-	}
88
-
89
-	private static function initLocalStorageRootFS() {
90
-		// mount local file backend as root
91
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
92
-		//first set up the local "root" storage
93
-		\OC\Files\Filesystem::initMountManager();
94
-		if (!self::$rootMounted) {
95
-			\OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
96
-			self::$rootMounted = true;
97
-		}
98
-	}
99
-
100
-	/**
101
-	 * mounting an object storage as the root fs will in essence remove the
102
-	 * necessity of a data folder being present.
103
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
104
-	 *
105
-	 * @param array $config containing 'class' and optional 'arguments'
106
-	 * @suppress PhanDeprecatedFunction
107
-	 */
108
-	private static function initObjectStoreRootFS($config) {
109
-		// check misconfiguration
110
-		if (empty($config['class'])) {
111
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
112
-		}
113
-		if (!isset($config['arguments'])) {
114
-			$config['arguments'] = [];
115
-		}
116
-
117
-		// instantiate object store implementation
118
-		$name = $config['class'];
119
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
120
-			$segments = explode('\\', $name);
121
-			OC_App::loadApp(strtolower($segments[1]));
122
-		}
123
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
124
-		// mount with plain / root object store implementation
125
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
126
-
127
-		// mount object storage as root
128
-		\OC\Files\Filesystem::initMountManager();
129
-		if (!self::$rootMounted) {
130
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
131
-			self::$rootMounted = true;
132
-		}
133
-	}
134
-
135
-	/**
136
-	 * mounting an object storage as the root fs will in essence remove the
137
-	 * necessity of a data folder being present.
138
-	 *
139
-	 * @param array $config containing 'class' and optional 'arguments'
140
-	 * @suppress PhanDeprecatedFunction
141
-	 */
142
-	private static function initObjectStoreMultibucketRootFS($config) {
143
-		// check misconfiguration
144
-		if (empty($config['class'])) {
145
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
146
-		}
147
-		if (!isset($config['arguments'])) {
148
-			$config['arguments'] = [];
149
-		}
150
-
151
-		// instantiate object store implementation
152
-		$name = $config['class'];
153
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
154
-			$segments = explode('\\', $name);
155
-			OC_App::loadApp(strtolower($segments[1]));
156
-		}
157
-
158
-		if (!isset($config['arguments']['bucket'])) {
159
-			$config['arguments']['bucket'] = '';
160
-		}
161
-		// put the root FS always in first bucket for multibucket configuration
162
-		$config['arguments']['bucket'] .= '0';
163
-
164
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
165
-		// mount with plain / root object store implementation
166
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
167
-
168
-		// mount object storage as root
169
-		\OC\Files\Filesystem::initMountManager();
170
-		if (!self::$rootMounted) {
171
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
172
-			self::$rootMounted = true;
173
-		}
174
-	}
175
-
176
-	/**
177
-	 * Can be set up
178
-	 *
179
-	 * @param string $user
180
-	 * @return boolean
181
-	 * @description configure the initial filesystem based on the configuration
182
-	 * @suppress PhanDeprecatedFunction
183
-	 * @suppress PhanAccessMethodInternal
184
-	 */
185
-	public static function setupFS($user = '') {
186
-		//setting up the filesystem twice can only lead to trouble
187
-		if (self::$fsSetup) {
188
-			return false;
189
-		}
190
-
191
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
192
-
193
-		// If we are not forced to load a specific user we load the one that is logged in
194
-		if ($user === null) {
195
-			$user = '';
196
-		} elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
197
-			$user = OC_User::getUser();
198
-		}
199
-
200
-		// load all filesystem apps before, so no setup-hook gets lost
201
-		OC_App::loadApps(['filesystem']);
202
-
203
-		// the filesystem will finish when $user is not empty,
204
-		// mark fs setup here to avoid doing the setup from loading
205
-		// OC_Filesystem
206
-		if ($user != '') {
207
-			self::$fsSetup = true;
208
-		}
209
-
210
-		\OC\Files\Filesystem::initMountManager();
211
-
212
-		$prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
213
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
214
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
215
-				/** @var \OC\Files\Storage\Common $storage */
216
-				$storage->setMountOptions($mount->getOptions());
217
-			}
218
-			return $storage;
219
-		});
220
-
221
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
222
-			if (!$mount->getOption('enable_sharing', true)) {
223
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
224
-					'storage' => $storage,
225
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
226
-				]);
227
-			}
228
-			return $storage;
229
-		});
230
-
231
-		// install storage availability wrapper, before most other wrappers
232
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
233
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
234
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
235
-			}
236
-			return $storage;
237
-		});
238
-
239
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
240
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
241
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
242
-			}
243
-			return $storage;
244
-		});
245
-
246
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
247
-			// set up quota for home storages, even for other users
248
-			// which can happen when using sharing
249
-
250
-			/**
251
-			 * @var \OC\Files\Storage\Storage $storage
252
-			 */
253
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
254
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
255
-			) {
256
-				/** @var \OC\Files\Storage\Home $storage */
257
-				if (is_object($storage->getUser())) {
258
-					$quota = OC_Util::getUserQuota($storage->getUser());
259
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
260
-						return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
261
-					}
262
-				}
263
-			}
264
-
265
-			return $storage;
266
-		});
267
-
268
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
269
-			/*
76
+    public static $scripts = [];
77
+    public static $styles = [];
78
+    public static $headers = [];
79
+    private static $rootMounted = false;
80
+    private static $fsSetup = false;
81
+
82
+    /** @var array Local cache of version.php */
83
+    private static $versionCache = null;
84
+
85
+    protected static function getAppManager() {
86
+        return \OC::$server->getAppManager();
87
+    }
88
+
89
+    private static function initLocalStorageRootFS() {
90
+        // mount local file backend as root
91
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
92
+        //first set up the local "root" storage
93
+        \OC\Files\Filesystem::initMountManager();
94
+        if (!self::$rootMounted) {
95
+            \OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
96
+            self::$rootMounted = true;
97
+        }
98
+    }
99
+
100
+    /**
101
+     * mounting an object storage as the root fs will in essence remove the
102
+     * necessity of a data folder being present.
103
+     * TODO make home storage aware of this and use the object storage instead of local disk access
104
+     *
105
+     * @param array $config containing 'class' and optional 'arguments'
106
+     * @suppress PhanDeprecatedFunction
107
+     */
108
+    private static function initObjectStoreRootFS($config) {
109
+        // check misconfiguration
110
+        if (empty($config['class'])) {
111
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
112
+        }
113
+        if (!isset($config['arguments'])) {
114
+            $config['arguments'] = [];
115
+        }
116
+
117
+        // instantiate object store implementation
118
+        $name = $config['class'];
119
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
120
+            $segments = explode('\\', $name);
121
+            OC_App::loadApp(strtolower($segments[1]));
122
+        }
123
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
124
+        // mount with plain / root object store implementation
125
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
126
+
127
+        // mount object storage as root
128
+        \OC\Files\Filesystem::initMountManager();
129
+        if (!self::$rootMounted) {
130
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
131
+            self::$rootMounted = true;
132
+        }
133
+    }
134
+
135
+    /**
136
+     * mounting an object storage as the root fs will in essence remove the
137
+     * necessity of a data folder being present.
138
+     *
139
+     * @param array $config containing 'class' and optional 'arguments'
140
+     * @suppress PhanDeprecatedFunction
141
+     */
142
+    private static function initObjectStoreMultibucketRootFS($config) {
143
+        // check misconfiguration
144
+        if (empty($config['class'])) {
145
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
146
+        }
147
+        if (!isset($config['arguments'])) {
148
+            $config['arguments'] = [];
149
+        }
150
+
151
+        // instantiate object store implementation
152
+        $name = $config['class'];
153
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
154
+            $segments = explode('\\', $name);
155
+            OC_App::loadApp(strtolower($segments[1]));
156
+        }
157
+
158
+        if (!isset($config['arguments']['bucket'])) {
159
+            $config['arguments']['bucket'] = '';
160
+        }
161
+        // put the root FS always in first bucket for multibucket configuration
162
+        $config['arguments']['bucket'] .= '0';
163
+
164
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
165
+        // mount with plain / root object store implementation
166
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
167
+
168
+        // mount object storage as root
169
+        \OC\Files\Filesystem::initMountManager();
170
+        if (!self::$rootMounted) {
171
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
172
+            self::$rootMounted = true;
173
+        }
174
+    }
175
+
176
+    /**
177
+     * Can be set up
178
+     *
179
+     * @param string $user
180
+     * @return boolean
181
+     * @description configure the initial filesystem based on the configuration
182
+     * @suppress PhanDeprecatedFunction
183
+     * @suppress PhanAccessMethodInternal
184
+     */
185
+    public static function setupFS($user = '') {
186
+        //setting up the filesystem twice can only lead to trouble
187
+        if (self::$fsSetup) {
188
+            return false;
189
+        }
190
+
191
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
192
+
193
+        // If we are not forced to load a specific user we load the one that is logged in
194
+        if ($user === null) {
195
+            $user = '';
196
+        } elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
197
+            $user = OC_User::getUser();
198
+        }
199
+
200
+        // load all filesystem apps before, so no setup-hook gets lost
201
+        OC_App::loadApps(['filesystem']);
202
+
203
+        // the filesystem will finish when $user is not empty,
204
+        // mark fs setup here to avoid doing the setup from loading
205
+        // OC_Filesystem
206
+        if ($user != '') {
207
+            self::$fsSetup = true;
208
+        }
209
+
210
+        \OC\Files\Filesystem::initMountManager();
211
+
212
+        $prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
213
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
214
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
215
+                /** @var \OC\Files\Storage\Common $storage */
216
+                $storage->setMountOptions($mount->getOptions());
217
+            }
218
+            return $storage;
219
+        });
220
+
221
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
222
+            if (!$mount->getOption('enable_sharing', true)) {
223
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
224
+                    'storage' => $storage,
225
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
226
+                ]);
227
+            }
228
+            return $storage;
229
+        });
230
+
231
+        // install storage availability wrapper, before most other wrappers
232
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
233
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
234
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
235
+            }
236
+            return $storage;
237
+        });
238
+
239
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
240
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
241
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
242
+            }
243
+            return $storage;
244
+        });
245
+
246
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
247
+            // set up quota for home storages, even for other users
248
+            // which can happen when using sharing
249
+
250
+            /**
251
+             * @var \OC\Files\Storage\Storage $storage
252
+             */
253
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
254
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
255
+            ) {
256
+                /** @var \OC\Files\Storage\Home $storage */
257
+                if (is_object($storage->getUser())) {
258
+                    $quota = OC_Util::getUserQuota($storage->getUser());
259
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
260
+                        return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
261
+                    }
262
+                }
263
+            }
264
+
265
+            return $storage;
266
+        });
267
+
268
+        \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
269
+            /*
270 270
 			 * Do not allow any operations that modify the storage
271 271
 			 */
272
-			if ($mount->getOption('readonly', false)) {
273
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
274
-					'storage' => $storage,
275
-					'mask' => \OCP\Constants::PERMISSION_ALL & ~(
276
-						\OCP\Constants::PERMISSION_UPDATE |
277
-						\OCP\Constants::PERMISSION_CREATE |
278
-						\OCP\Constants::PERMISSION_DELETE
279
-					),
280
-				]);
281
-			}
282
-			return $storage;
283
-		});
284
-
285
-		OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
286
-
287
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
288
-
289
-		//check if we are using an object storage
290
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
291
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
292
-
293
-		// use the same order as in ObjectHomeMountProvider
294
-		if (isset($objectStoreMultibucket)) {
295
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
296
-		} elseif (isset($objectStore)) {
297
-			self::initObjectStoreRootFS($objectStore);
298
-		} else {
299
-			self::initLocalStorageRootFS();
300
-		}
301
-
302
-		/** @var \OCP\Files\Config\IMountProviderCollection $mountProviderCollection */
303
-		$mountProviderCollection = \OC::$server->query(\OCP\Files\Config\IMountProviderCollection::class);
304
-		$rootMountProviders = $mountProviderCollection->getRootMounts();
305
-
306
-		/** @var \OC\Files\Mount\Manager $mountManager */
307
-		$mountManager = \OC\Files\Filesystem::getMountManager();
308
-		foreach ($rootMountProviders as $rootMountProvider) {
309
-			$mountManager->addMount($rootMountProvider);
310
-		}
311
-
312
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
313
-			\OC::$server->getEventLogger()->end('setup_fs');
314
-			return false;
315
-		}
316
-
317
-		//if we aren't logged in, there is no use to set up the filesystem
318
-		if ($user != "") {
319
-			$userDir = '/' . $user . '/files';
320
-
321
-			//jail the user into his "home" directory
322
-			\OC\Files\Filesystem::init($user, $userDir);
323
-
324
-			OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
325
-		}
326
-		\OC::$server->getEventLogger()->end('setup_fs');
327
-		return true;
328
-	}
329
-
330
-	/**
331
-	 * check if a password is required for each public link
332
-	 *
333
-	 * @return boolean
334
-	 * @suppress PhanDeprecatedFunction
335
-	 */
336
-	public static function isPublicLinkPasswordRequired() {
337
-		$enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
338
-		return $enforcePassword === 'yes';
339
-	}
340
-
341
-	/**
342
-	 * check if sharing is disabled for the current user
343
-	 * @param IConfig $config
344
-	 * @param IGroupManager $groupManager
345
-	 * @param IUser|null $user
346
-	 * @return bool
347
-	 */
348
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
349
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
350
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
351
-			$excludedGroups = json_decode($groupsList);
352
-			if (is_null($excludedGroups)) {
353
-				$excludedGroups = explode(',', $groupsList);
354
-				$newValue = json_encode($excludedGroups);
355
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
356
-			}
357
-			$usersGroups = $groupManager->getUserGroupIds($user);
358
-			if (!empty($usersGroups)) {
359
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
360
-				// if the user is only in groups which are disabled for sharing then
361
-				// sharing is also disabled for the user
362
-				if (empty($remainingGroups)) {
363
-					return true;
364
-				}
365
-			}
366
-		}
367
-		return false;
368
-	}
369
-
370
-	/**
371
-	 * check if share API enforces a default expire date
372
-	 *
373
-	 * @return boolean
374
-	 * @suppress PhanDeprecatedFunction
375
-	 */
376
-	public static function isDefaultExpireDateEnforced() {
377
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
378
-		$enforceDefaultExpireDate = false;
379
-		if ($isDefaultExpireDateEnabled === 'yes') {
380
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
381
-			$enforceDefaultExpireDate = $value === 'yes';
382
-		}
383
-
384
-		return $enforceDefaultExpireDate;
385
-	}
386
-
387
-	/**
388
-	 * Get the quota of a user
389
-	 *
390
-	 * @param IUser|null $user
391
-	 * @return float Quota bytes
392
-	 */
393
-	public static function getUserQuota(?IUser $user) {
394
-		if (is_null($user)) {
395
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
396
-		}
397
-		$userQuota = $user->getQuota();
398
-		if ($userQuota === 'none') {
399
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
400
-		}
401
-		return OC_Helper::computerFileSize($userQuota);
402
-	}
403
-
404
-	/**
405
-	 * copies the skeleton to the users /files
406
-	 *
407
-	 * @param string $userId
408
-	 * @param \OCP\Files\Folder $userDirectory
409
-	 * @throws \OCP\Files\NotFoundException
410
-	 * @throws \OCP\Files\NotPermittedException
411
-	 * @suppress PhanDeprecatedFunction
412
-	 */
413
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
414
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
415
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
416
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
417
-
418
-		if (!file_exists($skeletonDirectory)) {
419
-			$dialectStart = strpos($userLang, '_');
420
-			if ($dialectStart !== false) {
421
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
422
-			}
423
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
424
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
425
-			}
426
-			if (!file_exists($skeletonDirectory)) {
427
-				$skeletonDirectory = '';
428
-			}
429
-		}
430
-
431
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
432
-
433
-		if ($instanceId === null) {
434
-			throw new \RuntimeException('no instance id!');
435
-		}
436
-		$appdata = 'appdata_' . $instanceId;
437
-		if ($userId === $appdata) {
438
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
439
-		}
440
-
441
-		if (!empty($skeletonDirectory)) {
442
-			\OCP\Util::writeLog(
443
-				'files_skeleton',
444
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
445
-				ILogger::DEBUG
446
-			);
447
-			self::copyr($skeletonDirectory, $userDirectory);
448
-			// update the file cache
449
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
450
-		}
451
-	}
452
-
453
-	/**
454
-	 * copies a directory recursively by using streams
455
-	 *
456
-	 * @param string $source
457
-	 * @param \OCP\Files\Folder $target
458
-	 * @return void
459
-	 */
460
-	public static function copyr($source, \OCP\Files\Folder $target) {
461
-		$logger = \OC::$server->getLogger();
462
-
463
-		// Verify if folder exists
464
-		$dir = opendir($source);
465
-		if ($dir === false) {
466
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
467
-			return;
468
-		}
469
-
470
-		// Copy the files
471
-		while (false !== ($file = readdir($dir))) {
472
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
473
-				if (is_dir($source . '/' . $file)) {
474
-					$child = $target->newFolder($file);
475
-					self::copyr($source . '/' . $file, $child);
476
-				} else {
477
-					$child = $target->newFile($file);
478
-					$sourceStream = fopen($source . '/' . $file, 'r');
479
-					if ($sourceStream === false) {
480
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
481
-						closedir($dir);
482
-						return;
483
-					}
484
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
485
-				}
486
-			}
487
-		}
488
-		closedir($dir);
489
-	}
490
-
491
-	/**
492
-	 * @return void
493
-	 * @suppress PhanUndeclaredMethod
494
-	 */
495
-	public static function tearDownFS() {
496
-		\OC\Files\Filesystem::tearDown();
497
-		\OC::$server->getRootFolder()->clearCache();
498
-		self::$fsSetup = false;
499
-		self::$rootMounted = false;
500
-	}
501
-
502
-	/**
503
-	 * get the current installed version of ownCloud
504
-	 *
505
-	 * @return array
506
-	 */
507
-	public static function getVersion() {
508
-		OC_Util::loadVersion();
509
-		return self::$versionCache['OC_Version'];
510
-	}
511
-
512
-	/**
513
-	 * get the current installed version string of ownCloud
514
-	 *
515
-	 * @return string
516
-	 */
517
-	public static function getVersionString() {
518
-		OC_Util::loadVersion();
519
-		return self::$versionCache['OC_VersionString'];
520
-	}
521
-
522
-	/**
523
-	 * @deprecated the value is of no use anymore
524
-	 * @return string
525
-	 */
526
-	public static function getEditionString() {
527
-		return '';
528
-	}
529
-
530
-	/**
531
-	 * @description get the update channel of the current installed of ownCloud.
532
-	 * @return string
533
-	 */
534
-	public static function getChannel() {
535
-		OC_Util::loadVersion();
536
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
537
-	}
538
-
539
-	/**
540
-	 * @description get the build number of the current installed of ownCloud.
541
-	 * @return string
542
-	 */
543
-	public static function getBuild() {
544
-		OC_Util::loadVersion();
545
-		return self::$versionCache['OC_Build'];
546
-	}
547
-
548
-	/**
549
-	 * @description load the version.php into the session as cache
550
-	 * @suppress PhanUndeclaredVariable
551
-	 */
552
-	private static function loadVersion() {
553
-		if (self::$versionCache !== null) {
554
-			return;
555
-		}
556
-
557
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
558
-		require OC::$SERVERROOT . '/version.php';
559
-		/** @var int $timestamp */
560
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
561
-		/** @var string $OC_Version */
562
-		self::$versionCache['OC_Version'] = $OC_Version;
563
-		/** @var string $OC_VersionString */
564
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
565
-		/** @var string $OC_Build */
566
-		self::$versionCache['OC_Build'] = $OC_Build;
567
-
568
-		/** @var string $OC_Channel */
569
-		self::$versionCache['OC_Channel'] = $OC_Channel;
570
-	}
571
-
572
-	/**
573
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
574
-	 *
575
-	 * @param string $application application to get the files from
576
-	 * @param string $directory directory within this application (css, js, vendor, etc)
577
-	 * @param string $file the file inside of the above folder
578
-	 * @return string the path
579
-	 */
580
-	private static function generatePath($application, $directory, $file) {
581
-		if (is_null($file)) {
582
-			$file = $application;
583
-			$application = "";
584
-		}
585
-		if (!empty($application)) {
586
-			return "$application/$directory/$file";
587
-		} else {
588
-			return "$directory/$file";
589
-		}
590
-	}
591
-
592
-	/**
593
-	 * add a javascript file
594
-	 *
595
-	 * @param string $application application id
596
-	 * @param string|null $file filename
597
-	 * @param bool $prepend prepend the Script to the beginning of the list
598
-	 * @return void
599
-	 */
600
-	public static function addScript($application, $file = null, $prepend = false) {
601
-		$path = OC_Util::generatePath($application, 'js', $file);
602
-
603
-		// core js files need separate handling
604
-		if ($application !== 'core' && $file !== null) {
605
-			self::addTranslations($application);
606
-		}
607
-		self::addExternalResource($application, $prepend, $path, "script");
608
-	}
609
-
610
-	/**
611
-	 * add a javascript file from the vendor sub folder
612
-	 *
613
-	 * @param string $application application id
614
-	 * @param string|null $file filename
615
-	 * @param bool $prepend prepend the Script to the beginning of the list
616
-	 * @return void
617
-	 */
618
-	public static function addVendorScript($application, $file = null, $prepend = false) {
619
-		$path = OC_Util::generatePath($application, 'vendor', $file);
620
-		self::addExternalResource($application, $prepend, $path, "script");
621
-	}
622
-
623
-	/**
624
-	 * add a translation JS file
625
-	 *
626
-	 * @param string $application application id
627
-	 * @param string|null $languageCode language code, defaults to the current language
628
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
629
-	 */
630
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
631
-		if (is_null($languageCode)) {
632
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
633
-		}
634
-		if (!empty($application)) {
635
-			$path = "$application/l10n/$languageCode";
636
-		} else {
637
-			$path = "l10n/$languageCode";
638
-		}
639
-		self::addExternalResource($application, $prepend, $path, "script");
640
-	}
641
-
642
-	/**
643
-	 * add a css file
644
-	 *
645
-	 * @param string $application application id
646
-	 * @param string|null $file filename
647
-	 * @param bool $prepend prepend the Style to the beginning of the list
648
-	 * @return void
649
-	 */
650
-	public static function addStyle($application, $file = null, $prepend = false) {
651
-		$path = OC_Util::generatePath($application, 'css', $file);
652
-		self::addExternalResource($application, $prepend, $path, "style");
653
-	}
654
-
655
-	/**
656
-	 * add a css file from the vendor sub folder
657
-	 *
658
-	 * @param string $application application id
659
-	 * @param string|null $file filename
660
-	 * @param bool $prepend prepend the Style to the beginning of the list
661
-	 * @return void
662
-	 */
663
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
664
-		$path = OC_Util::generatePath($application, 'vendor', $file);
665
-		self::addExternalResource($application, $prepend, $path, "style");
666
-	}
667
-
668
-	/**
669
-	 * add an external resource css/js file
670
-	 *
671
-	 * @param string $application application id
672
-	 * @param bool $prepend prepend the file to the beginning of the list
673
-	 * @param string $path
674
-	 * @param string $type (script or style)
675
-	 * @return void
676
-	 */
677
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
678
-		if ($type === "style") {
679
-			if (!in_array($path, self::$styles)) {
680
-				if ($prepend === true) {
681
-					array_unshift(self::$styles, $path);
682
-				} else {
683
-					self::$styles[] = $path;
684
-				}
685
-			}
686
-		} elseif ($type === "script") {
687
-			if (!in_array($path, self::$scripts)) {
688
-				if ($prepend === true) {
689
-					array_unshift(self::$scripts, $path);
690
-				} else {
691
-					self::$scripts [] = $path;
692
-				}
693
-			}
694
-		}
695
-	}
696
-
697
-	/**
698
-	 * Add a custom element to the header
699
-	 * If $text is null then the element will be written as empty element.
700
-	 * So use "" to get a closing tag.
701
-	 * @param string $tag tag name of the element
702
-	 * @param array $attributes array of attributes for the element
703
-	 * @param string $text the text content for the element
704
-	 * @param bool $prepend prepend the header to the beginning of the list
705
-	 */
706
-	public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
707
-		$header = [
708
-			'tag' => $tag,
709
-			'attributes' => $attributes,
710
-			'text' => $text
711
-		];
712
-		if ($prepend === true) {
713
-			array_unshift(self::$headers, $header);
714
-		} else {
715
-			self::$headers[] = $header;
716
-		}
717
-	}
718
-
719
-	/**
720
-	 * check if the current server configuration is suitable for ownCloud
721
-	 *
722
-	 * @param \OC\SystemConfig $config
723
-	 * @return array arrays with error messages and hints
724
-	 */
725
-	public static function checkServer(\OC\SystemConfig $config) {
726
-		$l = \OC::$server->getL10N('lib');
727
-		$errors = [];
728
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
729
-
730
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
731
-			// this check needs to be done every time
732
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
733
-		}
734
-
735
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
736
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
737
-			return $errors;
738
-		}
739
-
740
-		$webServerRestart = false;
741
-		$setup = new \OC\Setup(
742
-			$config,
743
-			\OC::$server->get(IniGetWrapper::class),
744
-			\OC::$server->getL10N('lib'),
745
-			\OC::$server->query(\OCP\Defaults::class),
746
-			\OC::$server->getLogger(),
747
-			\OC::$server->getSecureRandom(),
748
-			\OC::$server->query(\OC\Installer::class)
749
-		);
750
-
751
-		$urlGenerator = \OC::$server->getURLGenerator();
752
-
753
-		$availableDatabases = $setup->getSupportedDatabases();
754
-		if (empty($availableDatabases)) {
755
-			$errors[] = [
756
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
757
-				'hint' => '' //TODO: sane hint
758
-			];
759
-			$webServerRestart = true;
760
-		}
761
-
762
-		// Check if config folder is writable.
763
-		if (!OC_Helper::isReadOnlyConfigEnabled()) {
764
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
765
-				$errors[] = [
766
-					'error' => $l->t('Cannot write into "config" directory'),
767
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
768
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
769
-						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
770
-						[ $urlGenerator->linkToDocs('admin-config') ])
771
-				];
772
-			}
773
-		}
774
-
775
-		// Check if there is a writable install folder.
776
-		if ($config->getValue('appstoreenabled', true)) {
777
-			if (OC_App::getInstallPath() === null
778
-				|| !is_writable(OC_App::getInstallPath())
779
-				|| !is_readable(OC_App::getInstallPath())
780
-			) {
781
-				$errors[] = [
782
-					'error' => $l->t('Cannot write into "apps" directory'),
783
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
784
-						. ' or disabling the appstore in the config file.')
785
-				];
786
-			}
787
-		}
788
-		// Create root dir.
789
-		if ($config->getValue('installed', false)) {
790
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
791
-				$success = @mkdir($CONFIG_DATADIRECTORY);
792
-				if ($success) {
793
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
794
-				} else {
795
-					$errors[] = [
796
-						'error' => $l->t('Cannot create "data" directory'),
797
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
798
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
799
-					];
800
-				}
801
-			} elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
802
-				// is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
803
-				$testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
804
-				$handle = fopen($testFile, 'w');
805
-				if (!$handle || fwrite($handle, 'Test write operation') === false) {
806
-					$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
807
-						[$urlGenerator->linkToDocs('admin-dir_permissions')]);
808
-					$errors[] = [
809
-						'error' => 'Your data directory is not writable',
810
-						'hint' => $permissionsHint
811
-					];
812
-				} else {
813
-					fclose($handle);
814
-					unlink($testFile);
815
-				}
816
-			} else {
817
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
818
-			}
819
-		}
820
-
821
-		if (!OC_Util::isSetLocaleWorking()) {
822
-			$errors[] = [
823
-				'error' => $l->t('Setting locale to %s failed',
824
-					['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
825
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
826
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
827
-			];
828
-		}
829
-
830
-		// Contains the dependencies that should be checked against
831
-		// classes = class_exists
832
-		// functions = function_exists
833
-		// defined = defined
834
-		// ini = ini_get
835
-		// If the dependency is not found the missing module name is shown to the EndUser
836
-		// When adding new checks always verify that they pass on Travis as well
837
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
838
-		$dependencies = [
839
-			'classes' => [
840
-				'ZipArchive' => 'zip',
841
-				'DOMDocument' => 'dom',
842
-				'XMLWriter' => 'XMLWriter',
843
-				'XMLReader' => 'XMLReader',
844
-			],
845
-			'functions' => [
846
-				'xml_parser_create' => 'libxml',
847
-				'mb_strcut' => 'mbstring',
848
-				'ctype_digit' => 'ctype',
849
-				'json_encode' => 'JSON',
850
-				'gd_info' => 'GD',
851
-				'gzencode' => 'zlib',
852
-				'iconv' => 'iconv',
853
-				'simplexml_load_string' => 'SimpleXML',
854
-				'hash' => 'HASH Message Digest Framework',
855
-				'curl_init' => 'cURL',
856
-				'openssl_verify' => 'OpenSSL',
857
-			],
858
-			'defined' => [
859
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
860
-			],
861
-			'ini' => [
862
-				'default_charset' => 'UTF-8',
863
-			],
864
-		];
865
-		$missingDependencies = [];
866
-		$invalidIniSettings = [];
867
-
868
-		$iniWrapper = \OC::$server->get(IniGetWrapper::class);
869
-		foreach ($dependencies['classes'] as $class => $module) {
870
-			if (!class_exists($class)) {
871
-				$missingDependencies[] = $module;
872
-			}
873
-		}
874
-		foreach ($dependencies['functions'] as $function => $module) {
875
-			if (!function_exists($function)) {
876
-				$missingDependencies[] = $module;
877
-			}
878
-		}
879
-		foreach ($dependencies['defined'] as $defined => $module) {
880
-			if (!defined($defined)) {
881
-				$missingDependencies[] = $module;
882
-			}
883
-		}
884
-		foreach ($dependencies['ini'] as $setting => $expected) {
885
-			if (is_bool($expected)) {
886
-				if ($iniWrapper->getBool($setting) !== $expected) {
887
-					$invalidIniSettings[] = [$setting, $expected];
888
-				}
889
-			}
890
-			if (is_int($expected)) {
891
-				if ($iniWrapper->getNumeric($setting) !== $expected) {
892
-					$invalidIniSettings[] = [$setting, $expected];
893
-				}
894
-			}
895
-			if (is_string($expected)) {
896
-				if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
897
-					$invalidIniSettings[] = [$setting, $expected];
898
-				}
899
-			}
900
-		}
901
-
902
-		foreach ($missingDependencies as $missingDependency) {
903
-			$errors[] = [
904
-				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
905
-				'hint' => $l->t('Please ask your server administrator to install the module.'),
906
-			];
907
-			$webServerRestart = true;
908
-		}
909
-		foreach ($invalidIniSettings as $setting) {
910
-			if (is_bool($setting[1])) {
911
-				$setting[1] = $setting[1] ? 'on' : 'off';
912
-			}
913
-			$errors[] = [
914
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
915
-				'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
916
-			];
917
-			$webServerRestart = true;
918
-		}
919
-
920
-		/**
921
-		 * The mbstring.func_overload check can only be performed if the mbstring
922
-		 * module is installed as it will return null if the checking setting is
923
-		 * not available and thus a check on the boolean value fails.
924
-		 *
925
-		 * TODO: Should probably be implemented in the above generic dependency
926
-		 *       check somehow in the long-term.
927
-		 */
928
-		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
929
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
930
-			$errors[] = [
931
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
932
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
933
-			];
934
-		}
935
-
936
-		if (function_exists('xml_parser_create') &&
937
-			LIBXML_LOADED_VERSION < 20700) {
938
-			$version = LIBXML_LOADED_VERSION;
939
-			$major = floor($version / 10000);
940
-			$version -= ($major * 10000);
941
-			$minor = floor($version / 100);
942
-			$version -= ($minor * 100);
943
-			$patch = $version;
944
-			$errors[] = [
945
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
946
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
947
-			];
948
-		}
949
-
950
-		if (!self::isAnnotationsWorking()) {
951
-			$errors[] = [
952
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
953
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
954
-			];
955
-		}
956
-
957
-		if (!\OC::$CLI && $webServerRestart) {
958
-			$errors[] = [
959
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
960
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
961
-			];
962
-		}
963
-
964
-		$errors = array_merge($errors, self::checkDatabaseVersion());
965
-
966
-		// Cache the result of this function
967
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
968
-
969
-		return $errors;
970
-	}
971
-
972
-	/**
973
-	 * Check the database version
974
-	 *
975
-	 * @return array errors array
976
-	 */
977
-	public static function checkDatabaseVersion() {
978
-		$l = \OC::$server->getL10N('lib');
979
-		$errors = [];
980
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
981
-		if ($dbType === 'pgsql') {
982
-			// check PostgreSQL version
983
-			try {
984
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
985
-				$data = $result->fetchRow();
986
-				$result->closeCursor();
987
-				if (isset($data['server_version'])) {
988
-					$version = $data['server_version'];
989
-					if (version_compare($version, '9.0.0', '<')) {
990
-						$errors[] = [
991
-							'error' => $l->t('PostgreSQL >= 9 required'),
992
-							'hint' => $l->t('Please upgrade your database version')
993
-						];
994
-					}
995
-				}
996
-			} catch (\Doctrine\DBAL\Exception $e) {
997
-				$logger = \OC::$server->getLogger();
998
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
999
-				$logger->logException($e);
1000
-			}
1001
-		}
1002
-		return $errors;
1003
-	}
1004
-
1005
-	/**
1006
-	 * Check for correct file permissions of data directory
1007
-	 *
1008
-	 * @param string $dataDirectory
1009
-	 * @return array arrays with error messages and hints
1010
-	 */
1011
-	public static function checkDataDirectoryPermissions($dataDirectory) {
1012
-		if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1013
-			return  [];
1014
-		}
1015
-
1016
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1017
-		if (substr($perms, -1) !== '0') {
1018
-			chmod($dataDirectory, 0770);
1019
-			clearstatcache();
1020
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1021
-			if ($perms[2] !== '0') {
1022
-				$l = \OC::$server->getL10N('lib');
1023
-				return [[
1024
-					'error' => $l->t('Your data directory is readable by other users'),
1025
-					'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1026
-				]];
1027
-			}
1028
-		}
1029
-		return [];
1030
-	}
1031
-
1032
-	/**
1033
-	 * Check that the data directory exists and is valid by
1034
-	 * checking the existence of the ".ocdata" file.
1035
-	 *
1036
-	 * @param string $dataDirectory data directory path
1037
-	 * @return array errors found
1038
-	 */
1039
-	public static function checkDataDirectoryValidity($dataDirectory) {
1040
-		$l = \OC::$server->getL10N('lib');
1041
-		$errors = [];
1042
-		if ($dataDirectory[0] !== '/') {
1043
-			$errors[] = [
1044
-				'error' => $l->t('Your data directory must be an absolute path'),
1045
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1046
-			];
1047
-		}
1048
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1049
-			$errors[] = [
1050
-				'error' => $l->t('Your data directory is invalid'),
1051
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1052
-					' in the root of the data directory.')
1053
-			];
1054
-		}
1055
-		return $errors;
1056
-	}
1057
-
1058
-	/**
1059
-	 * Check if the user is logged in, redirects to home if not. With
1060
-	 * redirect URL parameter to the request URI.
1061
-	 *
1062
-	 * @return void
1063
-	 */
1064
-	public static function checkLoggedIn() {
1065
-		// Check if we are a user
1066
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1067
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1068
-						'core.login.showLoginForm',
1069
-						[
1070
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1071
-						]
1072
-					)
1073
-			);
1074
-			exit();
1075
-		}
1076
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1077
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1078
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1079
-			exit();
1080
-		}
1081
-	}
1082
-
1083
-	/**
1084
-	 * Check if the user is a admin, redirects to home if not
1085
-	 *
1086
-	 * @return void
1087
-	 */
1088
-	public static function checkAdminUser() {
1089
-		OC_Util::checkLoggedIn();
1090
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1091
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1092
-			exit();
1093
-		}
1094
-	}
1095
-
1096
-	/**
1097
-	 * Returns the URL of the default page
1098
-	 * based on the system configuration and
1099
-	 * the apps visible for the current user
1100
-	 *
1101
-	 * @return string URL
1102
-	 * @suppress PhanDeprecatedFunction
1103
-	 */
1104
-	public static function getDefaultPageUrl() {
1105
-		/** @var IConfig $config */
1106
-		$config = \OC::$server->get(IConfig::class);
1107
-		$urlGenerator = \OC::$server->getURLGenerator();
1108
-		// Deny the redirect if the URL contains a @
1109
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1110
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1111
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1112
-		} else {
1113
-			$defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1114
-			if ($defaultPage) {
1115
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1116
-			} else {
1117
-				$appId = 'files';
1118
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'dashboard,files'));
1119
-
1120
-				/** @var IUserSession $userSession */
1121
-				$userSession = \OC::$server->get(IUserSession::class);
1122
-				$user = $userSession->getUser();
1123
-				if ($user) {
1124
-					$userDefaultApps = explode(',', $config->getUserValue($user->getUID(), 'core', 'defaultapp'));
1125
-					$defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
1126
-				}
1127
-
1128
-				// find the first app that is enabled for the current user
1129
-				foreach ($defaultApps as $defaultApp) {
1130
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1131
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1132
-						$appId = $defaultApp;
1133
-						break;
1134
-					}
1135
-				}
1136
-
1137
-				if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1138
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1139
-				} else {
1140
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1141
-				}
1142
-			}
1143
-		}
1144
-		return $location;
1145
-	}
1146
-
1147
-	/**
1148
-	 * Redirect to the user default page
1149
-	 *
1150
-	 * @return void
1151
-	 */
1152
-	public static function redirectToDefaultPage() {
1153
-		$location = self::getDefaultPageUrl();
1154
-		header('Location: ' . $location);
1155
-		exit();
1156
-	}
1157
-
1158
-	/**
1159
-	 * get an id unique for this instance
1160
-	 *
1161
-	 * @return string
1162
-	 */
1163
-	public static function getInstanceId() {
1164
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1165
-		if (is_null($id)) {
1166
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1167
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1168
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1169
-		}
1170
-		return $id;
1171
-	}
1172
-
1173
-	/**
1174
-	 * Public function to sanitize HTML
1175
-	 *
1176
-	 * This function is used to sanitize HTML and should be applied on any
1177
-	 * string or array of strings before displaying it on a web page.
1178
-	 *
1179
-	 * @param string|array $value
1180
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1181
-	 */
1182
-	public static function sanitizeHTML($value) {
1183
-		if (is_array($value)) {
1184
-			$value = array_map(function ($value) {
1185
-				return self::sanitizeHTML($value);
1186
-			}, $value);
1187
-		} else {
1188
-			// Specify encoding for PHP<5.4
1189
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1190
-		}
1191
-		return $value;
1192
-	}
1193
-
1194
-	/**
1195
-	 * Public function to encode url parameters
1196
-	 *
1197
-	 * This function is used to encode path to file before output.
1198
-	 * Encoding is done according to RFC 3986 with one exception:
1199
-	 * Character '/' is preserved as is.
1200
-	 *
1201
-	 * @param string $component part of URI to encode
1202
-	 * @return string
1203
-	 */
1204
-	public static function encodePath($component) {
1205
-		$encoded = rawurlencode($component);
1206
-		$encoded = str_replace('%2F', '/', $encoded);
1207
-		return $encoded;
1208
-	}
1209
-
1210
-
1211
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1212
-		// php dev server does not support htaccess
1213
-		if (php_sapi_name() === 'cli-server') {
1214
-			return false;
1215
-		}
1216
-
1217
-		// testdata
1218
-		$fileName = '/htaccesstest.txt';
1219
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1220
-
1221
-		// creating a test file
1222
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1223
-
1224
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1225
-			return false;
1226
-		}
1227
-
1228
-		$fp = @fopen($testFile, 'w');
1229
-		if (!$fp) {
1230
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1231
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1232
-		}
1233
-		fwrite($fp, $testContent);
1234
-		fclose($fp);
1235
-
1236
-		return $testContent;
1237
-	}
1238
-
1239
-	/**
1240
-	 * Check if the .htaccess file is working
1241
-	 * @param \OCP\IConfig $config
1242
-	 * @return bool
1243
-	 * @throws Exception
1244
-	 * @throws \OC\HintException If the test file can't get written.
1245
-	 */
1246
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1247
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1248
-			return true;
1249
-		}
1250
-
1251
-		$testContent = $this->createHtaccessTestFile($config);
1252
-		if ($testContent === false) {
1253
-			return false;
1254
-		}
1255
-
1256
-		$fileName = '/htaccesstest.txt';
1257
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1258
-
1259
-		// accessing the file via http
1260
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1261
-		try {
1262
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1263
-		} catch (\Exception $e) {
1264
-			$content = false;
1265
-		}
1266
-
1267
-		if (strpos($url, 'https:') === 0) {
1268
-			$url = 'http:' . substr($url, 6);
1269
-		} else {
1270
-			$url = 'https:' . substr($url, 5);
1271
-		}
1272
-
1273
-		try {
1274
-			$fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1275
-		} catch (\Exception $e) {
1276
-			$fallbackContent = false;
1277
-		}
1278
-
1279
-		// cleanup
1280
-		@unlink($testFile);
1281
-
1282
-		/*
272
+            if ($mount->getOption('readonly', false)) {
273
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
274
+                    'storage' => $storage,
275
+                    'mask' => \OCP\Constants::PERMISSION_ALL & ~(
276
+                        \OCP\Constants::PERMISSION_UPDATE |
277
+                        \OCP\Constants::PERMISSION_CREATE |
278
+                        \OCP\Constants::PERMISSION_DELETE
279
+                    ),
280
+                ]);
281
+            }
282
+            return $storage;
283
+        });
284
+
285
+        OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
286
+
287
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
288
+
289
+        //check if we are using an object storage
290
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
291
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
292
+
293
+        // use the same order as in ObjectHomeMountProvider
294
+        if (isset($objectStoreMultibucket)) {
295
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
296
+        } elseif (isset($objectStore)) {
297
+            self::initObjectStoreRootFS($objectStore);
298
+        } else {
299
+            self::initLocalStorageRootFS();
300
+        }
301
+
302
+        /** @var \OCP\Files\Config\IMountProviderCollection $mountProviderCollection */
303
+        $mountProviderCollection = \OC::$server->query(\OCP\Files\Config\IMountProviderCollection::class);
304
+        $rootMountProviders = $mountProviderCollection->getRootMounts();
305
+
306
+        /** @var \OC\Files\Mount\Manager $mountManager */
307
+        $mountManager = \OC\Files\Filesystem::getMountManager();
308
+        foreach ($rootMountProviders as $rootMountProvider) {
309
+            $mountManager->addMount($rootMountProvider);
310
+        }
311
+
312
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
313
+            \OC::$server->getEventLogger()->end('setup_fs');
314
+            return false;
315
+        }
316
+
317
+        //if we aren't logged in, there is no use to set up the filesystem
318
+        if ($user != "") {
319
+            $userDir = '/' . $user . '/files';
320
+
321
+            //jail the user into his "home" directory
322
+            \OC\Files\Filesystem::init($user, $userDir);
323
+
324
+            OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
325
+        }
326
+        \OC::$server->getEventLogger()->end('setup_fs');
327
+        return true;
328
+    }
329
+
330
+    /**
331
+     * check if a password is required for each public link
332
+     *
333
+     * @return boolean
334
+     * @suppress PhanDeprecatedFunction
335
+     */
336
+    public static function isPublicLinkPasswordRequired() {
337
+        $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
338
+        return $enforcePassword === 'yes';
339
+    }
340
+
341
+    /**
342
+     * check if sharing is disabled for the current user
343
+     * @param IConfig $config
344
+     * @param IGroupManager $groupManager
345
+     * @param IUser|null $user
346
+     * @return bool
347
+     */
348
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
349
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
350
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
351
+            $excludedGroups = json_decode($groupsList);
352
+            if (is_null($excludedGroups)) {
353
+                $excludedGroups = explode(',', $groupsList);
354
+                $newValue = json_encode($excludedGroups);
355
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
356
+            }
357
+            $usersGroups = $groupManager->getUserGroupIds($user);
358
+            if (!empty($usersGroups)) {
359
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
360
+                // if the user is only in groups which are disabled for sharing then
361
+                // sharing is also disabled for the user
362
+                if (empty($remainingGroups)) {
363
+                    return true;
364
+                }
365
+            }
366
+        }
367
+        return false;
368
+    }
369
+
370
+    /**
371
+     * check if share API enforces a default expire date
372
+     *
373
+     * @return boolean
374
+     * @suppress PhanDeprecatedFunction
375
+     */
376
+    public static function isDefaultExpireDateEnforced() {
377
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
378
+        $enforceDefaultExpireDate = false;
379
+        if ($isDefaultExpireDateEnabled === 'yes') {
380
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
381
+            $enforceDefaultExpireDate = $value === 'yes';
382
+        }
383
+
384
+        return $enforceDefaultExpireDate;
385
+    }
386
+
387
+    /**
388
+     * Get the quota of a user
389
+     *
390
+     * @param IUser|null $user
391
+     * @return float Quota bytes
392
+     */
393
+    public static function getUserQuota(?IUser $user) {
394
+        if (is_null($user)) {
395
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
396
+        }
397
+        $userQuota = $user->getQuota();
398
+        if ($userQuota === 'none') {
399
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
400
+        }
401
+        return OC_Helper::computerFileSize($userQuota);
402
+    }
403
+
404
+    /**
405
+     * copies the skeleton to the users /files
406
+     *
407
+     * @param string $userId
408
+     * @param \OCP\Files\Folder $userDirectory
409
+     * @throws \OCP\Files\NotFoundException
410
+     * @throws \OCP\Files\NotPermittedException
411
+     * @suppress PhanDeprecatedFunction
412
+     */
413
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
414
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
415
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
416
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
417
+
418
+        if (!file_exists($skeletonDirectory)) {
419
+            $dialectStart = strpos($userLang, '_');
420
+            if ($dialectStart !== false) {
421
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
422
+            }
423
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
424
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
425
+            }
426
+            if (!file_exists($skeletonDirectory)) {
427
+                $skeletonDirectory = '';
428
+            }
429
+        }
430
+
431
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
432
+
433
+        if ($instanceId === null) {
434
+            throw new \RuntimeException('no instance id!');
435
+        }
436
+        $appdata = 'appdata_' . $instanceId;
437
+        if ($userId === $appdata) {
438
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
439
+        }
440
+
441
+        if (!empty($skeletonDirectory)) {
442
+            \OCP\Util::writeLog(
443
+                'files_skeleton',
444
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
445
+                ILogger::DEBUG
446
+            );
447
+            self::copyr($skeletonDirectory, $userDirectory);
448
+            // update the file cache
449
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
450
+        }
451
+    }
452
+
453
+    /**
454
+     * copies a directory recursively by using streams
455
+     *
456
+     * @param string $source
457
+     * @param \OCP\Files\Folder $target
458
+     * @return void
459
+     */
460
+    public static function copyr($source, \OCP\Files\Folder $target) {
461
+        $logger = \OC::$server->getLogger();
462
+
463
+        // Verify if folder exists
464
+        $dir = opendir($source);
465
+        if ($dir === false) {
466
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
467
+            return;
468
+        }
469
+
470
+        // Copy the files
471
+        while (false !== ($file = readdir($dir))) {
472
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
473
+                if (is_dir($source . '/' . $file)) {
474
+                    $child = $target->newFolder($file);
475
+                    self::copyr($source . '/' . $file, $child);
476
+                } else {
477
+                    $child = $target->newFile($file);
478
+                    $sourceStream = fopen($source . '/' . $file, 'r');
479
+                    if ($sourceStream === false) {
480
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
481
+                        closedir($dir);
482
+                        return;
483
+                    }
484
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
485
+                }
486
+            }
487
+        }
488
+        closedir($dir);
489
+    }
490
+
491
+    /**
492
+     * @return void
493
+     * @suppress PhanUndeclaredMethod
494
+     */
495
+    public static function tearDownFS() {
496
+        \OC\Files\Filesystem::tearDown();
497
+        \OC::$server->getRootFolder()->clearCache();
498
+        self::$fsSetup = false;
499
+        self::$rootMounted = false;
500
+    }
501
+
502
+    /**
503
+     * get the current installed version of ownCloud
504
+     *
505
+     * @return array
506
+     */
507
+    public static function getVersion() {
508
+        OC_Util::loadVersion();
509
+        return self::$versionCache['OC_Version'];
510
+    }
511
+
512
+    /**
513
+     * get the current installed version string of ownCloud
514
+     *
515
+     * @return string
516
+     */
517
+    public static function getVersionString() {
518
+        OC_Util::loadVersion();
519
+        return self::$versionCache['OC_VersionString'];
520
+    }
521
+
522
+    /**
523
+     * @deprecated the value is of no use anymore
524
+     * @return string
525
+     */
526
+    public static function getEditionString() {
527
+        return '';
528
+    }
529
+
530
+    /**
531
+     * @description get the update channel of the current installed of ownCloud.
532
+     * @return string
533
+     */
534
+    public static function getChannel() {
535
+        OC_Util::loadVersion();
536
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
537
+    }
538
+
539
+    /**
540
+     * @description get the build number of the current installed of ownCloud.
541
+     * @return string
542
+     */
543
+    public static function getBuild() {
544
+        OC_Util::loadVersion();
545
+        return self::$versionCache['OC_Build'];
546
+    }
547
+
548
+    /**
549
+     * @description load the version.php into the session as cache
550
+     * @suppress PhanUndeclaredVariable
551
+     */
552
+    private static function loadVersion() {
553
+        if (self::$versionCache !== null) {
554
+            return;
555
+        }
556
+
557
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
558
+        require OC::$SERVERROOT . '/version.php';
559
+        /** @var int $timestamp */
560
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
561
+        /** @var string $OC_Version */
562
+        self::$versionCache['OC_Version'] = $OC_Version;
563
+        /** @var string $OC_VersionString */
564
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
565
+        /** @var string $OC_Build */
566
+        self::$versionCache['OC_Build'] = $OC_Build;
567
+
568
+        /** @var string $OC_Channel */
569
+        self::$versionCache['OC_Channel'] = $OC_Channel;
570
+    }
571
+
572
+    /**
573
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
574
+     *
575
+     * @param string $application application to get the files from
576
+     * @param string $directory directory within this application (css, js, vendor, etc)
577
+     * @param string $file the file inside of the above folder
578
+     * @return string the path
579
+     */
580
+    private static function generatePath($application, $directory, $file) {
581
+        if (is_null($file)) {
582
+            $file = $application;
583
+            $application = "";
584
+        }
585
+        if (!empty($application)) {
586
+            return "$application/$directory/$file";
587
+        } else {
588
+            return "$directory/$file";
589
+        }
590
+    }
591
+
592
+    /**
593
+     * add a javascript file
594
+     *
595
+     * @param string $application application id
596
+     * @param string|null $file filename
597
+     * @param bool $prepend prepend the Script to the beginning of the list
598
+     * @return void
599
+     */
600
+    public static function addScript($application, $file = null, $prepend = false) {
601
+        $path = OC_Util::generatePath($application, 'js', $file);
602
+
603
+        // core js files need separate handling
604
+        if ($application !== 'core' && $file !== null) {
605
+            self::addTranslations($application);
606
+        }
607
+        self::addExternalResource($application, $prepend, $path, "script");
608
+    }
609
+
610
+    /**
611
+     * add a javascript file from the vendor sub folder
612
+     *
613
+     * @param string $application application id
614
+     * @param string|null $file filename
615
+     * @param bool $prepend prepend the Script to the beginning of the list
616
+     * @return void
617
+     */
618
+    public static function addVendorScript($application, $file = null, $prepend = false) {
619
+        $path = OC_Util::generatePath($application, 'vendor', $file);
620
+        self::addExternalResource($application, $prepend, $path, "script");
621
+    }
622
+
623
+    /**
624
+     * add a translation JS file
625
+     *
626
+     * @param string $application application id
627
+     * @param string|null $languageCode language code, defaults to the current language
628
+     * @param bool|null $prepend prepend the Script to the beginning of the list
629
+     */
630
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
631
+        if (is_null($languageCode)) {
632
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
633
+        }
634
+        if (!empty($application)) {
635
+            $path = "$application/l10n/$languageCode";
636
+        } else {
637
+            $path = "l10n/$languageCode";
638
+        }
639
+        self::addExternalResource($application, $prepend, $path, "script");
640
+    }
641
+
642
+    /**
643
+     * add a css file
644
+     *
645
+     * @param string $application application id
646
+     * @param string|null $file filename
647
+     * @param bool $prepend prepend the Style to the beginning of the list
648
+     * @return void
649
+     */
650
+    public static function addStyle($application, $file = null, $prepend = false) {
651
+        $path = OC_Util::generatePath($application, 'css', $file);
652
+        self::addExternalResource($application, $prepend, $path, "style");
653
+    }
654
+
655
+    /**
656
+     * add a css file from the vendor sub folder
657
+     *
658
+     * @param string $application application id
659
+     * @param string|null $file filename
660
+     * @param bool $prepend prepend the Style to the beginning of the list
661
+     * @return void
662
+     */
663
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
664
+        $path = OC_Util::generatePath($application, 'vendor', $file);
665
+        self::addExternalResource($application, $prepend, $path, "style");
666
+    }
667
+
668
+    /**
669
+     * add an external resource css/js file
670
+     *
671
+     * @param string $application application id
672
+     * @param bool $prepend prepend the file to the beginning of the list
673
+     * @param string $path
674
+     * @param string $type (script or style)
675
+     * @return void
676
+     */
677
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
678
+        if ($type === "style") {
679
+            if (!in_array($path, self::$styles)) {
680
+                if ($prepend === true) {
681
+                    array_unshift(self::$styles, $path);
682
+                } else {
683
+                    self::$styles[] = $path;
684
+                }
685
+            }
686
+        } elseif ($type === "script") {
687
+            if (!in_array($path, self::$scripts)) {
688
+                if ($prepend === true) {
689
+                    array_unshift(self::$scripts, $path);
690
+                } else {
691
+                    self::$scripts [] = $path;
692
+                }
693
+            }
694
+        }
695
+    }
696
+
697
+    /**
698
+     * Add a custom element to the header
699
+     * If $text is null then the element will be written as empty element.
700
+     * So use "" to get a closing tag.
701
+     * @param string $tag tag name of the element
702
+     * @param array $attributes array of attributes for the element
703
+     * @param string $text the text content for the element
704
+     * @param bool $prepend prepend the header to the beginning of the list
705
+     */
706
+    public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
707
+        $header = [
708
+            'tag' => $tag,
709
+            'attributes' => $attributes,
710
+            'text' => $text
711
+        ];
712
+        if ($prepend === true) {
713
+            array_unshift(self::$headers, $header);
714
+        } else {
715
+            self::$headers[] = $header;
716
+        }
717
+    }
718
+
719
+    /**
720
+     * check if the current server configuration is suitable for ownCloud
721
+     *
722
+     * @param \OC\SystemConfig $config
723
+     * @return array arrays with error messages and hints
724
+     */
725
+    public static function checkServer(\OC\SystemConfig $config) {
726
+        $l = \OC::$server->getL10N('lib');
727
+        $errors = [];
728
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
729
+
730
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
731
+            // this check needs to be done every time
732
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
733
+        }
734
+
735
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
736
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
737
+            return $errors;
738
+        }
739
+
740
+        $webServerRestart = false;
741
+        $setup = new \OC\Setup(
742
+            $config,
743
+            \OC::$server->get(IniGetWrapper::class),
744
+            \OC::$server->getL10N('lib'),
745
+            \OC::$server->query(\OCP\Defaults::class),
746
+            \OC::$server->getLogger(),
747
+            \OC::$server->getSecureRandom(),
748
+            \OC::$server->query(\OC\Installer::class)
749
+        );
750
+
751
+        $urlGenerator = \OC::$server->getURLGenerator();
752
+
753
+        $availableDatabases = $setup->getSupportedDatabases();
754
+        if (empty($availableDatabases)) {
755
+            $errors[] = [
756
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
757
+                'hint' => '' //TODO: sane hint
758
+            ];
759
+            $webServerRestart = true;
760
+        }
761
+
762
+        // Check if config folder is writable.
763
+        if (!OC_Helper::isReadOnlyConfigEnabled()) {
764
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
765
+                $errors[] = [
766
+                    'error' => $l->t('Cannot write into "config" directory'),
767
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
768
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
769
+                        . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
770
+                        [ $urlGenerator->linkToDocs('admin-config') ])
771
+                ];
772
+            }
773
+        }
774
+
775
+        // Check if there is a writable install folder.
776
+        if ($config->getValue('appstoreenabled', true)) {
777
+            if (OC_App::getInstallPath() === null
778
+                || !is_writable(OC_App::getInstallPath())
779
+                || !is_readable(OC_App::getInstallPath())
780
+            ) {
781
+                $errors[] = [
782
+                    'error' => $l->t('Cannot write into "apps" directory'),
783
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
784
+                        . ' or disabling the appstore in the config file.')
785
+                ];
786
+            }
787
+        }
788
+        // Create root dir.
789
+        if ($config->getValue('installed', false)) {
790
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
791
+                $success = @mkdir($CONFIG_DATADIRECTORY);
792
+                if ($success) {
793
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
794
+                } else {
795
+                    $errors[] = [
796
+                        'error' => $l->t('Cannot create "data" directory'),
797
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
798
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
799
+                    ];
800
+                }
801
+            } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
802
+                // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
803
+                $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
804
+                $handle = fopen($testFile, 'w');
805
+                if (!$handle || fwrite($handle, 'Test write operation') === false) {
806
+                    $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
807
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')]);
808
+                    $errors[] = [
809
+                        'error' => 'Your data directory is not writable',
810
+                        'hint' => $permissionsHint
811
+                    ];
812
+                } else {
813
+                    fclose($handle);
814
+                    unlink($testFile);
815
+                }
816
+            } else {
817
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
818
+            }
819
+        }
820
+
821
+        if (!OC_Util::isSetLocaleWorking()) {
822
+            $errors[] = [
823
+                'error' => $l->t('Setting locale to %s failed',
824
+                    ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
825
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
826
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
827
+            ];
828
+        }
829
+
830
+        // Contains the dependencies that should be checked against
831
+        // classes = class_exists
832
+        // functions = function_exists
833
+        // defined = defined
834
+        // ini = ini_get
835
+        // If the dependency is not found the missing module name is shown to the EndUser
836
+        // When adding new checks always verify that they pass on Travis as well
837
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
838
+        $dependencies = [
839
+            'classes' => [
840
+                'ZipArchive' => 'zip',
841
+                'DOMDocument' => 'dom',
842
+                'XMLWriter' => 'XMLWriter',
843
+                'XMLReader' => 'XMLReader',
844
+            ],
845
+            'functions' => [
846
+                'xml_parser_create' => 'libxml',
847
+                'mb_strcut' => 'mbstring',
848
+                'ctype_digit' => 'ctype',
849
+                'json_encode' => 'JSON',
850
+                'gd_info' => 'GD',
851
+                'gzencode' => 'zlib',
852
+                'iconv' => 'iconv',
853
+                'simplexml_load_string' => 'SimpleXML',
854
+                'hash' => 'HASH Message Digest Framework',
855
+                'curl_init' => 'cURL',
856
+                'openssl_verify' => 'OpenSSL',
857
+            ],
858
+            'defined' => [
859
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
860
+            ],
861
+            'ini' => [
862
+                'default_charset' => 'UTF-8',
863
+            ],
864
+        ];
865
+        $missingDependencies = [];
866
+        $invalidIniSettings = [];
867
+
868
+        $iniWrapper = \OC::$server->get(IniGetWrapper::class);
869
+        foreach ($dependencies['classes'] as $class => $module) {
870
+            if (!class_exists($class)) {
871
+                $missingDependencies[] = $module;
872
+            }
873
+        }
874
+        foreach ($dependencies['functions'] as $function => $module) {
875
+            if (!function_exists($function)) {
876
+                $missingDependencies[] = $module;
877
+            }
878
+        }
879
+        foreach ($dependencies['defined'] as $defined => $module) {
880
+            if (!defined($defined)) {
881
+                $missingDependencies[] = $module;
882
+            }
883
+        }
884
+        foreach ($dependencies['ini'] as $setting => $expected) {
885
+            if (is_bool($expected)) {
886
+                if ($iniWrapper->getBool($setting) !== $expected) {
887
+                    $invalidIniSettings[] = [$setting, $expected];
888
+                }
889
+            }
890
+            if (is_int($expected)) {
891
+                if ($iniWrapper->getNumeric($setting) !== $expected) {
892
+                    $invalidIniSettings[] = [$setting, $expected];
893
+                }
894
+            }
895
+            if (is_string($expected)) {
896
+                if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
897
+                    $invalidIniSettings[] = [$setting, $expected];
898
+                }
899
+            }
900
+        }
901
+
902
+        foreach ($missingDependencies as $missingDependency) {
903
+            $errors[] = [
904
+                'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
905
+                'hint' => $l->t('Please ask your server administrator to install the module.'),
906
+            ];
907
+            $webServerRestart = true;
908
+        }
909
+        foreach ($invalidIniSettings as $setting) {
910
+            if (is_bool($setting[1])) {
911
+                $setting[1] = $setting[1] ? 'on' : 'off';
912
+            }
913
+            $errors[] = [
914
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
915
+                'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
916
+            ];
917
+            $webServerRestart = true;
918
+        }
919
+
920
+        /**
921
+         * The mbstring.func_overload check can only be performed if the mbstring
922
+         * module is installed as it will return null if the checking setting is
923
+         * not available and thus a check on the boolean value fails.
924
+         *
925
+         * TODO: Should probably be implemented in the above generic dependency
926
+         *       check somehow in the long-term.
927
+         */
928
+        if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
929
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
930
+            $errors[] = [
931
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
932
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
933
+            ];
934
+        }
935
+
936
+        if (function_exists('xml_parser_create') &&
937
+            LIBXML_LOADED_VERSION < 20700) {
938
+            $version = LIBXML_LOADED_VERSION;
939
+            $major = floor($version / 10000);
940
+            $version -= ($major * 10000);
941
+            $minor = floor($version / 100);
942
+            $version -= ($minor * 100);
943
+            $patch = $version;
944
+            $errors[] = [
945
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
946
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
947
+            ];
948
+        }
949
+
950
+        if (!self::isAnnotationsWorking()) {
951
+            $errors[] = [
952
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
953
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
954
+            ];
955
+        }
956
+
957
+        if (!\OC::$CLI && $webServerRestart) {
958
+            $errors[] = [
959
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
960
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
961
+            ];
962
+        }
963
+
964
+        $errors = array_merge($errors, self::checkDatabaseVersion());
965
+
966
+        // Cache the result of this function
967
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
968
+
969
+        return $errors;
970
+    }
971
+
972
+    /**
973
+     * Check the database version
974
+     *
975
+     * @return array errors array
976
+     */
977
+    public static function checkDatabaseVersion() {
978
+        $l = \OC::$server->getL10N('lib');
979
+        $errors = [];
980
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
981
+        if ($dbType === 'pgsql') {
982
+            // check PostgreSQL version
983
+            try {
984
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
985
+                $data = $result->fetchRow();
986
+                $result->closeCursor();
987
+                if (isset($data['server_version'])) {
988
+                    $version = $data['server_version'];
989
+                    if (version_compare($version, '9.0.0', '<')) {
990
+                        $errors[] = [
991
+                            'error' => $l->t('PostgreSQL >= 9 required'),
992
+                            'hint' => $l->t('Please upgrade your database version')
993
+                        ];
994
+                    }
995
+                }
996
+            } catch (\Doctrine\DBAL\Exception $e) {
997
+                $logger = \OC::$server->getLogger();
998
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
999
+                $logger->logException($e);
1000
+            }
1001
+        }
1002
+        return $errors;
1003
+    }
1004
+
1005
+    /**
1006
+     * Check for correct file permissions of data directory
1007
+     *
1008
+     * @param string $dataDirectory
1009
+     * @return array arrays with error messages and hints
1010
+     */
1011
+    public static function checkDataDirectoryPermissions($dataDirectory) {
1012
+        if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1013
+            return  [];
1014
+        }
1015
+
1016
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1017
+        if (substr($perms, -1) !== '0') {
1018
+            chmod($dataDirectory, 0770);
1019
+            clearstatcache();
1020
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1021
+            if ($perms[2] !== '0') {
1022
+                $l = \OC::$server->getL10N('lib');
1023
+                return [[
1024
+                    'error' => $l->t('Your data directory is readable by other users'),
1025
+                    'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1026
+                ]];
1027
+            }
1028
+        }
1029
+        return [];
1030
+    }
1031
+
1032
+    /**
1033
+     * Check that the data directory exists and is valid by
1034
+     * checking the existence of the ".ocdata" file.
1035
+     *
1036
+     * @param string $dataDirectory data directory path
1037
+     * @return array errors found
1038
+     */
1039
+    public static function checkDataDirectoryValidity($dataDirectory) {
1040
+        $l = \OC::$server->getL10N('lib');
1041
+        $errors = [];
1042
+        if ($dataDirectory[0] !== '/') {
1043
+            $errors[] = [
1044
+                'error' => $l->t('Your data directory must be an absolute path'),
1045
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1046
+            ];
1047
+        }
1048
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1049
+            $errors[] = [
1050
+                'error' => $l->t('Your data directory is invalid'),
1051
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1052
+                    ' in the root of the data directory.')
1053
+            ];
1054
+        }
1055
+        return $errors;
1056
+    }
1057
+
1058
+    /**
1059
+     * Check if the user is logged in, redirects to home if not. With
1060
+     * redirect URL parameter to the request URI.
1061
+     *
1062
+     * @return void
1063
+     */
1064
+    public static function checkLoggedIn() {
1065
+        // Check if we are a user
1066
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1067
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1068
+                        'core.login.showLoginForm',
1069
+                        [
1070
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1071
+                        ]
1072
+                    )
1073
+            );
1074
+            exit();
1075
+        }
1076
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1077
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1078
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1079
+            exit();
1080
+        }
1081
+    }
1082
+
1083
+    /**
1084
+     * Check if the user is a admin, redirects to home if not
1085
+     *
1086
+     * @return void
1087
+     */
1088
+    public static function checkAdminUser() {
1089
+        OC_Util::checkLoggedIn();
1090
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1091
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1092
+            exit();
1093
+        }
1094
+    }
1095
+
1096
+    /**
1097
+     * Returns the URL of the default page
1098
+     * based on the system configuration and
1099
+     * the apps visible for the current user
1100
+     *
1101
+     * @return string URL
1102
+     * @suppress PhanDeprecatedFunction
1103
+     */
1104
+    public static function getDefaultPageUrl() {
1105
+        /** @var IConfig $config */
1106
+        $config = \OC::$server->get(IConfig::class);
1107
+        $urlGenerator = \OC::$server->getURLGenerator();
1108
+        // Deny the redirect if the URL contains a @
1109
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1110
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1111
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1112
+        } else {
1113
+            $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1114
+            if ($defaultPage) {
1115
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1116
+            } else {
1117
+                $appId = 'files';
1118
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'dashboard,files'));
1119
+
1120
+                /** @var IUserSession $userSession */
1121
+                $userSession = \OC::$server->get(IUserSession::class);
1122
+                $user = $userSession->getUser();
1123
+                if ($user) {
1124
+                    $userDefaultApps = explode(',', $config->getUserValue($user->getUID(), 'core', 'defaultapp'));
1125
+                    $defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
1126
+                }
1127
+
1128
+                // find the first app that is enabled for the current user
1129
+                foreach ($defaultApps as $defaultApp) {
1130
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1131
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1132
+                        $appId = $defaultApp;
1133
+                        break;
1134
+                    }
1135
+                }
1136
+
1137
+                if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1138
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1139
+                } else {
1140
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1141
+                }
1142
+            }
1143
+        }
1144
+        return $location;
1145
+    }
1146
+
1147
+    /**
1148
+     * Redirect to the user default page
1149
+     *
1150
+     * @return void
1151
+     */
1152
+    public static function redirectToDefaultPage() {
1153
+        $location = self::getDefaultPageUrl();
1154
+        header('Location: ' . $location);
1155
+        exit();
1156
+    }
1157
+
1158
+    /**
1159
+     * get an id unique for this instance
1160
+     *
1161
+     * @return string
1162
+     */
1163
+    public static function getInstanceId() {
1164
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1165
+        if (is_null($id)) {
1166
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1167
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1168
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1169
+        }
1170
+        return $id;
1171
+    }
1172
+
1173
+    /**
1174
+     * Public function to sanitize HTML
1175
+     *
1176
+     * This function is used to sanitize HTML and should be applied on any
1177
+     * string or array of strings before displaying it on a web page.
1178
+     *
1179
+     * @param string|array $value
1180
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1181
+     */
1182
+    public static function sanitizeHTML($value) {
1183
+        if (is_array($value)) {
1184
+            $value = array_map(function ($value) {
1185
+                return self::sanitizeHTML($value);
1186
+            }, $value);
1187
+        } else {
1188
+            // Specify encoding for PHP<5.4
1189
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1190
+        }
1191
+        return $value;
1192
+    }
1193
+
1194
+    /**
1195
+     * Public function to encode url parameters
1196
+     *
1197
+     * This function is used to encode path to file before output.
1198
+     * Encoding is done according to RFC 3986 with one exception:
1199
+     * Character '/' is preserved as is.
1200
+     *
1201
+     * @param string $component part of URI to encode
1202
+     * @return string
1203
+     */
1204
+    public static function encodePath($component) {
1205
+        $encoded = rawurlencode($component);
1206
+        $encoded = str_replace('%2F', '/', $encoded);
1207
+        return $encoded;
1208
+    }
1209
+
1210
+
1211
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1212
+        // php dev server does not support htaccess
1213
+        if (php_sapi_name() === 'cli-server') {
1214
+            return false;
1215
+        }
1216
+
1217
+        // testdata
1218
+        $fileName = '/htaccesstest.txt';
1219
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1220
+
1221
+        // creating a test file
1222
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1223
+
1224
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1225
+            return false;
1226
+        }
1227
+
1228
+        $fp = @fopen($testFile, 'w');
1229
+        if (!$fp) {
1230
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1231
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1232
+        }
1233
+        fwrite($fp, $testContent);
1234
+        fclose($fp);
1235
+
1236
+        return $testContent;
1237
+    }
1238
+
1239
+    /**
1240
+     * Check if the .htaccess file is working
1241
+     * @param \OCP\IConfig $config
1242
+     * @return bool
1243
+     * @throws Exception
1244
+     * @throws \OC\HintException If the test file can't get written.
1245
+     */
1246
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1247
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1248
+            return true;
1249
+        }
1250
+
1251
+        $testContent = $this->createHtaccessTestFile($config);
1252
+        if ($testContent === false) {
1253
+            return false;
1254
+        }
1255
+
1256
+        $fileName = '/htaccesstest.txt';
1257
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1258
+
1259
+        // accessing the file via http
1260
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1261
+        try {
1262
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1263
+        } catch (\Exception $e) {
1264
+            $content = false;
1265
+        }
1266
+
1267
+        if (strpos($url, 'https:') === 0) {
1268
+            $url = 'http:' . substr($url, 6);
1269
+        } else {
1270
+            $url = 'https:' . substr($url, 5);
1271
+        }
1272
+
1273
+        try {
1274
+            $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1275
+        } catch (\Exception $e) {
1276
+            $fallbackContent = false;
1277
+        }
1278
+
1279
+        // cleanup
1280
+        @unlink($testFile);
1281
+
1282
+        /*
1283 1283
 		 * If the content is not equal to test content our .htaccess
1284 1284
 		 * is working as required
1285 1285
 		 */
1286
-		return $content !== $testContent && $fallbackContent !== $testContent;
1287
-	}
1288
-
1289
-	/**
1290
-	 * Check if the setlocal call does not work. This can happen if the right
1291
-	 * local packages are not available on the server.
1292
-	 *
1293
-	 * @return bool
1294
-	 */
1295
-	public static function isSetLocaleWorking() {
1296
-		if ('' === basename('§')) {
1297
-			// Borrowed from \Patchwork\Utf8\Bootup::initLocale
1298
-			setlocale(LC_ALL, 'C.UTF-8', 'C');
1299
-			setlocale(LC_CTYPE, 'en_US.UTF-8', 'fr_FR.UTF-8', 'es_ES.UTF-8', 'de_DE.UTF-8', 'ru_RU.UTF-8', 'pt_BR.UTF-8', 'it_IT.UTF-8', 'ja_JP.UTF-8', 'zh_CN.UTF-8', '0');
1300
-		}
1301
-
1302
-		// Check again
1303
-		if ('' === basename('§')) {
1304
-			return false;
1305
-		}
1306
-		return true;
1307
-	}
1308
-
1309
-	/**
1310
-	 * Check if it's possible to get the inline annotations
1311
-	 *
1312
-	 * @return bool
1313
-	 */
1314
-	public static function isAnnotationsWorking() {
1315
-		$reflection = new \ReflectionMethod(__METHOD__);
1316
-		$docs = $reflection->getDocComment();
1317
-
1318
-		return (is_string($docs) && strlen($docs) > 50);
1319
-	}
1320
-
1321
-	/**
1322
-	 * Check if the PHP module fileinfo is loaded.
1323
-	 *
1324
-	 * @return bool
1325
-	 */
1326
-	public static function fileInfoLoaded() {
1327
-		return function_exists('finfo_open');
1328
-	}
1329
-
1330
-	/**
1331
-	 * clear all levels of output buffering
1332
-	 *
1333
-	 * @return void
1334
-	 */
1335
-	public static function obEnd() {
1336
-		while (ob_get_level()) {
1337
-			ob_end_clean();
1338
-		}
1339
-	}
1340
-
1341
-	/**
1342
-	 * Checks whether the server is running on Mac OS X
1343
-	 *
1344
-	 * @return bool true if running on Mac OS X, false otherwise
1345
-	 */
1346
-	public static function runningOnMac() {
1347
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1348
-	}
1349
-
1350
-	/**
1351
-	 * Handles the case that there may not be a theme, then check if a "default"
1352
-	 * theme exists and take that one
1353
-	 *
1354
-	 * @return string the theme
1355
-	 */
1356
-	public static function getTheme() {
1357
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1358
-
1359
-		if ($theme === '') {
1360
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1361
-				$theme = 'default';
1362
-			}
1363
-		}
1364
-
1365
-		return $theme;
1366
-	}
1367
-
1368
-	/**
1369
-	 * Normalize a unicode string
1370
-	 *
1371
-	 * @param string $value a not normalized string
1372
-	 * @return bool|string
1373
-	 */
1374
-	public static function normalizeUnicode($value) {
1375
-		if (Normalizer::isNormalized($value)) {
1376
-			return $value;
1377
-		}
1378
-
1379
-		$normalizedValue = Normalizer::normalize($value);
1380
-		if ($normalizedValue === null || $normalizedValue === false) {
1381
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1382
-			return $value;
1383
-		}
1384
-
1385
-		return $normalizedValue;
1386
-	}
1387
-
1388
-	/**
1389
-	 * A human readable string is generated based on version and build number
1390
-	 *
1391
-	 * @return string
1392
-	 */
1393
-	public static function getHumanVersion() {
1394
-		$version = OC_Util::getVersionString();
1395
-		$build = OC_Util::getBuild();
1396
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1397
-			$version .= ' Build:' . $build;
1398
-		}
1399
-		return $version;
1400
-	}
1401
-
1402
-	/**
1403
-	 * Returns whether the given file name is valid
1404
-	 *
1405
-	 * @param string $file file name to check
1406
-	 * @return bool true if the file name is valid, false otherwise
1407
-	 * @deprecated use \OC\Files\View::verifyPath()
1408
-	 */
1409
-	public static function isValidFileName($file) {
1410
-		$trimmed = trim($file);
1411
-		if ($trimmed === '') {
1412
-			return false;
1413
-		}
1414
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1415
-			return false;
1416
-		}
1417
-
1418
-		// detect part files
1419
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1420
-			return false;
1421
-		}
1422
-
1423
-		foreach (str_split($trimmed) as $char) {
1424
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1425
-				return false;
1426
-			}
1427
-		}
1428
-		return true;
1429
-	}
1430
-
1431
-	/**
1432
-	 * Check whether the instance needs to perform an upgrade,
1433
-	 * either when the core version is higher or any app requires
1434
-	 * an upgrade.
1435
-	 *
1436
-	 * @param \OC\SystemConfig $config
1437
-	 * @return bool whether the core or any app needs an upgrade
1438
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1439
-	 */
1440
-	public static function needUpgrade(\OC\SystemConfig $config) {
1441
-		if ($config->getValue('installed', false)) {
1442
-			$installedVersion = $config->getValue('version', '0.0.0');
1443
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1444
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1445
-			if ($versionDiff > 0) {
1446
-				return true;
1447
-			} elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1448
-				// downgrade with debug
1449
-				$installedMajor = explode('.', $installedVersion);
1450
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1451
-				$currentMajor = explode('.', $currentVersion);
1452
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1453
-				if ($installedMajor === $currentMajor) {
1454
-					// Same major, allow downgrade for developers
1455
-					return true;
1456
-				} else {
1457
-					// downgrade attempt, throw exception
1458
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1459
-				}
1460
-			} elseif ($versionDiff < 0) {
1461
-				// downgrade attempt, throw exception
1462
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1463
-			}
1464
-
1465
-			// also check for upgrades for apps (independently from the user)
1466
-			$apps = \OC_App::getEnabledApps(false, true);
1467
-			$shouldUpgrade = false;
1468
-			foreach ($apps as $app) {
1469
-				if (\OC_App::shouldUpgrade($app)) {
1470
-					$shouldUpgrade = true;
1471
-					break;
1472
-				}
1473
-			}
1474
-			return $shouldUpgrade;
1475
-		} else {
1476
-			return false;
1477
-		}
1478
-	}
1479
-
1480
-	/**
1481
-	 * is this Internet explorer ?
1482
-	 *
1483
-	 * @return boolean
1484
-	 */
1485
-	public static function isIe() {
1486
-		if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1487
-			return false;
1488
-		}
1489
-
1490
-		return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1491
-	}
1286
+        return $content !== $testContent && $fallbackContent !== $testContent;
1287
+    }
1288
+
1289
+    /**
1290
+     * Check if the setlocal call does not work. This can happen if the right
1291
+     * local packages are not available on the server.
1292
+     *
1293
+     * @return bool
1294
+     */
1295
+    public static function isSetLocaleWorking() {
1296
+        if ('' === basename('§')) {
1297
+            // Borrowed from \Patchwork\Utf8\Bootup::initLocale
1298
+            setlocale(LC_ALL, 'C.UTF-8', 'C');
1299
+            setlocale(LC_CTYPE, 'en_US.UTF-8', 'fr_FR.UTF-8', 'es_ES.UTF-8', 'de_DE.UTF-8', 'ru_RU.UTF-8', 'pt_BR.UTF-8', 'it_IT.UTF-8', 'ja_JP.UTF-8', 'zh_CN.UTF-8', '0');
1300
+        }
1301
+
1302
+        // Check again
1303
+        if ('' === basename('§')) {
1304
+            return false;
1305
+        }
1306
+        return true;
1307
+    }
1308
+
1309
+    /**
1310
+     * Check if it's possible to get the inline annotations
1311
+     *
1312
+     * @return bool
1313
+     */
1314
+    public static function isAnnotationsWorking() {
1315
+        $reflection = new \ReflectionMethod(__METHOD__);
1316
+        $docs = $reflection->getDocComment();
1317
+
1318
+        return (is_string($docs) && strlen($docs) > 50);
1319
+    }
1320
+
1321
+    /**
1322
+     * Check if the PHP module fileinfo is loaded.
1323
+     *
1324
+     * @return bool
1325
+     */
1326
+    public static function fileInfoLoaded() {
1327
+        return function_exists('finfo_open');
1328
+    }
1329
+
1330
+    /**
1331
+     * clear all levels of output buffering
1332
+     *
1333
+     * @return void
1334
+     */
1335
+    public static function obEnd() {
1336
+        while (ob_get_level()) {
1337
+            ob_end_clean();
1338
+        }
1339
+    }
1340
+
1341
+    /**
1342
+     * Checks whether the server is running on Mac OS X
1343
+     *
1344
+     * @return bool true if running on Mac OS X, false otherwise
1345
+     */
1346
+    public static function runningOnMac() {
1347
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1348
+    }
1349
+
1350
+    /**
1351
+     * Handles the case that there may not be a theme, then check if a "default"
1352
+     * theme exists and take that one
1353
+     *
1354
+     * @return string the theme
1355
+     */
1356
+    public static function getTheme() {
1357
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1358
+
1359
+        if ($theme === '') {
1360
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1361
+                $theme = 'default';
1362
+            }
1363
+        }
1364
+
1365
+        return $theme;
1366
+    }
1367
+
1368
+    /**
1369
+     * Normalize a unicode string
1370
+     *
1371
+     * @param string $value a not normalized string
1372
+     * @return bool|string
1373
+     */
1374
+    public static function normalizeUnicode($value) {
1375
+        if (Normalizer::isNormalized($value)) {
1376
+            return $value;
1377
+        }
1378
+
1379
+        $normalizedValue = Normalizer::normalize($value);
1380
+        if ($normalizedValue === null || $normalizedValue === false) {
1381
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1382
+            return $value;
1383
+        }
1384
+
1385
+        return $normalizedValue;
1386
+    }
1387
+
1388
+    /**
1389
+     * A human readable string is generated based on version and build number
1390
+     *
1391
+     * @return string
1392
+     */
1393
+    public static function getHumanVersion() {
1394
+        $version = OC_Util::getVersionString();
1395
+        $build = OC_Util::getBuild();
1396
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1397
+            $version .= ' Build:' . $build;
1398
+        }
1399
+        return $version;
1400
+    }
1401
+
1402
+    /**
1403
+     * Returns whether the given file name is valid
1404
+     *
1405
+     * @param string $file file name to check
1406
+     * @return bool true if the file name is valid, false otherwise
1407
+     * @deprecated use \OC\Files\View::verifyPath()
1408
+     */
1409
+    public static function isValidFileName($file) {
1410
+        $trimmed = trim($file);
1411
+        if ($trimmed === '') {
1412
+            return false;
1413
+        }
1414
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1415
+            return false;
1416
+        }
1417
+
1418
+        // detect part files
1419
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1420
+            return false;
1421
+        }
1422
+
1423
+        foreach (str_split($trimmed) as $char) {
1424
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1425
+                return false;
1426
+            }
1427
+        }
1428
+        return true;
1429
+    }
1430
+
1431
+    /**
1432
+     * Check whether the instance needs to perform an upgrade,
1433
+     * either when the core version is higher or any app requires
1434
+     * an upgrade.
1435
+     *
1436
+     * @param \OC\SystemConfig $config
1437
+     * @return bool whether the core or any app needs an upgrade
1438
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1439
+     */
1440
+    public static function needUpgrade(\OC\SystemConfig $config) {
1441
+        if ($config->getValue('installed', false)) {
1442
+            $installedVersion = $config->getValue('version', '0.0.0');
1443
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1444
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1445
+            if ($versionDiff > 0) {
1446
+                return true;
1447
+            } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1448
+                // downgrade with debug
1449
+                $installedMajor = explode('.', $installedVersion);
1450
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1451
+                $currentMajor = explode('.', $currentVersion);
1452
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1453
+                if ($installedMajor === $currentMajor) {
1454
+                    // Same major, allow downgrade for developers
1455
+                    return true;
1456
+                } else {
1457
+                    // downgrade attempt, throw exception
1458
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1459
+                }
1460
+            } elseif ($versionDiff < 0) {
1461
+                // downgrade attempt, throw exception
1462
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1463
+            }
1464
+
1465
+            // also check for upgrades for apps (independently from the user)
1466
+            $apps = \OC_App::getEnabledApps(false, true);
1467
+            $shouldUpgrade = false;
1468
+            foreach ($apps as $app) {
1469
+                if (\OC_App::shouldUpgrade($app)) {
1470
+                    $shouldUpgrade = true;
1471
+                    break;
1472
+                }
1473
+            }
1474
+            return $shouldUpgrade;
1475
+        } else {
1476
+            return false;
1477
+        }
1478
+    }
1479
+
1480
+    /**
1481
+     * is this Internet explorer ?
1482
+     *
1483
+     * @return boolean
1484
+     */
1485
+    public static function isIe() {
1486
+        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1487
+            return false;
1488
+        }
1489
+
1490
+        return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1491
+    }
1492 1492
 }
Please login to merge, or discard this patch.
lib/private/legacy/OC_App.php 2 patches
Indentation   +1121 added lines, -1121 removed lines patch added patch discarded remove patch
@@ -68,1125 +68,1125 @@
 block discarded – undo
68 68
  * upgrading and removing apps.
69 69
  */
70 70
 class OC_App {
71
-	private static $adminForms = [];
72
-	private static $personalForms = [];
73
-	private static $appTypes = [];
74
-	private static $loadedApps = [];
75
-	private static $altLogin = [];
76
-	private static $alreadyRegistered = [];
77
-	public const supportedApp = 300;
78
-	public const officialApp = 200;
79
-
80
-	/**
81
-	 * clean the appId
82
-	 *
83
-	 * @psalm-taint-escape file
84
-	 * @psalm-taint-escape include
85
-	 *
86
-	 * @param string $app AppId that needs to be cleaned
87
-	 * @return string
88
-	 */
89
-	public static function cleanAppId(string $app): string {
90
-		return str_replace(['\0', '/', '\\', '..'], '', $app);
91
-	}
92
-
93
-	/**
94
-	 * Check if an app is loaded
95
-	 *
96
-	 * @param string $app
97
-	 * @return bool
98
-	 */
99
-	public static function isAppLoaded(string $app): bool {
100
-		return isset(self::$loadedApps[$app]);
101
-	}
102
-
103
-	/**
104
-	 * loads all apps
105
-	 *
106
-	 * @param string[] $types
107
-	 * @return bool
108
-	 *
109
-	 * This function walks through the ownCloud directory and loads all apps
110
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
111
-	 * exists.
112
-	 *
113
-	 * if $types is set to non-empty array, only apps of those types will be loaded
114
-	 */
115
-	public static function loadApps(array $types = []): bool {
116
-		if ((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) {
117
-			return false;
118
-		}
119
-		// Load the enabled apps here
120
-		$apps = self::getEnabledApps();
121
-
122
-		// Add each apps' folder as allowed class path
123
-		foreach ($apps as $app) {
124
-			// If the app is already loaded then autoloading it makes no sense
125
-			if (!isset(self::$loadedApps[$app])) {
126
-				$path = self::getAppPath($app);
127
-				if ($path !== false) {
128
-					self::registerAutoloading($app, $path);
129
-				}
130
-			}
131
-		}
132
-
133
-		// prevent app.php from printing output
134
-		ob_start();
135
-		foreach ($apps as $app) {
136
-			if (!isset(self::$loadedApps[$app]) && ($types === [] || self::isType($app, $types))) {
137
-				self::loadApp($app);
138
-			}
139
-		}
140
-		ob_end_clean();
141
-
142
-		return true;
143
-	}
144
-
145
-	/**
146
-	 * load a single app
147
-	 *
148
-	 * @param string $app
149
-	 * @throws Exception
150
-	 */
151
-	public static function loadApp(string $app) {
152
-		self::$loadedApps[$app] = true;
153
-		$appPath = self::getAppPath($app);
154
-		if ($appPath === false) {
155
-			return;
156
-		}
157
-
158
-		// in case someone calls loadApp() directly
159
-		self::registerAutoloading($app, $appPath);
160
-
161
-		/** @var Coordinator $coordinator */
162
-		$coordinator = \OC::$server->query(Coordinator::class);
163
-		$isBootable = $coordinator->isBootable($app);
164
-
165
-		$hasAppPhpFile = is_file($appPath . '/appinfo/app.php');
166
-
167
-		if ($isBootable && $hasAppPhpFile) {
168
-			\OC::$server->getLogger()->error('/appinfo/app.php is not loaded when \OCP\AppFramework\Bootstrap\IBootstrap on the application class is used. Migrate everything from app.php to the Application class.', [
169
-				'app' => $app,
170
-			]);
171
-		} elseif ($hasAppPhpFile) {
172
-			\OC::$server->getLogger()->debug('/appinfo/app.php is deprecated, use \OCP\AppFramework\Bootstrap\IBootstrap on the application class instead.', [
173
-				'app' => $app,
174
-			]);
175
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
176
-			try {
177
-				self::requireAppFile($app);
178
-			} catch (Throwable $ex) {
179
-				if ($ex instanceof ServerNotAvailableException) {
180
-					throw $ex;
181
-				}
182
-				if (!\OC::$server->getAppManager()->isShipped($app) && !self::isType($app, ['authentication'])) {
183
-					\OC::$server->getLogger()->logException($ex, [
184
-						'message' => "App $app threw an error during app.php load and will be disabled: " . $ex->getMessage(),
185
-					]);
186
-
187
-					// Only disable apps which are not shipped and that are not authentication apps
188
-					\OC::$server->getAppManager()->disableApp($app, true);
189
-				} else {
190
-					\OC::$server->getLogger()->logException($ex, [
191
-						'message' => "App $app threw an error during app.php load: " . $ex->getMessage(),
192
-					]);
193
-				}
194
-			}
195
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
196
-		}
197
-		$coordinator->bootApp($app);
198
-
199
-		$info = self::getAppInfo($app);
200
-		if (!empty($info['activity']['filters'])) {
201
-			foreach ($info['activity']['filters'] as $filter) {
202
-				\OC::$server->getActivityManager()->registerFilter($filter);
203
-			}
204
-		}
205
-		if (!empty($info['activity']['settings'])) {
206
-			foreach ($info['activity']['settings'] as $setting) {
207
-				\OC::$server->getActivityManager()->registerSetting($setting);
208
-			}
209
-		}
210
-		if (!empty($info['activity']['providers'])) {
211
-			foreach ($info['activity']['providers'] as $provider) {
212
-				\OC::$server->getActivityManager()->registerProvider($provider);
213
-			}
214
-		}
215
-
216
-		if (!empty($info['settings']['admin'])) {
217
-			foreach ($info['settings']['admin'] as $setting) {
218
-				\OC::$server->getSettingsManager()->registerSetting('admin', $setting);
219
-			}
220
-		}
221
-		if (!empty($info['settings']['admin-section'])) {
222
-			foreach ($info['settings']['admin-section'] as $section) {
223
-				\OC::$server->getSettingsManager()->registerSection('admin', $section);
224
-			}
225
-		}
226
-		if (!empty($info['settings']['personal'])) {
227
-			foreach ($info['settings']['personal'] as $setting) {
228
-				\OC::$server->getSettingsManager()->registerSetting('personal', $setting);
229
-			}
230
-		}
231
-		if (!empty($info['settings']['personal-section'])) {
232
-			foreach ($info['settings']['personal-section'] as $section) {
233
-				\OC::$server->getSettingsManager()->registerSection('personal', $section);
234
-			}
235
-		}
236
-
237
-		if (!empty($info['collaboration']['plugins'])) {
238
-			// deal with one or many plugin entries
239
-			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
240
-				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
241
-			foreach ($plugins as $plugin) {
242
-				if ($plugin['@attributes']['type'] === 'collaborator-search') {
243
-					$pluginInfo = [
244
-						'shareType' => $plugin['@attributes']['share-type'],
245
-						'class' => $plugin['@value'],
246
-					];
247
-					\OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
248
-				} elseif ($plugin['@attributes']['type'] === 'autocomplete-sort') {
249
-					\OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
250
-				}
251
-			}
252
-		}
253
-	}
254
-
255
-	/**
256
-	 * @internal
257
-	 * @param string $app
258
-	 * @param string $path
259
-	 * @param bool $force
260
-	 */
261
-	public static function registerAutoloading(string $app, string $path, bool $force = false) {
262
-		$key = $app . '-' . $path;
263
-		if (!$force && isset(self::$alreadyRegistered[$key])) {
264
-			return;
265
-		}
266
-
267
-		self::$alreadyRegistered[$key] = true;
268
-
269
-		// Register on PSR-4 composer autoloader
270
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
271
-		\OC::$server->registerNamespace($app, $appNamespace);
272
-
273
-		if (file_exists($path . '/composer/autoload.php')) {
274
-			require_once $path . '/composer/autoload.php';
275
-		} else {
276
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
277
-			// Register on legacy autoloader
278
-			\OC::$loader->addValidRoot($path);
279
-		}
280
-
281
-		// Register Test namespace only when testing
282
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
283
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
284
-		}
285
-	}
286
-
287
-	/**
288
-	 * Load app.php from the given app
289
-	 *
290
-	 * @param string $app app name
291
-	 * @throws Error
292
-	 */
293
-	private static function requireAppFile(string $app) {
294
-		// encapsulated here to avoid variable scope conflicts
295
-		require_once $app . '/appinfo/app.php';
296
-	}
297
-
298
-	/**
299
-	 * check if an app is of a specific type
300
-	 *
301
-	 * @param string $app
302
-	 * @param array $types
303
-	 * @return bool
304
-	 */
305
-	public static function isType(string $app, array $types): bool {
306
-		$appTypes = self::getAppTypes($app);
307
-		foreach ($types as $type) {
308
-			if (array_search($type, $appTypes) !== false) {
309
-				return true;
310
-			}
311
-		}
312
-		return false;
313
-	}
314
-
315
-	/**
316
-	 * get the types of an app
317
-	 *
318
-	 * @param string $app
319
-	 * @return array
320
-	 */
321
-	private static function getAppTypes(string $app): array {
322
-		//load the cache
323
-		if (count(self::$appTypes) == 0) {
324
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
325
-		}
326
-
327
-		if (isset(self::$appTypes[$app])) {
328
-			return explode(',', self::$appTypes[$app]);
329
-		}
330
-
331
-		return [];
332
-	}
333
-
334
-	/**
335
-	 * read app types from info.xml and cache them in the database
336
-	 */
337
-	public static function setAppTypes(string $app) {
338
-		$appManager = \OC::$server->getAppManager();
339
-		$appData = $appManager->getAppInfo($app);
340
-		if (!is_array($appData)) {
341
-			return;
342
-		}
343
-
344
-		if (isset($appData['types'])) {
345
-			$appTypes = implode(',', $appData['types']);
346
-		} else {
347
-			$appTypes = '';
348
-			$appData['types'] = [];
349
-		}
350
-
351
-		$config = \OC::$server->getConfig();
352
-		$config->setAppValue($app, 'types', $appTypes);
353
-
354
-		if ($appManager->hasProtectedAppType($appData['types'])) {
355
-			$enabled = $config->getAppValue($app, 'enabled', 'yes');
356
-			if ($enabled !== 'yes' && $enabled !== 'no') {
357
-				$config->setAppValue($app, 'enabled', 'yes');
358
-			}
359
-		}
360
-	}
361
-
362
-	/**
363
-	 * Returns apps enabled for the current user.
364
-	 *
365
-	 * @param bool $forceRefresh whether to refresh the cache
366
-	 * @param bool $all whether to return apps for all users, not only the
367
-	 * currently logged in one
368
-	 * @return string[]
369
-	 */
370
-	public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array {
371
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
372
-			return [];
373
-		}
374
-		// in incognito mode or when logged out, $user will be false,
375
-		// which is also the case during an upgrade
376
-		$appManager = \OC::$server->getAppManager();
377
-		if ($all) {
378
-			$user = null;
379
-		} else {
380
-			$user = \OC::$server->getUserSession()->getUser();
381
-		}
382
-
383
-		if (is_null($user)) {
384
-			$apps = $appManager->getInstalledApps();
385
-		} else {
386
-			$apps = $appManager->getEnabledAppsForUser($user);
387
-		}
388
-		$apps = array_filter($apps, function ($app) {
389
-			return $app !== 'files';//we add this manually
390
-		});
391
-		sort($apps);
392
-		array_unshift($apps, 'files');
393
-		return $apps;
394
-	}
395
-
396
-	/**
397
-	 * checks whether or not an app is enabled
398
-	 *
399
-	 * @param string $app app
400
-	 * @return bool
401
-	 * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
402
-	 *
403
-	 * This function checks whether or not an app is enabled.
404
-	 */
405
-	public static function isEnabled(string $app): bool {
406
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
407
-	}
408
-
409
-	/**
410
-	 * enables an app
411
-	 *
412
-	 * @param string $appId
413
-	 * @param array $groups (optional) when set, only these groups will have access to the app
414
-	 * @throws \Exception
415
-	 * @return void
416
-	 *
417
-	 * This function set an app as enabled in appconfig.
418
-	 */
419
-	public function enable(string $appId,
420
-						   array $groups = []) {
421
-
422
-		// Check if app is already downloaded
423
-		/** @var Installer $installer */
424
-		$installer = \OC::$server->query(Installer::class);
425
-		$isDownloaded = $installer->isDownloaded($appId);
426
-
427
-		if (!$isDownloaded) {
428
-			$installer->downloadApp($appId);
429
-		}
430
-
431
-		$installer->installApp($appId);
432
-
433
-		$appManager = \OC::$server->getAppManager();
434
-		if ($groups !== []) {
435
-			$groupManager = \OC::$server->getGroupManager();
436
-			$groupsList = [];
437
-			foreach ($groups as $group) {
438
-				$groupItem = $groupManager->get($group);
439
-				if ($groupItem instanceof \OCP\IGroup) {
440
-					$groupsList[] = $groupManager->get($group);
441
-				}
442
-			}
443
-			$appManager->enableAppForGroups($appId, $groupsList);
444
-		} else {
445
-			$appManager->enableApp($appId);
446
-		}
447
-	}
448
-
449
-	/**
450
-	 * Get the path where to install apps
451
-	 *
452
-	 * @return string|false
453
-	 */
454
-	public static function getInstallPath() {
455
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
456
-			return false;
457
-		}
458
-
459
-		foreach (OC::$APPSROOTS as $dir) {
460
-			if (isset($dir['writable']) && $dir['writable'] === true) {
461
-				return $dir['path'];
462
-			}
463
-		}
464
-
465
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', ILogger::ERROR);
466
-		return null;
467
-	}
468
-
469
-
470
-	/**
471
-	 * search for an app in all app-directories
472
-	 *
473
-	 * @param string $appId
474
-	 * @return false|string
475
-	 */
476
-	public static function findAppInDirectories(string $appId) {
477
-		$sanitizedAppId = self::cleanAppId($appId);
478
-		if ($sanitizedAppId !== $appId) {
479
-			return false;
480
-		}
481
-		static $app_dir = [];
482
-
483
-		if (isset($app_dir[$appId])) {
484
-			return $app_dir[$appId];
485
-		}
486
-
487
-		$possibleApps = [];
488
-		foreach (OC::$APPSROOTS as $dir) {
489
-			if (file_exists($dir['path'] . '/' . $appId)) {
490
-				$possibleApps[] = $dir;
491
-			}
492
-		}
493
-
494
-		if (empty($possibleApps)) {
495
-			return false;
496
-		} elseif (count($possibleApps) === 1) {
497
-			$dir = array_shift($possibleApps);
498
-			$app_dir[$appId] = $dir;
499
-			return $dir;
500
-		} else {
501
-			$versionToLoad = [];
502
-			foreach ($possibleApps as $possibleApp) {
503
-				$version = self::getAppVersionByPath($possibleApp['path'] . '/' . $appId);
504
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
505
-					$versionToLoad = [
506
-						'dir' => $possibleApp,
507
-						'version' => $version,
508
-					];
509
-				}
510
-			}
511
-			$app_dir[$appId] = $versionToLoad['dir'];
512
-			return $versionToLoad['dir'];
513
-			//TODO - write test
514
-		}
515
-	}
516
-
517
-	/**
518
-	 * Get the directory for the given app.
519
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
520
-	 *
521
-	 * @psalm-taint-specialize
522
-	 *
523
-	 * @param string $appId
524
-	 * @return string|false
525
-	 * @deprecated 11.0.0 use \OC::$server->getAppManager()->getAppPath()
526
-	 */
527
-	public static function getAppPath(string $appId) {
528
-		if ($appId === null || trim($appId) === '') {
529
-			return false;
530
-		}
531
-
532
-		if (($dir = self::findAppInDirectories($appId)) != false) {
533
-			return $dir['path'] . '/' . $appId;
534
-		}
535
-		return false;
536
-	}
537
-
538
-	/**
539
-	 * Get the path for the given app on the access
540
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
541
-	 *
542
-	 * @param string $appId
543
-	 * @return string|false
544
-	 * @deprecated 18.0.0 use \OC::$server->getAppManager()->getAppWebPath()
545
-	 */
546
-	public static function getAppWebPath(string $appId) {
547
-		if (($dir = self::findAppInDirectories($appId)) != false) {
548
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
549
-		}
550
-		return false;
551
-	}
552
-
553
-	/**
554
-	 * get the last version of the app from appinfo/info.xml
555
-	 *
556
-	 * @param string $appId
557
-	 * @param bool $useCache
558
-	 * @return string
559
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
560
-	 */
561
-	public static function getAppVersion(string $appId, bool $useCache = true): string {
562
-		return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
563
-	}
564
-
565
-	/**
566
-	 * get app's version based on it's path
567
-	 *
568
-	 * @param string $path
569
-	 * @return string
570
-	 */
571
-	public static function getAppVersionByPath(string $path): string {
572
-		$infoFile = $path . '/appinfo/info.xml';
573
-		$appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
574
-		return isset($appData['version']) ? $appData['version'] : '';
575
-	}
576
-
577
-
578
-	/**
579
-	 * Read all app metadata from the info.xml file
580
-	 *
581
-	 * @param string $appId id of the app or the path of the info.xml file
582
-	 * @param bool $path
583
-	 * @param string $lang
584
-	 * @return array|null
585
-	 * @note all data is read from info.xml, not just pre-defined fields
586
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
587
-	 */
588
-	public static function getAppInfo(string $appId, bool $path = false, string $lang = null) {
589
-		return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
590
-	}
591
-
592
-	/**
593
-	 * Returns the navigation
594
-	 *
595
-	 * @return array
596
-	 * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll()
597
-	 *
598
-	 * This function returns an array containing all entries added. The
599
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
600
-	 * given for each app the following keys exist:
601
-	 *   - active: boolean, signals if the user is on this navigation entry
602
-	 */
603
-	public static function getNavigation(): array {
604
-		return OC::$server->getNavigationManager()->getAll();
605
-	}
606
-
607
-	/**
608
-	 * Returns the Settings Navigation
609
-	 *
610
-	 * @return string[]
611
-	 * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll('settings')
612
-	 *
613
-	 * This function returns an array containing all settings pages added. The
614
-	 * entries are sorted by the key 'order' ascending.
615
-	 */
616
-	public static function getSettingsNavigation(): array {
617
-		return OC::$server->getNavigationManager()->getAll('settings');
618
-	}
619
-
620
-	/**
621
-	 * get the id of loaded app
622
-	 *
623
-	 * @return string
624
-	 */
625
-	public static function getCurrentApp(): string {
626
-		$request = \OC::$server->getRequest();
627
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
628
-		$topFolder = substr($script, 0, strpos($script, '/') ?: 0);
629
-		if (empty($topFolder)) {
630
-			$path_info = $request->getPathInfo();
631
-			if ($path_info) {
632
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
633
-			}
634
-		}
635
-		if ($topFolder == 'apps') {
636
-			$length = strlen($topFolder);
637
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1) ?: '';
638
-		} else {
639
-			return $topFolder;
640
-		}
641
-	}
642
-
643
-	/**
644
-	 * @param string $type
645
-	 * @return array
646
-	 */
647
-	public static function getForms(string $type): array {
648
-		$forms = [];
649
-		switch ($type) {
650
-			case 'admin':
651
-				$source = self::$adminForms;
652
-				break;
653
-			case 'personal':
654
-				$source = self::$personalForms;
655
-				break;
656
-			default:
657
-				return [];
658
-		}
659
-		foreach ($source as $form) {
660
-			$forms[] = include $form;
661
-		}
662
-		return $forms;
663
-	}
664
-
665
-	/**
666
-	 * register an admin form to be shown
667
-	 *
668
-	 * @param string $app
669
-	 * @param string $page
670
-	 */
671
-	public static function registerAdmin(string $app, string $page) {
672
-		self::$adminForms[] = $app . '/' . $page . '.php';
673
-	}
674
-
675
-	/**
676
-	 * register a personal form to be shown
677
-	 * @param string $app
678
-	 * @param string $page
679
-	 */
680
-	public static function registerPersonal(string $app, string $page) {
681
-		self::$personalForms[] = $app . '/' . $page . '.php';
682
-	}
683
-
684
-	/**
685
-	 * @param array $entry
686
-	 * @deprecated 20.0.0 Please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface
687
-	 */
688
-	public static function registerLogIn(array $entry) {
689
-		\OC::$server->getLogger()->debug('OC_App::registerLogIn() is deprecated, please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface');
690
-		self::$altLogin[] = $entry;
691
-	}
692
-
693
-	/**
694
-	 * @return array
695
-	 */
696
-	public static function getAlternativeLogIns(): array {
697
-		/** @var Coordinator $bootstrapCoordinator */
698
-		$bootstrapCoordinator = \OC::$server->query(Coordinator::class);
699
-
700
-		foreach ($bootstrapCoordinator->getRegistrationContext()->getAlternativeLogins() as $registration) {
701
-			if (!in_array(IAlternativeLogin::class, class_implements($registration['class']), true)) {
702
-				\OC::$server->getLogger()->error('Alternative login option {option} does not implement {interface} and is therefore ignored.', [
703
-					'option' => $registration['class'],
704
-					'interface' => IAlternativeLogin::class,
705
-					'app' => $registration['app'],
706
-				]);
707
-				continue;
708
-			}
709
-
710
-			try {
711
-				/** @var IAlternativeLogin $provider */
712
-				$provider = \OC::$server->query($registration['class']);
713
-			} catch (QueryException $e) {
714
-				\OC::$server->getLogger()->logException($e, [
715
-					'message' => 'Alternative login option {option} can not be initialised.',
716
-					'option' => $registration['class'],
717
-					'app' => $registration['app'],
718
-				]);
719
-			}
720
-
721
-			try {
722
-				$provider->load();
723
-
724
-				self::$altLogin[] = [
725
-					'name' => $provider->getLabel(),
726
-					'href' => $provider->getLink(),
727
-					'style' => $provider->getClass(),
728
-				];
729
-			} catch (Throwable $e) {
730
-				\OC::$server->getLogger()->logException($e, [
731
-					'message' => 'Alternative login option {option} had an error while loading.',
732
-					'option' => $registration['class'],
733
-					'app' => $registration['app'],
734
-				]);
735
-			}
736
-		}
737
-
738
-		return self::$altLogin;
739
-	}
740
-
741
-	/**
742
-	 * get a list of all apps in the apps folder
743
-	 *
744
-	 * @return string[] an array of app names (string IDs)
745
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
746
-	 */
747
-	public static function getAllApps(): array {
748
-		$apps = [];
749
-
750
-		foreach (OC::$APPSROOTS as $apps_dir) {
751
-			if (!is_readable($apps_dir['path'])) {
752
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
753
-				continue;
754
-			}
755
-			$dh = opendir($apps_dir['path']);
756
-
757
-			if (is_resource($dh)) {
758
-				while (($file = readdir($dh)) !== false) {
759
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
760
-						$apps[] = $file;
761
-					}
762
-				}
763
-			}
764
-		}
765
-
766
-		$apps = array_unique($apps);
767
-
768
-		return $apps;
769
-	}
770
-
771
-	/**
772
-	 * List all apps, this is used in apps.php
773
-	 *
774
-	 * @return array
775
-	 */
776
-	public function listAllApps(): array {
777
-		$installedApps = OC_App::getAllApps();
778
-
779
-		$appManager = \OC::$server->getAppManager();
780
-		//we don't want to show configuration for these
781
-		$blacklist = $appManager->getAlwaysEnabledApps();
782
-		$appList = [];
783
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
784
-		$urlGenerator = \OC::$server->getURLGenerator();
785
-		/** @var \OCP\Support\Subscription\IRegistry $subscriptionRegistry */
786
-		$subscriptionRegistry = \OC::$server->query(\OCP\Support\Subscription\IRegistry::class);
787
-		$supportedApps = $subscriptionRegistry->delegateGetSupportedApps();
788
-
789
-		foreach ($installedApps as $app) {
790
-			if (array_search($app, $blacklist) === false) {
791
-				$info = OC_App::getAppInfo($app, false, $langCode);
792
-				if (!is_array($info)) {
793
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
794
-					continue;
795
-				}
796
-
797
-				if (!isset($info['name'])) {
798
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
799
-					continue;
800
-				}
801
-
802
-				$enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
803
-				$info['groups'] = null;
804
-				if ($enabled === 'yes') {
805
-					$active = true;
806
-				} elseif ($enabled === 'no') {
807
-					$active = false;
808
-				} else {
809
-					$active = true;
810
-					$info['groups'] = $enabled;
811
-				}
812
-
813
-				$info['active'] = $active;
814
-
815
-				if ($appManager->isShipped($app)) {
816
-					$info['internal'] = true;
817
-					$info['level'] = self::officialApp;
818
-					$info['removable'] = false;
819
-				} else {
820
-					$info['internal'] = false;
821
-					$info['removable'] = true;
822
-				}
823
-
824
-				if (in_array($app, $supportedApps)) {
825
-					$info['level'] = self::supportedApp;
826
-				}
827
-
828
-				$appPath = self::getAppPath($app);
829
-				if ($appPath !== false) {
830
-					$appIcon = $appPath . '/img/' . $app . '.svg';
831
-					if (file_exists($appIcon)) {
832
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
833
-						$info['previewAsIcon'] = true;
834
-					} else {
835
-						$appIcon = $appPath . '/img/app.svg';
836
-						if (file_exists($appIcon)) {
837
-							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
838
-							$info['previewAsIcon'] = true;
839
-						}
840
-					}
841
-				}
842
-				// fix documentation
843
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
844
-					foreach ($info['documentation'] as $key => $url) {
845
-						// If it is not an absolute URL we assume it is a key
846
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
847
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
848
-							$url = $urlGenerator->linkToDocs($url);
849
-						}
850
-
851
-						$info['documentation'][$key] = $url;
852
-					}
853
-				}
854
-
855
-				$info['version'] = OC_App::getAppVersion($app);
856
-				$appList[] = $info;
857
-			}
858
-		}
859
-
860
-		return $appList;
861
-	}
862
-
863
-	public static function shouldUpgrade(string $app): bool {
864
-		$versions = self::getAppVersions();
865
-		$currentVersion = OC_App::getAppVersion($app);
866
-		if ($currentVersion && isset($versions[$app])) {
867
-			$installedVersion = $versions[$app];
868
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
869
-				return true;
870
-			}
871
-		}
872
-		return false;
873
-	}
874
-
875
-	/**
876
-	 * Adjust the number of version parts of $version1 to match
877
-	 * the number of version parts of $version2.
878
-	 *
879
-	 * @param string $version1 version to adjust
880
-	 * @param string $version2 version to take the number of parts from
881
-	 * @return string shortened $version1
882
-	 */
883
-	private static function adjustVersionParts(string $version1, string $version2): string {
884
-		$version1 = explode('.', $version1);
885
-		$version2 = explode('.', $version2);
886
-		// reduce $version1 to match the number of parts in $version2
887
-		while (count($version1) > count($version2)) {
888
-			array_pop($version1);
889
-		}
890
-		// if $version1 does not have enough parts, add some
891
-		while (count($version1) < count($version2)) {
892
-			$version1[] = '0';
893
-		}
894
-		return implode('.', $version1);
895
-	}
896
-
897
-	/**
898
-	 * Check whether the current ownCloud version matches the given
899
-	 * application's version requirements.
900
-	 *
901
-	 * The comparison is made based on the number of parts that the
902
-	 * app info version has. For example for ownCloud 6.0.3 if the
903
-	 * app info version is expecting version 6.0, the comparison is
904
-	 * made on the first two parts of the ownCloud version.
905
-	 * This means that it's possible to specify "requiremin" => 6
906
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
907
-	 *
908
-	 * @param string $ocVersion ownCloud version to check against
909
-	 * @param array $appInfo app info (from xml)
910
-	 *
911
-	 * @return boolean true if compatible, otherwise false
912
-	 */
913
-	public static function isAppCompatible(string $ocVersion, array $appInfo, bool $ignoreMax = false): bool {
914
-		$requireMin = '';
915
-		$requireMax = '';
916
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
917
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
918
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
919
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
920
-		} elseif (isset($appInfo['requiremin'])) {
921
-			$requireMin = $appInfo['requiremin'];
922
-		} elseif (isset($appInfo['require'])) {
923
-			$requireMin = $appInfo['require'];
924
-		}
925
-
926
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
927
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
928
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
929
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
930
-		} elseif (isset($appInfo['requiremax'])) {
931
-			$requireMax = $appInfo['requiremax'];
932
-		}
933
-
934
-		if (!empty($requireMin)
935
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
936
-		) {
937
-			return false;
938
-		}
939
-
940
-		if (!$ignoreMax && !empty($requireMax)
941
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
942
-		) {
943
-			return false;
944
-		}
945
-
946
-		return true;
947
-	}
948
-
949
-	/**
950
-	 * get the installed version of all apps
951
-	 */
952
-	public static function getAppVersions() {
953
-		static $versions;
954
-
955
-		if (!$versions) {
956
-			$appConfig = \OC::$server->getAppConfig();
957
-			$versions = $appConfig->getValues(false, 'installed_version');
958
-		}
959
-		return $versions;
960
-	}
961
-
962
-	/**
963
-	 * update the database for the app and call the update script
964
-	 *
965
-	 * @param string $appId
966
-	 * @return bool
967
-	 */
968
-	public static function updateApp(string $appId): bool {
969
-		$appPath = self::getAppPath($appId);
970
-		if ($appPath === false) {
971
-			return false;
972
-		}
973
-
974
-		\OC::$server->getAppManager()->clearAppsCache();
975
-		$appData = self::getAppInfo($appId);
976
-
977
-		$ignoreMaxApps = \OC::$server->getConfig()->getSystemValue('app_install_overwrite', []);
978
-		$ignoreMax = in_array($appId, $ignoreMaxApps, true);
979
-		\OC_App::checkAppDependencies(
980
-			\OC::$server->getConfig(),
981
-			\OC::$server->getL10N('core'),
982
-			$appData,
983
-			$ignoreMax
984
-		);
985
-
986
-		self::registerAutoloading($appId, $appPath, true);
987
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
988
-
989
-		if (file_exists($appPath . '/appinfo/database.xml')) {
990
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
991
-		} else {
992
-			$ms = new MigrationService($appId, \OC::$server->get(\OC\DB\Connection::class));
993
-			$ms->migrate();
994
-		}
995
-
996
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
997
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
998
-		// update appversion in app manager
999
-		\OC::$server->getAppManager()->clearAppsCache();
1000
-		\OC::$server->getAppManager()->getAppVersion($appId, false);
1001
-
1002
-		self::setupBackgroundJobs($appData['background-jobs']);
1003
-
1004
-		//set remote/public handlers
1005
-		if (array_key_exists('ocsid', $appData)) {
1006
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1007
-		} elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1008
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1009
-		}
1010
-		foreach ($appData['remote'] as $name => $path) {
1011
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1012
-		}
1013
-		foreach ($appData['public'] as $name => $path) {
1014
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1015
-		}
1016
-
1017
-		self::setAppTypes($appId);
1018
-
1019
-		$version = \OC_App::getAppVersion($appId);
1020
-		\OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
1021
-
1022
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1023
-			ManagerEvent::EVENT_APP_UPDATE, $appId
1024
-		));
1025
-
1026
-		return true;
1027
-	}
1028
-
1029
-	/**
1030
-	 * @param string $appId
1031
-	 * @param string[] $steps
1032
-	 * @throws \OC\NeedsUpdateException
1033
-	 */
1034
-	public static function executeRepairSteps(string $appId, array $steps) {
1035
-		if (empty($steps)) {
1036
-			return;
1037
-		}
1038
-		// load the app
1039
-		self::loadApp($appId);
1040
-
1041
-		$dispatcher = OC::$server->getEventDispatcher();
1042
-
1043
-		// load the steps
1044
-		$r = new Repair([], $dispatcher);
1045
-		foreach ($steps as $step) {
1046
-			try {
1047
-				$r->addStep($step);
1048
-			} catch (Exception $ex) {
1049
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1050
-				\OC::$server->getLogger()->logException($ex);
1051
-			}
1052
-		}
1053
-		// run the steps
1054
-		$r->run();
1055
-	}
1056
-
1057
-	public static function setupBackgroundJobs(array $jobs) {
1058
-		$queue = \OC::$server->getJobList();
1059
-		foreach ($jobs as $job) {
1060
-			$queue->add($job);
1061
-		}
1062
-	}
1063
-
1064
-	/**
1065
-	 * @param string $appId
1066
-	 * @param string[] $steps
1067
-	 */
1068
-	private static function setupLiveMigrations(string $appId, array $steps) {
1069
-		$queue = \OC::$server->getJobList();
1070
-		foreach ($steps as $step) {
1071
-			$queue->add('OC\Migration\BackgroundRepair', [
1072
-				'app' => $appId,
1073
-				'step' => $step]);
1074
-		}
1075
-	}
1076
-
1077
-	/**
1078
-	 * @param string $appId
1079
-	 * @return \OC\Files\View|false
1080
-	 */
1081
-	public static function getStorage(string $appId) {
1082
-		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1083
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1084
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1085
-				if (!$view->file_exists($appId)) {
1086
-					$view->mkdir($appId);
1087
-				}
1088
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1089
-			} else {
1090
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
1091
-				return false;
1092
-			}
1093
-		} else {
1094
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
1095
-			return false;
1096
-		}
1097
-	}
1098
-
1099
-	protected static function findBestL10NOption(array $options, string $lang): string {
1100
-		// only a single option
1101
-		if (isset($options['@value'])) {
1102
-			return $options['@value'];
1103
-		}
1104
-
1105
-		$fallback = $similarLangFallback = $englishFallback = false;
1106
-
1107
-		$lang = strtolower($lang);
1108
-		$similarLang = $lang;
1109
-		if (strpos($similarLang, '_')) {
1110
-			// For "de_DE" we want to find "de" and the other way around
1111
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1112
-		}
1113
-
1114
-		foreach ($options as $option) {
1115
-			if (is_array($option)) {
1116
-				if ($fallback === false) {
1117
-					$fallback = $option['@value'];
1118
-				}
1119
-
1120
-				if (!isset($option['@attributes']['lang'])) {
1121
-					continue;
1122
-				}
1123
-
1124
-				$attributeLang = strtolower($option['@attributes']['lang']);
1125
-				if ($attributeLang === $lang) {
1126
-					return $option['@value'];
1127
-				}
1128
-
1129
-				if ($attributeLang === $similarLang) {
1130
-					$similarLangFallback = $option['@value'];
1131
-				} elseif (strpos($attributeLang, $similarLang . '_') === 0) {
1132
-					if ($similarLangFallback === false) {
1133
-						$similarLangFallback = $option['@value'];
1134
-					}
1135
-				}
1136
-			} else {
1137
-				$englishFallback = $option;
1138
-			}
1139
-		}
1140
-
1141
-		if ($similarLangFallback !== false) {
1142
-			return $similarLangFallback;
1143
-		} elseif ($englishFallback !== false) {
1144
-			return $englishFallback;
1145
-		}
1146
-		return (string) $fallback;
1147
-	}
1148
-
1149
-	/**
1150
-	 * parses the app data array and enhanced the 'description' value
1151
-	 *
1152
-	 * @param array $data the app data
1153
-	 * @param string $lang
1154
-	 * @return array improved app data
1155
-	 */
1156
-	public static function parseAppInfo(array $data, $lang = null): array {
1157
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1158
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1159
-		}
1160
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1161
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1162
-		}
1163
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1164
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1165
-		} elseif (isset($data['description']) && is_string($data['description'])) {
1166
-			$data['description'] = trim($data['description']);
1167
-		} else {
1168
-			$data['description'] = '';
1169
-		}
1170
-
1171
-		return $data;
1172
-	}
1173
-
1174
-	/**
1175
-	 * @param \OCP\IConfig $config
1176
-	 * @param \OCP\IL10N $l
1177
-	 * @param array $info
1178
-	 * @throws \Exception
1179
-	 */
1180
-	public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info, bool $ignoreMax) {
1181
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1182
-		$missing = $dependencyAnalyzer->analyze($info, $ignoreMax);
1183
-		if (!empty($missing)) {
1184
-			$missingMsg = implode(PHP_EOL, $missing);
1185
-			throw new \Exception(
1186
-				$l->t('App "%1$s" cannot be installed because the following dependencies are not fulfilled: %2$s',
1187
-					[$info['name'], $missingMsg]
1188
-				)
1189
-			);
1190
-		}
1191
-	}
71
+    private static $adminForms = [];
72
+    private static $personalForms = [];
73
+    private static $appTypes = [];
74
+    private static $loadedApps = [];
75
+    private static $altLogin = [];
76
+    private static $alreadyRegistered = [];
77
+    public const supportedApp = 300;
78
+    public const officialApp = 200;
79
+
80
+    /**
81
+     * clean the appId
82
+     *
83
+     * @psalm-taint-escape file
84
+     * @psalm-taint-escape include
85
+     *
86
+     * @param string $app AppId that needs to be cleaned
87
+     * @return string
88
+     */
89
+    public static function cleanAppId(string $app): string {
90
+        return str_replace(['\0', '/', '\\', '..'], '', $app);
91
+    }
92
+
93
+    /**
94
+     * Check if an app is loaded
95
+     *
96
+     * @param string $app
97
+     * @return bool
98
+     */
99
+    public static function isAppLoaded(string $app): bool {
100
+        return isset(self::$loadedApps[$app]);
101
+    }
102
+
103
+    /**
104
+     * loads all apps
105
+     *
106
+     * @param string[] $types
107
+     * @return bool
108
+     *
109
+     * This function walks through the ownCloud directory and loads all apps
110
+     * it can find. A directory contains an app if the file /appinfo/info.xml
111
+     * exists.
112
+     *
113
+     * if $types is set to non-empty array, only apps of those types will be loaded
114
+     */
115
+    public static function loadApps(array $types = []): bool {
116
+        if ((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) {
117
+            return false;
118
+        }
119
+        // Load the enabled apps here
120
+        $apps = self::getEnabledApps();
121
+
122
+        // Add each apps' folder as allowed class path
123
+        foreach ($apps as $app) {
124
+            // If the app is already loaded then autoloading it makes no sense
125
+            if (!isset(self::$loadedApps[$app])) {
126
+                $path = self::getAppPath($app);
127
+                if ($path !== false) {
128
+                    self::registerAutoloading($app, $path);
129
+                }
130
+            }
131
+        }
132
+
133
+        // prevent app.php from printing output
134
+        ob_start();
135
+        foreach ($apps as $app) {
136
+            if (!isset(self::$loadedApps[$app]) && ($types === [] || self::isType($app, $types))) {
137
+                self::loadApp($app);
138
+            }
139
+        }
140
+        ob_end_clean();
141
+
142
+        return true;
143
+    }
144
+
145
+    /**
146
+     * load a single app
147
+     *
148
+     * @param string $app
149
+     * @throws Exception
150
+     */
151
+    public static function loadApp(string $app) {
152
+        self::$loadedApps[$app] = true;
153
+        $appPath = self::getAppPath($app);
154
+        if ($appPath === false) {
155
+            return;
156
+        }
157
+
158
+        // in case someone calls loadApp() directly
159
+        self::registerAutoloading($app, $appPath);
160
+
161
+        /** @var Coordinator $coordinator */
162
+        $coordinator = \OC::$server->query(Coordinator::class);
163
+        $isBootable = $coordinator->isBootable($app);
164
+
165
+        $hasAppPhpFile = is_file($appPath . '/appinfo/app.php');
166
+
167
+        if ($isBootable && $hasAppPhpFile) {
168
+            \OC::$server->getLogger()->error('/appinfo/app.php is not loaded when \OCP\AppFramework\Bootstrap\IBootstrap on the application class is used. Migrate everything from app.php to the Application class.', [
169
+                'app' => $app,
170
+            ]);
171
+        } elseif ($hasAppPhpFile) {
172
+            \OC::$server->getLogger()->debug('/appinfo/app.php is deprecated, use \OCP\AppFramework\Bootstrap\IBootstrap on the application class instead.', [
173
+                'app' => $app,
174
+            ]);
175
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
176
+            try {
177
+                self::requireAppFile($app);
178
+            } catch (Throwable $ex) {
179
+                if ($ex instanceof ServerNotAvailableException) {
180
+                    throw $ex;
181
+                }
182
+                if (!\OC::$server->getAppManager()->isShipped($app) && !self::isType($app, ['authentication'])) {
183
+                    \OC::$server->getLogger()->logException($ex, [
184
+                        'message' => "App $app threw an error during app.php load and will be disabled: " . $ex->getMessage(),
185
+                    ]);
186
+
187
+                    // Only disable apps which are not shipped and that are not authentication apps
188
+                    \OC::$server->getAppManager()->disableApp($app, true);
189
+                } else {
190
+                    \OC::$server->getLogger()->logException($ex, [
191
+                        'message' => "App $app threw an error during app.php load: " . $ex->getMessage(),
192
+                    ]);
193
+                }
194
+            }
195
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
196
+        }
197
+        $coordinator->bootApp($app);
198
+
199
+        $info = self::getAppInfo($app);
200
+        if (!empty($info['activity']['filters'])) {
201
+            foreach ($info['activity']['filters'] as $filter) {
202
+                \OC::$server->getActivityManager()->registerFilter($filter);
203
+            }
204
+        }
205
+        if (!empty($info['activity']['settings'])) {
206
+            foreach ($info['activity']['settings'] as $setting) {
207
+                \OC::$server->getActivityManager()->registerSetting($setting);
208
+            }
209
+        }
210
+        if (!empty($info['activity']['providers'])) {
211
+            foreach ($info['activity']['providers'] as $provider) {
212
+                \OC::$server->getActivityManager()->registerProvider($provider);
213
+            }
214
+        }
215
+
216
+        if (!empty($info['settings']['admin'])) {
217
+            foreach ($info['settings']['admin'] as $setting) {
218
+                \OC::$server->getSettingsManager()->registerSetting('admin', $setting);
219
+            }
220
+        }
221
+        if (!empty($info['settings']['admin-section'])) {
222
+            foreach ($info['settings']['admin-section'] as $section) {
223
+                \OC::$server->getSettingsManager()->registerSection('admin', $section);
224
+            }
225
+        }
226
+        if (!empty($info['settings']['personal'])) {
227
+            foreach ($info['settings']['personal'] as $setting) {
228
+                \OC::$server->getSettingsManager()->registerSetting('personal', $setting);
229
+            }
230
+        }
231
+        if (!empty($info['settings']['personal-section'])) {
232
+            foreach ($info['settings']['personal-section'] as $section) {
233
+                \OC::$server->getSettingsManager()->registerSection('personal', $section);
234
+            }
235
+        }
236
+
237
+        if (!empty($info['collaboration']['plugins'])) {
238
+            // deal with one or many plugin entries
239
+            $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
240
+                [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
241
+            foreach ($plugins as $plugin) {
242
+                if ($plugin['@attributes']['type'] === 'collaborator-search') {
243
+                    $pluginInfo = [
244
+                        'shareType' => $plugin['@attributes']['share-type'],
245
+                        'class' => $plugin['@value'],
246
+                    ];
247
+                    \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
248
+                } elseif ($plugin['@attributes']['type'] === 'autocomplete-sort') {
249
+                    \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
250
+                }
251
+            }
252
+        }
253
+    }
254
+
255
+    /**
256
+     * @internal
257
+     * @param string $app
258
+     * @param string $path
259
+     * @param bool $force
260
+     */
261
+    public static function registerAutoloading(string $app, string $path, bool $force = false) {
262
+        $key = $app . '-' . $path;
263
+        if (!$force && isset(self::$alreadyRegistered[$key])) {
264
+            return;
265
+        }
266
+
267
+        self::$alreadyRegistered[$key] = true;
268
+
269
+        // Register on PSR-4 composer autoloader
270
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
271
+        \OC::$server->registerNamespace($app, $appNamespace);
272
+
273
+        if (file_exists($path . '/composer/autoload.php')) {
274
+            require_once $path . '/composer/autoload.php';
275
+        } else {
276
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
277
+            // Register on legacy autoloader
278
+            \OC::$loader->addValidRoot($path);
279
+        }
280
+
281
+        // Register Test namespace only when testing
282
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
283
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
284
+        }
285
+    }
286
+
287
+    /**
288
+     * Load app.php from the given app
289
+     *
290
+     * @param string $app app name
291
+     * @throws Error
292
+     */
293
+    private static function requireAppFile(string $app) {
294
+        // encapsulated here to avoid variable scope conflicts
295
+        require_once $app . '/appinfo/app.php';
296
+    }
297
+
298
+    /**
299
+     * check if an app is of a specific type
300
+     *
301
+     * @param string $app
302
+     * @param array $types
303
+     * @return bool
304
+     */
305
+    public static function isType(string $app, array $types): bool {
306
+        $appTypes = self::getAppTypes($app);
307
+        foreach ($types as $type) {
308
+            if (array_search($type, $appTypes) !== false) {
309
+                return true;
310
+            }
311
+        }
312
+        return false;
313
+    }
314
+
315
+    /**
316
+     * get the types of an app
317
+     *
318
+     * @param string $app
319
+     * @return array
320
+     */
321
+    private static function getAppTypes(string $app): array {
322
+        //load the cache
323
+        if (count(self::$appTypes) == 0) {
324
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
325
+        }
326
+
327
+        if (isset(self::$appTypes[$app])) {
328
+            return explode(',', self::$appTypes[$app]);
329
+        }
330
+
331
+        return [];
332
+    }
333
+
334
+    /**
335
+     * read app types from info.xml and cache them in the database
336
+     */
337
+    public static function setAppTypes(string $app) {
338
+        $appManager = \OC::$server->getAppManager();
339
+        $appData = $appManager->getAppInfo($app);
340
+        if (!is_array($appData)) {
341
+            return;
342
+        }
343
+
344
+        if (isset($appData['types'])) {
345
+            $appTypes = implode(',', $appData['types']);
346
+        } else {
347
+            $appTypes = '';
348
+            $appData['types'] = [];
349
+        }
350
+
351
+        $config = \OC::$server->getConfig();
352
+        $config->setAppValue($app, 'types', $appTypes);
353
+
354
+        if ($appManager->hasProtectedAppType($appData['types'])) {
355
+            $enabled = $config->getAppValue($app, 'enabled', 'yes');
356
+            if ($enabled !== 'yes' && $enabled !== 'no') {
357
+                $config->setAppValue($app, 'enabled', 'yes');
358
+            }
359
+        }
360
+    }
361
+
362
+    /**
363
+     * Returns apps enabled for the current user.
364
+     *
365
+     * @param bool $forceRefresh whether to refresh the cache
366
+     * @param bool $all whether to return apps for all users, not only the
367
+     * currently logged in one
368
+     * @return string[]
369
+     */
370
+    public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array {
371
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
372
+            return [];
373
+        }
374
+        // in incognito mode or when logged out, $user will be false,
375
+        // which is also the case during an upgrade
376
+        $appManager = \OC::$server->getAppManager();
377
+        if ($all) {
378
+            $user = null;
379
+        } else {
380
+            $user = \OC::$server->getUserSession()->getUser();
381
+        }
382
+
383
+        if (is_null($user)) {
384
+            $apps = $appManager->getInstalledApps();
385
+        } else {
386
+            $apps = $appManager->getEnabledAppsForUser($user);
387
+        }
388
+        $apps = array_filter($apps, function ($app) {
389
+            return $app !== 'files';//we add this manually
390
+        });
391
+        sort($apps);
392
+        array_unshift($apps, 'files');
393
+        return $apps;
394
+    }
395
+
396
+    /**
397
+     * checks whether or not an app is enabled
398
+     *
399
+     * @param string $app app
400
+     * @return bool
401
+     * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
402
+     *
403
+     * This function checks whether or not an app is enabled.
404
+     */
405
+    public static function isEnabled(string $app): bool {
406
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
407
+    }
408
+
409
+    /**
410
+     * enables an app
411
+     *
412
+     * @param string $appId
413
+     * @param array $groups (optional) when set, only these groups will have access to the app
414
+     * @throws \Exception
415
+     * @return void
416
+     *
417
+     * This function set an app as enabled in appconfig.
418
+     */
419
+    public function enable(string $appId,
420
+                            array $groups = []) {
421
+
422
+        // Check if app is already downloaded
423
+        /** @var Installer $installer */
424
+        $installer = \OC::$server->query(Installer::class);
425
+        $isDownloaded = $installer->isDownloaded($appId);
426
+
427
+        if (!$isDownloaded) {
428
+            $installer->downloadApp($appId);
429
+        }
430
+
431
+        $installer->installApp($appId);
432
+
433
+        $appManager = \OC::$server->getAppManager();
434
+        if ($groups !== []) {
435
+            $groupManager = \OC::$server->getGroupManager();
436
+            $groupsList = [];
437
+            foreach ($groups as $group) {
438
+                $groupItem = $groupManager->get($group);
439
+                if ($groupItem instanceof \OCP\IGroup) {
440
+                    $groupsList[] = $groupManager->get($group);
441
+                }
442
+            }
443
+            $appManager->enableAppForGroups($appId, $groupsList);
444
+        } else {
445
+            $appManager->enableApp($appId);
446
+        }
447
+    }
448
+
449
+    /**
450
+     * Get the path where to install apps
451
+     *
452
+     * @return string|false
453
+     */
454
+    public static function getInstallPath() {
455
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
456
+            return false;
457
+        }
458
+
459
+        foreach (OC::$APPSROOTS as $dir) {
460
+            if (isset($dir['writable']) && $dir['writable'] === true) {
461
+                return $dir['path'];
462
+            }
463
+        }
464
+
465
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', ILogger::ERROR);
466
+        return null;
467
+    }
468
+
469
+
470
+    /**
471
+     * search for an app in all app-directories
472
+     *
473
+     * @param string $appId
474
+     * @return false|string
475
+     */
476
+    public static function findAppInDirectories(string $appId) {
477
+        $sanitizedAppId = self::cleanAppId($appId);
478
+        if ($sanitizedAppId !== $appId) {
479
+            return false;
480
+        }
481
+        static $app_dir = [];
482
+
483
+        if (isset($app_dir[$appId])) {
484
+            return $app_dir[$appId];
485
+        }
486
+
487
+        $possibleApps = [];
488
+        foreach (OC::$APPSROOTS as $dir) {
489
+            if (file_exists($dir['path'] . '/' . $appId)) {
490
+                $possibleApps[] = $dir;
491
+            }
492
+        }
493
+
494
+        if (empty($possibleApps)) {
495
+            return false;
496
+        } elseif (count($possibleApps) === 1) {
497
+            $dir = array_shift($possibleApps);
498
+            $app_dir[$appId] = $dir;
499
+            return $dir;
500
+        } else {
501
+            $versionToLoad = [];
502
+            foreach ($possibleApps as $possibleApp) {
503
+                $version = self::getAppVersionByPath($possibleApp['path'] . '/' . $appId);
504
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
505
+                    $versionToLoad = [
506
+                        'dir' => $possibleApp,
507
+                        'version' => $version,
508
+                    ];
509
+                }
510
+            }
511
+            $app_dir[$appId] = $versionToLoad['dir'];
512
+            return $versionToLoad['dir'];
513
+            //TODO - write test
514
+        }
515
+    }
516
+
517
+    /**
518
+     * Get the directory for the given app.
519
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
520
+     *
521
+     * @psalm-taint-specialize
522
+     *
523
+     * @param string $appId
524
+     * @return string|false
525
+     * @deprecated 11.0.0 use \OC::$server->getAppManager()->getAppPath()
526
+     */
527
+    public static function getAppPath(string $appId) {
528
+        if ($appId === null || trim($appId) === '') {
529
+            return false;
530
+        }
531
+
532
+        if (($dir = self::findAppInDirectories($appId)) != false) {
533
+            return $dir['path'] . '/' . $appId;
534
+        }
535
+        return false;
536
+    }
537
+
538
+    /**
539
+     * Get the path for the given app on the access
540
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
541
+     *
542
+     * @param string $appId
543
+     * @return string|false
544
+     * @deprecated 18.0.0 use \OC::$server->getAppManager()->getAppWebPath()
545
+     */
546
+    public static function getAppWebPath(string $appId) {
547
+        if (($dir = self::findAppInDirectories($appId)) != false) {
548
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
549
+        }
550
+        return false;
551
+    }
552
+
553
+    /**
554
+     * get the last version of the app from appinfo/info.xml
555
+     *
556
+     * @param string $appId
557
+     * @param bool $useCache
558
+     * @return string
559
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
560
+     */
561
+    public static function getAppVersion(string $appId, bool $useCache = true): string {
562
+        return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
563
+    }
564
+
565
+    /**
566
+     * get app's version based on it's path
567
+     *
568
+     * @param string $path
569
+     * @return string
570
+     */
571
+    public static function getAppVersionByPath(string $path): string {
572
+        $infoFile = $path . '/appinfo/info.xml';
573
+        $appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
574
+        return isset($appData['version']) ? $appData['version'] : '';
575
+    }
576
+
577
+
578
+    /**
579
+     * Read all app metadata from the info.xml file
580
+     *
581
+     * @param string $appId id of the app or the path of the info.xml file
582
+     * @param bool $path
583
+     * @param string $lang
584
+     * @return array|null
585
+     * @note all data is read from info.xml, not just pre-defined fields
586
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
587
+     */
588
+    public static function getAppInfo(string $appId, bool $path = false, string $lang = null) {
589
+        return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
590
+    }
591
+
592
+    /**
593
+     * Returns the navigation
594
+     *
595
+     * @return array
596
+     * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll()
597
+     *
598
+     * This function returns an array containing all entries added. The
599
+     * entries are sorted by the key 'order' ascending. Additional to the keys
600
+     * given for each app the following keys exist:
601
+     *   - active: boolean, signals if the user is on this navigation entry
602
+     */
603
+    public static function getNavigation(): array {
604
+        return OC::$server->getNavigationManager()->getAll();
605
+    }
606
+
607
+    /**
608
+     * Returns the Settings Navigation
609
+     *
610
+     * @return string[]
611
+     * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll('settings')
612
+     *
613
+     * This function returns an array containing all settings pages added. The
614
+     * entries are sorted by the key 'order' ascending.
615
+     */
616
+    public static function getSettingsNavigation(): array {
617
+        return OC::$server->getNavigationManager()->getAll('settings');
618
+    }
619
+
620
+    /**
621
+     * get the id of loaded app
622
+     *
623
+     * @return string
624
+     */
625
+    public static function getCurrentApp(): string {
626
+        $request = \OC::$server->getRequest();
627
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
628
+        $topFolder = substr($script, 0, strpos($script, '/') ?: 0);
629
+        if (empty($topFolder)) {
630
+            $path_info = $request->getPathInfo();
631
+            if ($path_info) {
632
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
633
+            }
634
+        }
635
+        if ($topFolder == 'apps') {
636
+            $length = strlen($topFolder);
637
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1) ?: '';
638
+        } else {
639
+            return $topFolder;
640
+        }
641
+    }
642
+
643
+    /**
644
+     * @param string $type
645
+     * @return array
646
+     */
647
+    public static function getForms(string $type): array {
648
+        $forms = [];
649
+        switch ($type) {
650
+            case 'admin':
651
+                $source = self::$adminForms;
652
+                break;
653
+            case 'personal':
654
+                $source = self::$personalForms;
655
+                break;
656
+            default:
657
+                return [];
658
+        }
659
+        foreach ($source as $form) {
660
+            $forms[] = include $form;
661
+        }
662
+        return $forms;
663
+    }
664
+
665
+    /**
666
+     * register an admin form to be shown
667
+     *
668
+     * @param string $app
669
+     * @param string $page
670
+     */
671
+    public static function registerAdmin(string $app, string $page) {
672
+        self::$adminForms[] = $app . '/' . $page . '.php';
673
+    }
674
+
675
+    /**
676
+     * register a personal form to be shown
677
+     * @param string $app
678
+     * @param string $page
679
+     */
680
+    public static function registerPersonal(string $app, string $page) {
681
+        self::$personalForms[] = $app . '/' . $page . '.php';
682
+    }
683
+
684
+    /**
685
+     * @param array $entry
686
+     * @deprecated 20.0.0 Please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface
687
+     */
688
+    public static function registerLogIn(array $entry) {
689
+        \OC::$server->getLogger()->debug('OC_App::registerLogIn() is deprecated, please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface');
690
+        self::$altLogin[] = $entry;
691
+    }
692
+
693
+    /**
694
+     * @return array
695
+     */
696
+    public static function getAlternativeLogIns(): array {
697
+        /** @var Coordinator $bootstrapCoordinator */
698
+        $bootstrapCoordinator = \OC::$server->query(Coordinator::class);
699
+
700
+        foreach ($bootstrapCoordinator->getRegistrationContext()->getAlternativeLogins() as $registration) {
701
+            if (!in_array(IAlternativeLogin::class, class_implements($registration['class']), true)) {
702
+                \OC::$server->getLogger()->error('Alternative login option {option} does not implement {interface} and is therefore ignored.', [
703
+                    'option' => $registration['class'],
704
+                    'interface' => IAlternativeLogin::class,
705
+                    'app' => $registration['app'],
706
+                ]);
707
+                continue;
708
+            }
709
+
710
+            try {
711
+                /** @var IAlternativeLogin $provider */
712
+                $provider = \OC::$server->query($registration['class']);
713
+            } catch (QueryException $e) {
714
+                \OC::$server->getLogger()->logException($e, [
715
+                    'message' => 'Alternative login option {option} can not be initialised.',
716
+                    'option' => $registration['class'],
717
+                    'app' => $registration['app'],
718
+                ]);
719
+            }
720
+
721
+            try {
722
+                $provider->load();
723
+
724
+                self::$altLogin[] = [
725
+                    'name' => $provider->getLabel(),
726
+                    'href' => $provider->getLink(),
727
+                    'style' => $provider->getClass(),
728
+                ];
729
+            } catch (Throwable $e) {
730
+                \OC::$server->getLogger()->logException($e, [
731
+                    'message' => 'Alternative login option {option} had an error while loading.',
732
+                    'option' => $registration['class'],
733
+                    'app' => $registration['app'],
734
+                ]);
735
+            }
736
+        }
737
+
738
+        return self::$altLogin;
739
+    }
740
+
741
+    /**
742
+     * get a list of all apps in the apps folder
743
+     *
744
+     * @return string[] an array of app names (string IDs)
745
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
746
+     */
747
+    public static function getAllApps(): array {
748
+        $apps = [];
749
+
750
+        foreach (OC::$APPSROOTS as $apps_dir) {
751
+            if (!is_readable($apps_dir['path'])) {
752
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
753
+                continue;
754
+            }
755
+            $dh = opendir($apps_dir['path']);
756
+
757
+            if (is_resource($dh)) {
758
+                while (($file = readdir($dh)) !== false) {
759
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
760
+                        $apps[] = $file;
761
+                    }
762
+                }
763
+            }
764
+        }
765
+
766
+        $apps = array_unique($apps);
767
+
768
+        return $apps;
769
+    }
770
+
771
+    /**
772
+     * List all apps, this is used in apps.php
773
+     *
774
+     * @return array
775
+     */
776
+    public function listAllApps(): array {
777
+        $installedApps = OC_App::getAllApps();
778
+
779
+        $appManager = \OC::$server->getAppManager();
780
+        //we don't want to show configuration for these
781
+        $blacklist = $appManager->getAlwaysEnabledApps();
782
+        $appList = [];
783
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
784
+        $urlGenerator = \OC::$server->getURLGenerator();
785
+        /** @var \OCP\Support\Subscription\IRegistry $subscriptionRegistry */
786
+        $subscriptionRegistry = \OC::$server->query(\OCP\Support\Subscription\IRegistry::class);
787
+        $supportedApps = $subscriptionRegistry->delegateGetSupportedApps();
788
+
789
+        foreach ($installedApps as $app) {
790
+            if (array_search($app, $blacklist) === false) {
791
+                $info = OC_App::getAppInfo($app, false, $langCode);
792
+                if (!is_array($info)) {
793
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
794
+                    continue;
795
+                }
796
+
797
+                if (!isset($info['name'])) {
798
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
799
+                    continue;
800
+                }
801
+
802
+                $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
803
+                $info['groups'] = null;
804
+                if ($enabled === 'yes') {
805
+                    $active = true;
806
+                } elseif ($enabled === 'no') {
807
+                    $active = false;
808
+                } else {
809
+                    $active = true;
810
+                    $info['groups'] = $enabled;
811
+                }
812
+
813
+                $info['active'] = $active;
814
+
815
+                if ($appManager->isShipped($app)) {
816
+                    $info['internal'] = true;
817
+                    $info['level'] = self::officialApp;
818
+                    $info['removable'] = false;
819
+                } else {
820
+                    $info['internal'] = false;
821
+                    $info['removable'] = true;
822
+                }
823
+
824
+                if (in_array($app, $supportedApps)) {
825
+                    $info['level'] = self::supportedApp;
826
+                }
827
+
828
+                $appPath = self::getAppPath($app);
829
+                if ($appPath !== false) {
830
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
831
+                    if (file_exists($appIcon)) {
832
+                        $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
833
+                        $info['previewAsIcon'] = true;
834
+                    } else {
835
+                        $appIcon = $appPath . '/img/app.svg';
836
+                        if (file_exists($appIcon)) {
837
+                            $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
838
+                            $info['previewAsIcon'] = true;
839
+                        }
840
+                    }
841
+                }
842
+                // fix documentation
843
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
844
+                    foreach ($info['documentation'] as $key => $url) {
845
+                        // If it is not an absolute URL we assume it is a key
846
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
847
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
848
+                            $url = $urlGenerator->linkToDocs($url);
849
+                        }
850
+
851
+                        $info['documentation'][$key] = $url;
852
+                    }
853
+                }
854
+
855
+                $info['version'] = OC_App::getAppVersion($app);
856
+                $appList[] = $info;
857
+            }
858
+        }
859
+
860
+        return $appList;
861
+    }
862
+
863
+    public static function shouldUpgrade(string $app): bool {
864
+        $versions = self::getAppVersions();
865
+        $currentVersion = OC_App::getAppVersion($app);
866
+        if ($currentVersion && isset($versions[$app])) {
867
+            $installedVersion = $versions[$app];
868
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
869
+                return true;
870
+            }
871
+        }
872
+        return false;
873
+    }
874
+
875
+    /**
876
+     * Adjust the number of version parts of $version1 to match
877
+     * the number of version parts of $version2.
878
+     *
879
+     * @param string $version1 version to adjust
880
+     * @param string $version2 version to take the number of parts from
881
+     * @return string shortened $version1
882
+     */
883
+    private static function adjustVersionParts(string $version1, string $version2): string {
884
+        $version1 = explode('.', $version1);
885
+        $version2 = explode('.', $version2);
886
+        // reduce $version1 to match the number of parts in $version2
887
+        while (count($version1) > count($version2)) {
888
+            array_pop($version1);
889
+        }
890
+        // if $version1 does not have enough parts, add some
891
+        while (count($version1) < count($version2)) {
892
+            $version1[] = '0';
893
+        }
894
+        return implode('.', $version1);
895
+    }
896
+
897
+    /**
898
+     * Check whether the current ownCloud version matches the given
899
+     * application's version requirements.
900
+     *
901
+     * The comparison is made based on the number of parts that the
902
+     * app info version has. For example for ownCloud 6.0.3 if the
903
+     * app info version is expecting version 6.0, the comparison is
904
+     * made on the first two parts of the ownCloud version.
905
+     * This means that it's possible to specify "requiremin" => 6
906
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
907
+     *
908
+     * @param string $ocVersion ownCloud version to check against
909
+     * @param array $appInfo app info (from xml)
910
+     *
911
+     * @return boolean true if compatible, otherwise false
912
+     */
913
+    public static function isAppCompatible(string $ocVersion, array $appInfo, bool $ignoreMax = false): bool {
914
+        $requireMin = '';
915
+        $requireMax = '';
916
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
917
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
918
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
919
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
920
+        } elseif (isset($appInfo['requiremin'])) {
921
+            $requireMin = $appInfo['requiremin'];
922
+        } elseif (isset($appInfo['require'])) {
923
+            $requireMin = $appInfo['require'];
924
+        }
925
+
926
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
927
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
928
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
929
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
930
+        } elseif (isset($appInfo['requiremax'])) {
931
+            $requireMax = $appInfo['requiremax'];
932
+        }
933
+
934
+        if (!empty($requireMin)
935
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
936
+        ) {
937
+            return false;
938
+        }
939
+
940
+        if (!$ignoreMax && !empty($requireMax)
941
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
942
+        ) {
943
+            return false;
944
+        }
945
+
946
+        return true;
947
+    }
948
+
949
+    /**
950
+     * get the installed version of all apps
951
+     */
952
+    public static function getAppVersions() {
953
+        static $versions;
954
+
955
+        if (!$versions) {
956
+            $appConfig = \OC::$server->getAppConfig();
957
+            $versions = $appConfig->getValues(false, 'installed_version');
958
+        }
959
+        return $versions;
960
+    }
961
+
962
+    /**
963
+     * update the database for the app and call the update script
964
+     *
965
+     * @param string $appId
966
+     * @return bool
967
+     */
968
+    public static function updateApp(string $appId): bool {
969
+        $appPath = self::getAppPath($appId);
970
+        if ($appPath === false) {
971
+            return false;
972
+        }
973
+
974
+        \OC::$server->getAppManager()->clearAppsCache();
975
+        $appData = self::getAppInfo($appId);
976
+
977
+        $ignoreMaxApps = \OC::$server->getConfig()->getSystemValue('app_install_overwrite', []);
978
+        $ignoreMax = in_array($appId, $ignoreMaxApps, true);
979
+        \OC_App::checkAppDependencies(
980
+            \OC::$server->getConfig(),
981
+            \OC::$server->getL10N('core'),
982
+            $appData,
983
+            $ignoreMax
984
+        );
985
+
986
+        self::registerAutoloading($appId, $appPath, true);
987
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
988
+
989
+        if (file_exists($appPath . '/appinfo/database.xml')) {
990
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
991
+        } else {
992
+            $ms = new MigrationService($appId, \OC::$server->get(\OC\DB\Connection::class));
993
+            $ms->migrate();
994
+        }
995
+
996
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
997
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
998
+        // update appversion in app manager
999
+        \OC::$server->getAppManager()->clearAppsCache();
1000
+        \OC::$server->getAppManager()->getAppVersion($appId, false);
1001
+
1002
+        self::setupBackgroundJobs($appData['background-jobs']);
1003
+
1004
+        //set remote/public handlers
1005
+        if (array_key_exists('ocsid', $appData)) {
1006
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1007
+        } elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1008
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1009
+        }
1010
+        foreach ($appData['remote'] as $name => $path) {
1011
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1012
+        }
1013
+        foreach ($appData['public'] as $name => $path) {
1014
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1015
+        }
1016
+
1017
+        self::setAppTypes($appId);
1018
+
1019
+        $version = \OC_App::getAppVersion($appId);
1020
+        \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
1021
+
1022
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1023
+            ManagerEvent::EVENT_APP_UPDATE, $appId
1024
+        ));
1025
+
1026
+        return true;
1027
+    }
1028
+
1029
+    /**
1030
+     * @param string $appId
1031
+     * @param string[] $steps
1032
+     * @throws \OC\NeedsUpdateException
1033
+     */
1034
+    public static function executeRepairSteps(string $appId, array $steps) {
1035
+        if (empty($steps)) {
1036
+            return;
1037
+        }
1038
+        // load the app
1039
+        self::loadApp($appId);
1040
+
1041
+        $dispatcher = OC::$server->getEventDispatcher();
1042
+
1043
+        // load the steps
1044
+        $r = new Repair([], $dispatcher);
1045
+        foreach ($steps as $step) {
1046
+            try {
1047
+                $r->addStep($step);
1048
+            } catch (Exception $ex) {
1049
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1050
+                \OC::$server->getLogger()->logException($ex);
1051
+            }
1052
+        }
1053
+        // run the steps
1054
+        $r->run();
1055
+    }
1056
+
1057
+    public static function setupBackgroundJobs(array $jobs) {
1058
+        $queue = \OC::$server->getJobList();
1059
+        foreach ($jobs as $job) {
1060
+            $queue->add($job);
1061
+        }
1062
+    }
1063
+
1064
+    /**
1065
+     * @param string $appId
1066
+     * @param string[] $steps
1067
+     */
1068
+    private static function setupLiveMigrations(string $appId, array $steps) {
1069
+        $queue = \OC::$server->getJobList();
1070
+        foreach ($steps as $step) {
1071
+            $queue->add('OC\Migration\BackgroundRepair', [
1072
+                'app' => $appId,
1073
+                'step' => $step]);
1074
+        }
1075
+    }
1076
+
1077
+    /**
1078
+     * @param string $appId
1079
+     * @return \OC\Files\View|false
1080
+     */
1081
+    public static function getStorage(string $appId) {
1082
+        if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1083
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1084
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1085
+                if (!$view->file_exists($appId)) {
1086
+                    $view->mkdir($appId);
1087
+                }
1088
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1089
+            } else {
1090
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
1091
+                return false;
1092
+            }
1093
+        } else {
1094
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
1095
+            return false;
1096
+        }
1097
+    }
1098
+
1099
+    protected static function findBestL10NOption(array $options, string $lang): string {
1100
+        // only a single option
1101
+        if (isset($options['@value'])) {
1102
+            return $options['@value'];
1103
+        }
1104
+
1105
+        $fallback = $similarLangFallback = $englishFallback = false;
1106
+
1107
+        $lang = strtolower($lang);
1108
+        $similarLang = $lang;
1109
+        if (strpos($similarLang, '_')) {
1110
+            // For "de_DE" we want to find "de" and the other way around
1111
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1112
+        }
1113
+
1114
+        foreach ($options as $option) {
1115
+            if (is_array($option)) {
1116
+                if ($fallback === false) {
1117
+                    $fallback = $option['@value'];
1118
+                }
1119
+
1120
+                if (!isset($option['@attributes']['lang'])) {
1121
+                    continue;
1122
+                }
1123
+
1124
+                $attributeLang = strtolower($option['@attributes']['lang']);
1125
+                if ($attributeLang === $lang) {
1126
+                    return $option['@value'];
1127
+                }
1128
+
1129
+                if ($attributeLang === $similarLang) {
1130
+                    $similarLangFallback = $option['@value'];
1131
+                } elseif (strpos($attributeLang, $similarLang . '_') === 0) {
1132
+                    if ($similarLangFallback === false) {
1133
+                        $similarLangFallback = $option['@value'];
1134
+                    }
1135
+                }
1136
+            } else {
1137
+                $englishFallback = $option;
1138
+            }
1139
+        }
1140
+
1141
+        if ($similarLangFallback !== false) {
1142
+            return $similarLangFallback;
1143
+        } elseif ($englishFallback !== false) {
1144
+            return $englishFallback;
1145
+        }
1146
+        return (string) $fallback;
1147
+    }
1148
+
1149
+    /**
1150
+     * parses the app data array and enhanced the 'description' value
1151
+     *
1152
+     * @param array $data the app data
1153
+     * @param string $lang
1154
+     * @return array improved app data
1155
+     */
1156
+    public static function parseAppInfo(array $data, $lang = null): array {
1157
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1158
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1159
+        }
1160
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1161
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1162
+        }
1163
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1164
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1165
+        } elseif (isset($data['description']) && is_string($data['description'])) {
1166
+            $data['description'] = trim($data['description']);
1167
+        } else {
1168
+            $data['description'] = '';
1169
+        }
1170
+
1171
+        return $data;
1172
+    }
1173
+
1174
+    /**
1175
+     * @param \OCP\IConfig $config
1176
+     * @param \OCP\IL10N $l
1177
+     * @param array $info
1178
+     * @throws \Exception
1179
+     */
1180
+    public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info, bool $ignoreMax) {
1181
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1182
+        $missing = $dependencyAnalyzer->analyze($info, $ignoreMax);
1183
+        if (!empty($missing)) {
1184
+            $missingMsg = implode(PHP_EOL, $missing);
1185
+            throw new \Exception(
1186
+                $l->t('App "%1$s" cannot be installed because the following dependencies are not fulfilled: %2$s',
1187
+                    [$info['name'], $missingMsg]
1188
+                )
1189
+            );
1190
+        }
1191
+    }
1192 1192
 }
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 		$coordinator = \OC::$server->query(Coordinator::class);
163 163
 		$isBootable = $coordinator->isBootable($app);
164 164
 
165
-		$hasAppPhpFile = is_file($appPath . '/appinfo/app.php');
165
+		$hasAppPhpFile = is_file($appPath.'/appinfo/app.php');
166 166
 
167 167
 		if ($isBootable && $hasAppPhpFile) {
168 168
 			\OC::$server->getLogger()->error('/appinfo/app.php is not loaded when \OCP\AppFramework\Bootstrap\IBootstrap on the application class is used. Migrate everything from app.php to the Application class.', [
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 			\OC::$server->getLogger()->debug('/appinfo/app.php is deprecated, use \OCP\AppFramework\Bootstrap\IBootstrap on the application class instead.', [
173 173
 				'app' => $app,
174 174
 			]);
175
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
175
+			\OC::$server->getEventLogger()->start('load_app_'.$app, 'Load app: '.$app);
176 176
 			try {
177 177
 				self::requireAppFile($app);
178 178
 			} catch (Throwable $ex) {
@@ -181,18 +181,18 @@  discard block
 block discarded – undo
181 181
 				}
182 182
 				if (!\OC::$server->getAppManager()->isShipped($app) && !self::isType($app, ['authentication'])) {
183 183
 					\OC::$server->getLogger()->logException($ex, [
184
-						'message' => "App $app threw an error during app.php load and will be disabled: " . $ex->getMessage(),
184
+						'message' => "App $app threw an error during app.php load and will be disabled: ".$ex->getMessage(),
185 185
 					]);
186 186
 
187 187
 					// Only disable apps which are not shipped and that are not authentication apps
188 188
 					\OC::$server->getAppManager()->disableApp($app, true);
189 189
 				} else {
190 190
 					\OC::$server->getLogger()->logException($ex, [
191
-						'message' => "App $app threw an error during app.php load: " . $ex->getMessage(),
191
+						'message' => "App $app threw an error during app.php load: ".$ex->getMessage(),
192 192
 					]);
193 193
 				}
194 194
 			}
195
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
195
+			\OC::$server->getEventLogger()->end('load_app_'.$app);
196 196
 		}
197 197
 		$coordinator->bootApp($app);
198 198
 
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 	 * @param bool $force
260 260
 	 */
261 261
 	public static function registerAutoloading(string $app, string $path, bool $force = false) {
262
-		$key = $app . '-' . $path;
262
+		$key = $app.'-'.$path;
263 263
 		if (!$force && isset(self::$alreadyRegistered[$key])) {
264 264
 			return;
265 265
 		}
@@ -270,17 +270,17 @@  discard block
 block discarded – undo
270 270
 		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
271 271
 		\OC::$server->registerNamespace($app, $appNamespace);
272 272
 
273
-		if (file_exists($path . '/composer/autoload.php')) {
274
-			require_once $path . '/composer/autoload.php';
273
+		if (file_exists($path.'/composer/autoload.php')) {
274
+			require_once $path.'/composer/autoload.php';
275 275
 		} else {
276
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
276
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\', $path.'/lib/', true);
277 277
 			// Register on legacy autoloader
278 278
 			\OC::$loader->addValidRoot($path);
279 279
 		}
280 280
 
281 281
 		// Register Test namespace only when testing
282 282
 		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
283
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
283
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\Tests\\', $path.'/tests/', true);
284 284
 		}
285 285
 	}
286 286
 
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
 	 */
293 293
 	private static function requireAppFile(string $app) {
294 294
 		// encapsulated here to avoid variable scope conflicts
295
-		require_once $app . '/appinfo/app.php';
295
+		require_once $app.'/appinfo/app.php';
296 296
 	}
297 297
 
298 298
 	/**
@@ -385,8 +385,8 @@  discard block
 block discarded – undo
385 385
 		} else {
386 386
 			$apps = $appManager->getEnabledAppsForUser($user);
387 387
 		}
388
-		$apps = array_filter($apps, function ($app) {
389
-			return $app !== 'files';//we add this manually
388
+		$apps = array_filter($apps, function($app) {
389
+			return $app !== 'files'; //we add this manually
390 390
 		});
391 391
 		sort($apps);
392 392
 		array_unshift($apps, 'files');
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
 
487 487
 		$possibleApps = [];
488 488
 		foreach (OC::$APPSROOTS as $dir) {
489
-			if (file_exists($dir['path'] . '/' . $appId)) {
489
+			if (file_exists($dir['path'].'/'.$appId)) {
490 490
 				$possibleApps[] = $dir;
491 491
 			}
492 492
 		}
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
 		} else {
501 501
 			$versionToLoad = [];
502 502
 			foreach ($possibleApps as $possibleApp) {
503
-				$version = self::getAppVersionByPath($possibleApp['path'] . '/' . $appId);
503
+				$version = self::getAppVersionByPath($possibleApp['path'].'/'.$appId);
504 504
 				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
505 505
 					$versionToLoad = [
506 506
 						'dir' => $possibleApp,
@@ -530,7 +530,7 @@  discard block
 block discarded – undo
530 530
 		}
531 531
 
532 532
 		if (($dir = self::findAppInDirectories($appId)) != false) {
533
-			return $dir['path'] . '/' . $appId;
533
+			return $dir['path'].'/'.$appId;
534 534
 		}
535 535
 		return false;
536 536
 	}
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 	 */
546 546
 	public static function getAppWebPath(string $appId) {
547 547
 		if (($dir = self::findAppInDirectories($appId)) != false) {
548
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
548
+			return OC::$WEBROOT.$dir['url'].'/'.$appId;
549 549
 		}
550 550
 		return false;
551 551
 	}
@@ -569,7 +569,7 @@  discard block
 block discarded – undo
569 569
 	 * @return string
570 570
 	 */
571 571
 	public static function getAppVersionByPath(string $path): string {
572
-		$infoFile = $path . '/appinfo/info.xml';
572
+		$infoFile = $path.'/appinfo/info.xml';
573 573
 		$appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
574 574
 		return isset($appData['version']) ? $appData['version'] : '';
575 575
 	}
@@ -669,7 +669,7 @@  discard block
 block discarded – undo
669 669
 	 * @param string $page
670 670
 	 */
671 671
 	public static function registerAdmin(string $app, string $page) {
672
-		self::$adminForms[] = $app . '/' . $page . '.php';
672
+		self::$adminForms[] = $app.'/'.$page.'.php';
673 673
 	}
674 674
 
675 675
 	/**
@@ -678,7 +678,7 @@  discard block
 block discarded – undo
678 678
 	 * @param string $page
679 679
 	 */
680 680
 	public static function registerPersonal(string $app, string $page) {
681
-		self::$personalForms[] = $app . '/' . $page . '.php';
681
+		self::$personalForms[] = $app.'/'.$page.'.php';
682 682
 	}
683 683
 
684 684
 	/**
@@ -749,14 +749,14 @@  discard block
 block discarded – undo
749 749
 
750 750
 		foreach (OC::$APPSROOTS as $apps_dir) {
751 751
 			if (!is_readable($apps_dir['path'])) {
752
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
752
+				\OCP\Util::writeLog('core', 'unable to read app folder : '.$apps_dir['path'], ILogger::WARN);
753 753
 				continue;
754 754
 			}
755 755
 			$dh = opendir($apps_dir['path']);
756 756
 
757 757
 			if (is_resource($dh)) {
758 758
 				while (($file = readdir($dh)) !== false) {
759
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
759
+					if ($file[0] != '.' and is_dir($apps_dir['path'].'/'.$file) and is_file($apps_dir['path'].'/'.$file.'/appinfo/info.xml')) {
760 760
 						$apps[] = $file;
761 761
 					}
762 762
 				}
@@ -790,12 +790,12 @@  discard block
 block discarded – undo
790 790
 			if (array_search($app, $blacklist) === false) {
791 791
 				$info = OC_App::getAppInfo($app, false, $langCode);
792 792
 				if (!is_array($info)) {
793
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
793
+					\OCP\Util::writeLog('core', 'Could not read app info file for app "'.$app.'"', ILogger::ERROR);
794 794
 					continue;
795 795
 				}
796 796
 
797 797
 				if (!isset($info['name'])) {
798
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
798
+					\OCP\Util::writeLog('core', 'App id "'.$app.'" has no name in appinfo', ILogger::ERROR);
799 799
 					continue;
800 800
 				}
801 801
 
@@ -827,12 +827,12 @@  discard block
 block discarded – undo
827 827
 
828 828
 				$appPath = self::getAppPath($app);
829 829
 				if ($appPath !== false) {
830
-					$appIcon = $appPath . '/img/' . $app . '.svg';
830
+					$appIcon = $appPath.'/img/'.$app.'.svg';
831 831
 					if (file_exists($appIcon)) {
832
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
832
+						$info['preview'] = $urlGenerator->imagePath($app, $app.'.svg');
833 833
 						$info['previewAsIcon'] = true;
834 834
 					} else {
835
-						$appIcon = $appPath . '/img/app.svg';
835
+						$appIcon = $appPath.'/img/app.svg';
836 836
 						if (file_exists($appIcon)) {
837 837
 							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
838 838
 							$info['previewAsIcon'] = true;
@@ -986,8 +986,8 @@  discard block
 block discarded – undo
986 986
 		self::registerAutoloading($appId, $appPath, true);
987 987
 		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
988 988
 
989
-		if (file_exists($appPath . '/appinfo/database.xml')) {
990
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
989
+		if (file_exists($appPath.'/appinfo/database.xml')) {
990
+			OC_DB::updateDbFromStructure($appPath.'/appinfo/database.xml');
991 991
 		} else {
992 992
 			$ms = new MigrationService($appId, \OC::$server->get(\OC\DB\Connection::class));
993 993
 			$ms->migrate();
@@ -1008,10 +1008,10 @@  discard block
 block discarded – undo
1008 1008
 			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1009 1009
 		}
1010 1010
 		foreach ($appData['remote'] as $name => $path) {
1011
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1011
+			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $appId.'/'.$path);
1012 1012
 		}
1013 1013
 		foreach ($appData['public'] as $name => $path) {
1014
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1014
+			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $appId.'/'.$path);
1015 1015
 		}
1016 1016
 
1017 1017
 		self::setAppTypes($appId);
@@ -1081,17 +1081,17 @@  discard block
 block discarded – undo
1081 1081
 	public static function getStorage(string $appId) {
1082 1082
 		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1083 1083
 			if (\OC::$server->getUserSession()->isLoggedIn()) {
1084
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1084
+				$view = new \OC\Files\View('/'.OC_User::getUser());
1085 1085
 				if (!$view->file_exists($appId)) {
1086 1086
 					$view->mkdir($appId);
1087 1087
 				}
1088
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1088
+				return new \OC\Files\View('/'.OC_User::getUser().'/'.$appId);
1089 1089
 			} else {
1090
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
1090
+				\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.', user not logged in', ILogger::ERROR);
1091 1091
 				return false;
1092 1092
 			}
1093 1093
 		} else {
1094
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
1094
+			\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.' not enabled', ILogger::ERROR);
1095 1095
 			return false;
1096 1096
 		}
1097 1097
 	}
@@ -1128,7 +1128,7 @@  discard block
 block discarded – undo
1128 1128
 
1129 1129
 				if ($attributeLang === $similarLang) {
1130 1130
 					$similarLangFallback = $option['@value'];
1131
-				} elseif (strpos($attributeLang, $similarLang . '_') === 0) {
1131
+				} elseif (strpos($attributeLang, $similarLang.'_') === 0) {
1132 1132
 					if ($similarLangFallback === false) {
1133 1133
 						$similarLangFallback = $option['@value'];
1134 1134
 					}
Please login to merge, or discard this patch.
lib/private/legacy/OC_DB.php 1 patch
Indentation   +199 added lines, -199 removed lines patch added patch discarded remove patch
@@ -38,203 +38,203 @@
 block discarded – undo
38 38
  */
39 39
 class OC_DB {
40 40
 
41
-	/**
42
-	 * get MDB2 schema manager
43
-	 *
44
-	 * @return \OC\DB\MDB2SchemaManager
45
-	 */
46
-	private static function getMDB2SchemaManager() {
47
-		return new \OC\DB\MDB2SchemaManager(\OC::$server->get(\OC\DB\Connection::class));
48
-	}
49
-
50
-	/**
51
-	 * Prepare a SQL query
52
-	 * @param string $query Query string
53
-	 * @param int|null $limit
54
-	 * @param int|null $offset
55
-	 * @param bool|null $isManipulation
56
-	 * @throws \OC\DatabaseException
57
-	 * @return OC_DB_StatementWrapper prepared SQL query
58
-	 * @deprecated 21.0.0 Please use \OCP\IDBConnection::getQueryBuilder() instead
59
-	 *
60
-	 * SQL query via Doctrine prepare(), needs to be execute()'d!
61
-	 */
62
-	public static function prepare($query , $limit = null, $offset = null, $isManipulation = null) {
63
-		$connection = \OC::$server->getDatabaseConnection();
64
-
65
-		if ($isManipulation === null) {
66
-			//try to guess, so we return the number of rows on manipulations
67
-			$isManipulation = self::isManipulation($query);
68
-		}
69
-
70
-		// return the result
71
-		try {
72
-			$result = $connection->prepare($query, $limit, $offset);
73
-		} catch (\Doctrine\DBAL\Exception $e) {
74
-			throw new \OC\DatabaseException($e->getMessage());
75
-		}
76
-		// differentiate between query and manipulation
77
-		return new OC_DB_StatementWrapper($result, $isManipulation);
78
-	}
79
-
80
-	/**
81
-	 * tries to guess the type of statement based on the first 10 characters
82
-	 * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
83
-	 *
84
-	 * @param string $sql
85
-	 * @return bool
86
-	 */
87
-	public static function isManipulation($sql) {
88
-		$sql = trim($sql);
89
-		$selectOccurrence = stripos($sql, 'SELECT');
90
-		if ($selectOccurrence === 0) {
91
-			return false;
92
-		}
93
-		$insertOccurrence = stripos($sql, 'INSERT');
94
-		if ($insertOccurrence === 0) {
95
-			return true;
96
-		}
97
-		$updateOccurrence = stripos($sql, 'UPDATE');
98
-		if ($updateOccurrence === 0) {
99
-			return true;
100
-		}
101
-		$deleteOccurrence = stripos($sql, 'DELETE');
102
-		if ($deleteOccurrence === 0) {
103
-			return true;
104
-		}
105
-
106
-		// This is triggered with "SHOW VERSION" and some more, so until we made a list, we keep this out.
107
-		// \OC::$server->getLogger()->logException(new \Exception('Can not detect if query is manipulating: ' . $sql));
108
-
109
-		return false;
110
-	}
111
-
112
-	/**
113
-	 * execute a prepared statement, on error write log and throw exception
114
-	 * @param mixed $stmt OC_DB_StatementWrapper,
115
-	 *					  an array with 'sql' and optionally 'limit' and 'offset' keys
116
-	 *					.. or a simple sql query string
117
-	 * @param array $parameters
118
-	 * @return OC_DB_StatementWrapper
119
-	 * @throws \OC\DatabaseException
120
-	 * @deprecated 21.0.0 Please use \OCP\IDBConnection::getQueryBuilder() instead
121
-	 */
122
-	public static function executeAudited($stmt, array $parameters = []) {
123
-		if (is_string($stmt)) {
124
-			// convert to an array with 'sql'
125
-			if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
126
-				// TODO try to convert LIMIT OFFSET notation to parameters
127
-				$message = 'LIMIT and OFFSET are forbidden for portability reasons,'
128
-						 . ' pass an array with \'limit\' and \'offset\' instead';
129
-				throw new \OC\DatabaseException($message);
130
-			}
131
-			$stmt = ['sql' => $stmt, 'limit' => null, 'offset' => null];
132
-		}
133
-		if (is_array($stmt)) {
134
-			// convert to prepared statement
135
-			if (! array_key_exists('sql', $stmt)) {
136
-				$message = 'statement array must at least contain key \'sql\'';
137
-				throw new \OC\DatabaseException($message);
138
-			}
139
-			if (! array_key_exists('limit', $stmt)) {
140
-				$stmt['limit'] = null;
141
-			}
142
-			if (! array_key_exists('limit', $stmt)) {
143
-				$stmt['offset'] = null;
144
-			}
145
-			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
146
-		}
147
-		self::raiseExceptionOnError($stmt, 'Could not prepare statement');
148
-		if ($stmt instanceof OC_DB_StatementWrapper) {
149
-			$result = $stmt->execute($parameters);
150
-			self::raiseExceptionOnError($result, 'Could not execute statement');
151
-		} else {
152
-			if (is_object($stmt)) {
153
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
154
-			} else {
155
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
156
-			}
157
-			throw new \OC\DatabaseException($message);
158
-		}
159
-		return $result;
160
-	}
161
-
162
-	/**
163
-	 * Creates tables from XML file
164
-	 * @param string $file file to read structure from
165
-	 * @return bool
166
-	 *
167
-	 * TODO: write more documentation
168
-	 */
169
-	public static function createDbFromStructure($file) {
170
-		$schemaManager = self::getMDB2SchemaManager();
171
-		return $schemaManager->createDbFromStructure($file);
172
-	}
173
-
174
-	/**
175
-	 * update the database schema
176
-	 * @param string $file file to read structure from
177
-	 * @throws Exception
178
-	 * @return string|boolean
179
-	 * @suppress PhanDeprecatedFunction
180
-	 */
181
-	public static function updateDbFromStructure($file) {
182
-		$schemaManager = self::getMDB2SchemaManager();
183
-		try {
184
-			$result = $schemaManager->updateDbFromStructure($file);
185
-		} catch (Exception $e) {
186
-			\OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', ILogger::FATAL);
187
-			throw $e;
188
-		}
189
-		return $result;
190
-	}
191
-
192
-	/**
193
-	 * remove all tables defined in a database structure xml file
194
-	 * @param string $file the xml file describing the tables
195
-	 */
196
-	public static function removeDBStructure($file) {
197
-		$schemaManager = self::getMDB2SchemaManager();
198
-		$schemaManager->removeDBStructure($file);
199
-	}
200
-
201
-	/**
202
-	 * check if a result is an error and throws an exception, works with \Doctrine\DBAL\Exception
203
-	 * @param mixed $result
204
-	 * @param string $message
205
-	 * @return void
206
-	 * @throws \OC\DatabaseException
207
-	 */
208
-	public static function raiseExceptionOnError($result, $message = null) {
209
-		if ($result === false) {
210
-			if ($message === null) {
211
-				$message = self::getErrorMessage();
212
-			} else {
213
-				$message .= ', Root cause:' . self::getErrorMessage();
214
-			}
215
-			throw new \OC\DatabaseException($message);
216
-		}
217
-	}
218
-
219
-	/**
220
-	 * returns the error code and message as a string for logging
221
-	 * works with DoctrineException
222
-	 * @return string
223
-	 */
224
-	public static function getErrorMessage() {
225
-		$connection = \OC::$server->getDatabaseConnection();
226
-		return $connection->getError();
227
-	}
228
-
229
-	/**
230
-	 * Checks if a table exists in the database - the database prefix will be prepended
231
-	 *
232
-	 * @param string $table
233
-	 * @return bool
234
-	 * @throws \OC\DatabaseException
235
-	 */
236
-	public static function tableExists($table) {
237
-		$connection = \OC::$server->getDatabaseConnection();
238
-		return $connection->tableExists($table);
239
-	}
41
+    /**
42
+     * get MDB2 schema manager
43
+     *
44
+     * @return \OC\DB\MDB2SchemaManager
45
+     */
46
+    private static function getMDB2SchemaManager() {
47
+        return new \OC\DB\MDB2SchemaManager(\OC::$server->get(\OC\DB\Connection::class));
48
+    }
49
+
50
+    /**
51
+     * Prepare a SQL query
52
+     * @param string $query Query string
53
+     * @param int|null $limit
54
+     * @param int|null $offset
55
+     * @param bool|null $isManipulation
56
+     * @throws \OC\DatabaseException
57
+     * @return OC_DB_StatementWrapper prepared SQL query
58
+     * @deprecated 21.0.0 Please use \OCP\IDBConnection::getQueryBuilder() instead
59
+     *
60
+     * SQL query via Doctrine prepare(), needs to be execute()'d!
61
+     */
62
+    public static function prepare($query , $limit = null, $offset = null, $isManipulation = null) {
63
+        $connection = \OC::$server->getDatabaseConnection();
64
+
65
+        if ($isManipulation === null) {
66
+            //try to guess, so we return the number of rows on manipulations
67
+            $isManipulation = self::isManipulation($query);
68
+        }
69
+
70
+        // return the result
71
+        try {
72
+            $result = $connection->prepare($query, $limit, $offset);
73
+        } catch (\Doctrine\DBAL\Exception $e) {
74
+            throw new \OC\DatabaseException($e->getMessage());
75
+        }
76
+        // differentiate between query and manipulation
77
+        return new OC_DB_StatementWrapper($result, $isManipulation);
78
+    }
79
+
80
+    /**
81
+     * tries to guess the type of statement based on the first 10 characters
82
+     * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
83
+     *
84
+     * @param string $sql
85
+     * @return bool
86
+     */
87
+    public static function isManipulation($sql) {
88
+        $sql = trim($sql);
89
+        $selectOccurrence = stripos($sql, 'SELECT');
90
+        if ($selectOccurrence === 0) {
91
+            return false;
92
+        }
93
+        $insertOccurrence = stripos($sql, 'INSERT');
94
+        if ($insertOccurrence === 0) {
95
+            return true;
96
+        }
97
+        $updateOccurrence = stripos($sql, 'UPDATE');
98
+        if ($updateOccurrence === 0) {
99
+            return true;
100
+        }
101
+        $deleteOccurrence = stripos($sql, 'DELETE');
102
+        if ($deleteOccurrence === 0) {
103
+            return true;
104
+        }
105
+
106
+        // This is triggered with "SHOW VERSION" and some more, so until we made a list, we keep this out.
107
+        // \OC::$server->getLogger()->logException(new \Exception('Can not detect if query is manipulating: ' . $sql));
108
+
109
+        return false;
110
+    }
111
+
112
+    /**
113
+     * execute a prepared statement, on error write log and throw exception
114
+     * @param mixed $stmt OC_DB_StatementWrapper,
115
+     *					  an array with 'sql' and optionally 'limit' and 'offset' keys
116
+     *					.. or a simple sql query string
117
+     * @param array $parameters
118
+     * @return OC_DB_StatementWrapper
119
+     * @throws \OC\DatabaseException
120
+     * @deprecated 21.0.0 Please use \OCP\IDBConnection::getQueryBuilder() instead
121
+     */
122
+    public static function executeAudited($stmt, array $parameters = []) {
123
+        if (is_string($stmt)) {
124
+            // convert to an array with 'sql'
125
+            if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
126
+                // TODO try to convert LIMIT OFFSET notation to parameters
127
+                $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
128
+                            . ' pass an array with \'limit\' and \'offset\' instead';
129
+                throw new \OC\DatabaseException($message);
130
+            }
131
+            $stmt = ['sql' => $stmt, 'limit' => null, 'offset' => null];
132
+        }
133
+        if (is_array($stmt)) {
134
+            // convert to prepared statement
135
+            if (! array_key_exists('sql', $stmt)) {
136
+                $message = 'statement array must at least contain key \'sql\'';
137
+                throw new \OC\DatabaseException($message);
138
+            }
139
+            if (! array_key_exists('limit', $stmt)) {
140
+                $stmt['limit'] = null;
141
+            }
142
+            if (! array_key_exists('limit', $stmt)) {
143
+                $stmt['offset'] = null;
144
+            }
145
+            $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
146
+        }
147
+        self::raiseExceptionOnError($stmt, 'Could not prepare statement');
148
+        if ($stmt instanceof OC_DB_StatementWrapper) {
149
+            $result = $stmt->execute($parameters);
150
+            self::raiseExceptionOnError($result, 'Could not execute statement');
151
+        } else {
152
+            if (is_object($stmt)) {
153
+                $message = 'Expected a prepared statement or array got ' . get_class($stmt);
154
+            } else {
155
+                $message = 'Expected a prepared statement or array got ' . gettype($stmt);
156
+            }
157
+            throw new \OC\DatabaseException($message);
158
+        }
159
+        return $result;
160
+    }
161
+
162
+    /**
163
+     * Creates tables from XML file
164
+     * @param string $file file to read structure from
165
+     * @return bool
166
+     *
167
+     * TODO: write more documentation
168
+     */
169
+    public static function createDbFromStructure($file) {
170
+        $schemaManager = self::getMDB2SchemaManager();
171
+        return $schemaManager->createDbFromStructure($file);
172
+    }
173
+
174
+    /**
175
+     * update the database schema
176
+     * @param string $file file to read structure from
177
+     * @throws Exception
178
+     * @return string|boolean
179
+     * @suppress PhanDeprecatedFunction
180
+     */
181
+    public static function updateDbFromStructure($file) {
182
+        $schemaManager = self::getMDB2SchemaManager();
183
+        try {
184
+            $result = $schemaManager->updateDbFromStructure($file);
185
+        } catch (Exception $e) {
186
+            \OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', ILogger::FATAL);
187
+            throw $e;
188
+        }
189
+        return $result;
190
+    }
191
+
192
+    /**
193
+     * remove all tables defined in a database structure xml file
194
+     * @param string $file the xml file describing the tables
195
+     */
196
+    public static function removeDBStructure($file) {
197
+        $schemaManager = self::getMDB2SchemaManager();
198
+        $schemaManager->removeDBStructure($file);
199
+    }
200
+
201
+    /**
202
+     * check if a result is an error and throws an exception, works with \Doctrine\DBAL\Exception
203
+     * @param mixed $result
204
+     * @param string $message
205
+     * @return void
206
+     * @throws \OC\DatabaseException
207
+     */
208
+    public static function raiseExceptionOnError($result, $message = null) {
209
+        if ($result === false) {
210
+            if ($message === null) {
211
+                $message = self::getErrorMessage();
212
+            } else {
213
+                $message .= ', Root cause:' . self::getErrorMessage();
214
+            }
215
+            throw new \OC\DatabaseException($message);
216
+        }
217
+    }
218
+
219
+    /**
220
+     * returns the error code and message as a string for logging
221
+     * works with DoctrineException
222
+     * @return string
223
+     */
224
+    public static function getErrorMessage() {
225
+        $connection = \OC::$server->getDatabaseConnection();
226
+        return $connection->getError();
227
+    }
228
+
229
+    /**
230
+     * Checks if a table exists in the database - the database prefix will be prepended
231
+     *
232
+     * @param string $table
233
+     * @return bool
234
+     * @throws \OC\DatabaseException
235
+     */
236
+    public static function tableExists($table) {
237
+        $connection = \OC::$server->getDatabaseConnection();
238
+        return $connection->tableExists($table);
239
+    }
240 240
 }
Please login to merge, or discard this patch.
lib/private/Setup/PostgreSQL.php 2 patches
Indentation   +131 added lines, -131 removed lines patch added patch discarded remove patch
@@ -34,135 +34,135 @@
 block discarded – undo
34 34
 use OC\DB\QueryBuilder\Literal;
35 35
 
36 36
 class PostgreSQL extends AbstractDatabase {
37
-	public $dbprettyname = 'PostgreSQL';
38
-
39
-	/**
40
-	 * @param string $username
41
-	 * @throws \OC\DatabaseSetupException
42
-	 */
43
-	public function setupDatabase($username) {
44
-		try {
45
-			$connection = $this->connect([
46
-				'dbname' => 'postgres'
47
-			]);
48
-			//check for roles creation rights in postgresql
49
-			$builder = $connection->getQueryBuilder();
50
-			$builder->automaticTablePrefix(false);
51
-			$query = $builder
52
-				->select('rolname')
53
-				->from('pg_roles')
54
-				->where($builder->expr()->eq('rolcreaterole', new Literal('TRUE')))
55
-				->andWhere($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
56
-
57
-			try {
58
-				$result = $query->execute();
59
-				$canCreateRoles = $result->rowCount() > 0;
60
-			} catch (DatabaseException $e) {
61
-				$canCreateRoles = false;
62
-			}
63
-
64
-			if ($canCreateRoles) {
65
-				//use the admin login data for the new database user
66
-
67
-				//add prefix to the postgresql user name to prevent collisions
68
-				$this->dbUser = 'oc_' . strtolower($username);
69
-				//create a new password so we don't need to store the admin config in the config file
70
-				$this->dbPassword = \OC::$server->getSecureRandom()->generate(30, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
71
-
72
-				$this->createDBUser($connection);
73
-			}
74
-
75
-			$this->config->setValues([
76
-				'dbuser' => $this->dbUser,
77
-				'dbpassword' => $this->dbPassword,
78
-			]);
79
-
80
-			//create the database
81
-			$this->createDatabase($connection);
82
-			// the connection to dbname=postgres is not needed anymore
83
-			$connection->close();
84
-		} catch (\Exception $e) {
85
-			$this->logger->logException($e);
86
-			$this->logger->warning('Error trying to connect as "postgres", assuming database is setup and tables need to be created');
87
-			$this->config->setValues([
88
-				'dbuser' => $this->dbUser,
89
-				'dbpassword' => $this->dbPassword,
90
-			]);
91
-		}
92
-
93
-		// connect to the database (dbname=$this->dbname) and check if it needs to be filled
94
-		$this->dbUser = $this->config->getValue('dbuser');
95
-		$this->dbPassword = $this->config->getValue('dbpassword');
96
-		$connection = $this->connect();
97
-		try {
98
-			$connection->connect();
99
-		} catch (\Exception $e) {
100
-			$this->logger->logException($e);
101
-			throw new \OC\DatabaseSetupException($this->trans->t('PostgreSQL username and/or password not valid'),
102
-				$this->trans->t('You need to enter details of an existing account.'), 0, $e);
103
-		}
104
-	}
105
-
106
-	private function createDatabase(Connection $connection) {
107
-		if (!$this->databaseExists($connection)) {
108
-			//The database does not exists... let's create it
109
-			$query = $connection->prepare("CREATE DATABASE " . addslashes($this->dbName) . " OWNER " . addslashes($this->dbUser));
110
-			try {
111
-				$query->execute();
112
-			} catch (DatabaseException $e) {
113
-				$this->logger->error('Error while trying to create database');
114
-				$this->logger->logException($e);
115
-			}
116
-		} else {
117
-			$query = $connection->prepare("REVOKE ALL PRIVILEGES ON DATABASE " . addslashes($this->dbName) . " FROM PUBLIC");
118
-			try {
119
-				$query->execute();
120
-			} catch (DatabaseException $e) {
121
-				$this->logger->error('Error while trying to restrict database permissions');
122
-				$this->logger->logException($e);
123
-			}
124
-		}
125
-	}
126
-
127
-	private function userExists(Connection $connection) {
128
-		$builder = $connection->getQueryBuilder();
129
-		$builder->automaticTablePrefix(false);
130
-		$query = $builder->select('*')
131
-			->from('pg_roles')
132
-			->where($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
133
-		$result = $query->execute();
134
-		return $result->rowCount() > 0;
135
-	}
136
-
137
-	private function databaseExists(Connection $connection) {
138
-		$builder = $connection->getQueryBuilder();
139
-		$builder->automaticTablePrefix(false);
140
-		$query = $builder->select('datname')
141
-			->from('pg_database')
142
-			->where($builder->expr()->eq('datname', $builder->createNamedParameter($this->dbName)));
143
-		$result = $query->execute();
144
-		return $result->rowCount() > 0;
145
-	}
146
-
147
-	private function createDBUser(Connection $connection) {
148
-		$dbUser = $this->dbUser;
149
-		try {
150
-			$i = 1;
151
-			while ($this->userExists($connection)) {
152
-				$i++;
153
-				$this->dbUser = $dbUser . $i;
154
-			}
155
-
156
-			// create the user
157
-			$query = $connection->prepare("CREATE USER " . addslashes($this->dbUser) . " CREATEDB PASSWORD '" . addslashes($this->dbPassword) . "'");
158
-			$query->execute();
159
-			if ($this->databaseExists($connection)) {
160
-				$query = $connection->prepare('GRANT CONNECT ON DATABASE ' . addslashes($this->dbName) . ' TO '.addslashes($this->dbUser));
161
-				$query->execute();
162
-			}
163
-		} catch (DatabaseException $e) {
164
-			$this->logger->error('Error while trying to create database user');
165
-			$this->logger->logException($e);
166
-		}
167
-	}
37
+    public $dbprettyname = 'PostgreSQL';
38
+
39
+    /**
40
+     * @param string $username
41
+     * @throws \OC\DatabaseSetupException
42
+     */
43
+    public function setupDatabase($username) {
44
+        try {
45
+            $connection = $this->connect([
46
+                'dbname' => 'postgres'
47
+            ]);
48
+            //check for roles creation rights in postgresql
49
+            $builder = $connection->getQueryBuilder();
50
+            $builder->automaticTablePrefix(false);
51
+            $query = $builder
52
+                ->select('rolname')
53
+                ->from('pg_roles')
54
+                ->where($builder->expr()->eq('rolcreaterole', new Literal('TRUE')))
55
+                ->andWhere($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
56
+
57
+            try {
58
+                $result = $query->execute();
59
+                $canCreateRoles = $result->rowCount() > 0;
60
+            } catch (DatabaseException $e) {
61
+                $canCreateRoles = false;
62
+            }
63
+
64
+            if ($canCreateRoles) {
65
+                //use the admin login data for the new database user
66
+
67
+                //add prefix to the postgresql user name to prevent collisions
68
+                $this->dbUser = 'oc_' . strtolower($username);
69
+                //create a new password so we don't need to store the admin config in the config file
70
+                $this->dbPassword = \OC::$server->getSecureRandom()->generate(30, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
71
+
72
+                $this->createDBUser($connection);
73
+            }
74
+
75
+            $this->config->setValues([
76
+                'dbuser' => $this->dbUser,
77
+                'dbpassword' => $this->dbPassword,
78
+            ]);
79
+
80
+            //create the database
81
+            $this->createDatabase($connection);
82
+            // the connection to dbname=postgres is not needed anymore
83
+            $connection->close();
84
+        } catch (\Exception $e) {
85
+            $this->logger->logException($e);
86
+            $this->logger->warning('Error trying to connect as "postgres", assuming database is setup and tables need to be created');
87
+            $this->config->setValues([
88
+                'dbuser' => $this->dbUser,
89
+                'dbpassword' => $this->dbPassword,
90
+            ]);
91
+        }
92
+
93
+        // connect to the database (dbname=$this->dbname) and check if it needs to be filled
94
+        $this->dbUser = $this->config->getValue('dbuser');
95
+        $this->dbPassword = $this->config->getValue('dbpassword');
96
+        $connection = $this->connect();
97
+        try {
98
+            $connection->connect();
99
+        } catch (\Exception $e) {
100
+            $this->logger->logException($e);
101
+            throw new \OC\DatabaseSetupException($this->trans->t('PostgreSQL username and/or password not valid'),
102
+                $this->trans->t('You need to enter details of an existing account.'), 0, $e);
103
+        }
104
+    }
105
+
106
+    private function createDatabase(Connection $connection) {
107
+        if (!$this->databaseExists($connection)) {
108
+            //The database does not exists... let's create it
109
+            $query = $connection->prepare("CREATE DATABASE " . addslashes($this->dbName) . " OWNER " . addslashes($this->dbUser));
110
+            try {
111
+                $query->execute();
112
+            } catch (DatabaseException $e) {
113
+                $this->logger->error('Error while trying to create database');
114
+                $this->logger->logException($e);
115
+            }
116
+        } else {
117
+            $query = $connection->prepare("REVOKE ALL PRIVILEGES ON DATABASE " . addslashes($this->dbName) . " FROM PUBLIC");
118
+            try {
119
+                $query->execute();
120
+            } catch (DatabaseException $e) {
121
+                $this->logger->error('Error while trying to restrict database permissions');
122
+                $this->logger->logException($e);
123
+            }
124
+        }
125
+    }
126
+
127
+    private function userExists(Connection $connection) {
128
+        $builder = $connection->getQueryBuilder();
129
+        $builder->automaticTablePrefix(false);
130
+        $query = $builder->select('*')
131
+            ->from('pg_roles')
132
+            ->where($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
133
+        $result = $query->execute();
134
+        return $result->rowCount() > 0;
135
+    }
136
+
137
+    private function databaseExists(Connection $connection) {
138
+        $builder = $connection->getQueryBuilder();
139
+        $builder->automaticTablePrefix(false);
140
+        $query = $builder->select('datname')
141
+            ->from('pg_database')
142
+            ->where($builder->expr()->eq('datname', $builder->createNamedParameter($this->dbName)));
143
+        $result = $query->execute();
144
+        return $result->rowCount() > 0;
145
+    }
146
+
147
+    private function createDBUser(Connection $connection) {
148
+        $dbUser = $this->dbUser;
149
+        try {
150
+            $i = 1;
151
+            while ($this->userExists($connection)) {
152
+                $i++;
153
+                $this->dbUser = $dbUser . $i;
154
+            }
155
+
156
+            // create the user
157
+            $query = $connection->prepare("CREATE USER " . addslashes($this->dbUser) . " CREATEDB PASSWORD '" . addslashes($this->dbPassword) . "'");
158
+            $query->execute();
159
+            if ($this->databaseExists($connection)) {
160
+                $query = $connection->prepare('GRANT CONNECT ON DATABASE ' . addslashes($this->dbName) . ' TO '.addslashes($this->dbUser));
161
+                $query->execute();
162
+            }
163
+        } catch (DatabaseException $e) {
164
+            $this->logger->error('Error while trying to create database user');
165
+            $this->logger->logException($e);
166
+        }
167
+    }
168 168
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -65,9 +65,9 @@  discard block
 block discarded – undo
65 65
 				//use the admin login data for the new database user
66 66
 
67 67
 				//add prefix to the postgresql user name to prevent collisions
68
-				$this->dbUser = 'oc_' . strtolower($username);
68
+				$this->dbUser = 'oc_'.strtolower($username);
69 69
 				//create a new password so we don't need to store the admin config in the config file
70
-				$this->dbPassword = \OC::$server->getSecureRandom()->generate(30, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
70
+				$this->dbPassword = \OC::$server->getSecureRandom()->generate(30, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
71 71
 
72 72
 				$this->createDBUser($connection);
73 73
 			}
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
 	private function createDatabase(Connection $connection) {
107 107
 		if (!$this->databaseExists($connection)) {
108 108
 			//The database does not exists... let's create it
109
-			$query = $connection->prepare("CREATE DATABASE " . addslashes($this->dbName) . " OWNER " . addslashes($this->dbUser));
109
+			$query = $connection->prepare("CREATE DATABASE ".addslashes($this->dbName)." OWNER ".addslashes($this->dbUser));
110 110
 			try {
111 111
 				$query->execute();
112 112
 			} catch (DatabaseException $e) {
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 				$this->logger->logException($e);
115 115
 			}
116 116
 		} else {
117
-			$query = $connection->prepare("REVOKE ALL PRIVILEGES ON DATABASE " . addslashes($this->dbName) . " FROM PUBLIC");
117
+			$query = $connection->prepare("REVOKE ALL PRIVILEGES ON DATABASE ".addslashes($this->dbName)." FROM PUBLIC");
118 118
 			try {
119 119
 				$query->execute();
120 120
 			} catch (DatabaseException $e) {
@@ -150,14 +150,14 @@  discard block
 block discarded – undo
150 150
 			$i = 1;
151 151
 			while ($this->userExists($connection)) {
152 152
 				$i++;
153
-				$this->dbUser = $dbUser . $i;
153
+				$this->dbUser = $dbUser.$i;
154 154
 			}
155 155
 
156 156
 			// create the user
157
-			$query = $connection->prepare("CREATE USER " . addslashes($this->dbUser) . " CREATEDB PASSWORD '" . addslashes($this->dbPassword) . "'");
157
+			$query = $connection->prepare("CREATE USER ".addslashes($this->dbUser)." CREATEDB PASSWORD '".addslashes($this->dbPassword)."'");
158 158
 			$query->execute();
159 159
 			if ($this->databaseExists($connection)) {
160
-				$query = $connection->prepare('GRANT CONNECT ON DATABASE ' . addslashes($this->dbName) . ' TO '.addslashes($this->dbUser));
160
+				$query = $connection->prepare('GRANT CONNECT ON DATABASE '.addslashes($this->dbName).' TO '.addslashes($this->dbUser));
161 161
 				$query->execute();
162 162
 			}
163 163
 		} catch (DatabaseException $e) {
Please login to merge, or discard this patch.
lib/private/Setup/AbstractDatabase.php 1 patch
Indentation   +104 added lines, -104 removed lines patch added patch discarded remove patch
@@ -39,118 +39,118 @@
 block discarded – undo
39 39
 
40 40
 abstract class AbstractDatabase {
41 41
 
42
-	/** @var IL10N */
43
-	protected $trans;
44
-	/** @var string */
45
-	protected $dbUser;
46
-	/** @var string */
47
-	protected $dbPassword;
48
-	/** @var string */
49
-	protected $dbName;
50
-	/** @var string */
51
-	protected $dbHost;
52
-	/** @var string */
53
-	protected $dbPort;
54
-	/** @var string */
55
-	protected $tablePrefix;
56
-	/** @var SystemConfig */
57
-	protected $config;
58
-	/** @var ILogger */
59
-	protected $logger;
60
-	/** @var ISecureRandom */
61
-	protected $random;
42
+    /** @var IL10N */
43
+    protected $trans;
44
+    /** @var string */
45
+    protected $dbUser;
46
+    /** @var string */
47
+    protected $dbPassword;
48
+    /** @var string */
49
+    protected $dbName;
50
+    /** @var string */
51
+    protected $dbHost;
52
+    /** @var string */
53
+    protected $dbPort;
54
+    /** @var string */
55
+    protected $tablePrefix;
56
+    /** @var SystemConfig */
57
+    protected $config;
58
+    /** @var ILogger */
59
+    protected $logger;
60
+    /** @var ISecureRandom */
61
+    protected $random;
62 62
 
63
-	public function __construct(IL10N $trans, SystemConfig $config, ILogger $logger, ISecureRandom $random) {
64
-		$this->trans = $trans;
65
-		$this->config = $config;
66
-		$this->logger = $logger;
67
-		$this->random = $random;
68
-	}
63
+    public function __construct(IL10N $trans, SystemConfig $config, ILogger $logger, ISecureRandom $random) {
64
+        $this->trans = $trans;
65
+        $this->config = $config;
66
+        $this->logger = $logger;
67
+        $this->random = $random;
68
+    }
69 69
 
70
-	public function validate($config) {
71
-		$errors = [];
72
-		if (empty($config['dbuser']) && empty($config['dbname'])) {
73
-			$errors[] = $this->trans->t("%s enter the database username and name.", [$this->dbprettyname]);
74
-		} elseif (empty($config['dbuser'])) {
75
-			$errors[] = $this->trans->t("%s enter the database username.", [$this->dbprettyname]);
76
-		} elseif (empty($config['dbname'])) {
77
-			$errors[] = $this->trans->t("%s enter the database name.", [$this->dbprettyname]);
78
-		}
79
-		if (substr_count($config['dbname'], '.') >= 1) {
80
-			$errors[] = $this->trans->t("%s you may not use dots in the database name", [$this->dbprettyname]);
81
-		}
82
-		return $errors;
83
-	}
70
+    public function validate($config) {
71
+        $errors = [];
72
+        if (empty($config['dbuser']) && empty($config['dbname'])) {
73
+            $errors[] = $this->trans->t("%s enter the database username and name.", [$this->dbprettyname]);
74
+        } elseif (empty($config['dbuser'])) {
75
+            $errors[] = $this->trans->t("%s enter the database username.", [$this->dbprettyname]);
76
+        } elseif (empty($config['dbname'])) {
77
+            $errors[] = $this->trans->t("%s enter the database name.", [$this->dbprettyname]);
78
+        }
79
+        if (substr_count($config['dbname'], '.') >= 1) {
80
+            $errors[] = $this->trans->t("%s you may not use dots in the database name", [$this->dbprettyname]);
81
+        }
82
+        return $errors;
83
+    }
84 84
 
85
-	public function initialize($config) {
86
-		$dbUser = $config['dbuser'];
87
-		$dbPass = $config['dbpass'];
88
-		$dbName = $config['dbname'];
89
-		$dbHost = !empty($config['dbhost']) ? $config['dbhost'] : 'localhost';
90
-		$dbPort = !empty($config['dbport']) ? $config['dbport'] : '';
91
-		$dbTablePrefix = isset($config['dbtableprefix']) ? $config['dbtableprefix'] : 'oc_';
85
+    public function initialize($config) {
86
+        $dbUser = $config['dbuser'];
87
+        $dbPass = $config['dbpass'];
88
+        $dbName = $config['dbname'];
89
+        $dbHost = !empty($config['dbhost']) ? $config['dbhost'] : 'localhost';
90
+        $dbPort = !empty($config['dbport']) ? $config['dbport'] : '';
91
+        $dbTablePrefix = isset($config['dbtableprefix']) ? $config['dbtableprefix'] : 'oc_';
92 92
 
93
-		$this->config->setValues([
94
-			'dbname' => $dbName,
95
-			'dbhost' => $dbHost,
96
-			'dbport' => $dbPort,
97
-			'dbtableprefix' => $dbTablePrefix,
98
-		]);
93
+        $this->config->setValues([
94
+            'dbname' => $dbName,
95
+            'dbhost' => $dbHost,
96
+            'dbport' => $dbPort,
97
+            'dbtableprefix' => $dbTablePrefix,
98
+        ]);
99 99
 
100
-		$this->dbUser = $dbUser;
101
-		$this->dbPassword = $dbPass;
102
-		$this->dbName = $dbName;
103
-		$this->dbHost = $dbHost;
104
-		$this->dbPort = $dbPort;
105
-		$this->tablePrefix = $dbTablePrefix;
106
-	}
100
+        $this->dbUser = $dbUser;
101
+        $this->dbPassword = $dbPass;
102
+        $this->dbName = $dbName;
103
+        $this->dbHost = $dbHost;
104
+        $this->dbPort = $dbPort;
105
+        $this->tablePrefix = $dbTablePrefix;
106
+    }
107 107
 
108
-	/**
109
-	 * @param array $configOverwrite
110
-	 * @return \OC\DB\Connection
111
-	 */
112
-	protected function connect(array $configOverwrite = []): Connection {
113
-		$connectionParams = [
114
-			'host' => $this->dbHost,
115
-			'user' => $this->dbUser,
116
-			'password' => $this->dbPassword,
117
-			'tablePrefix' => $this->tablePrefix,
118
-			'dbname' => $this->dbName
119
-		];
108
+    /**
109
+     * @param array $configOverwrite
110
+     * @return \OC\DB\Connection
111
+     */
112
+    protected function connect(array $configOverwrite = []): Connection {
113
+        $connectionParams = [
114
+            'host' => $this->dbHost,
115
+            'user' => $this->dbUser,
116
+            'password' => $this->dbPassword,
117
+            'tablePrefix' => $this->tablePrefix,
118
+            'dbname' => $this->dbName
119
+        ];
120 120
 
121
-		// adding port support through installer
122
-		if (!empty($this->dbPort)) {
123
-			if (ctype_digit($this->dbPort)) {
124
-				$connectionParams['port'] = $this->dbPort;
125
-			} else {
126
-				$connectionParams['unix_socket'] = $this->dbPort;
127
-			}
128
-		} elseif (strpos($this->dbHost, ':')) {
129
-			// Host variable may carry a port or socket.
130
-			list($host, $portOrSocket) = explode(':', $this->dbHost, 2);
131
-			if (ctype_digit($portOrSocket)) {
132
-				$connectionParams['port'] = $portOrSocket;
133
-			} else {
134
-				$connectionParams['unix_socket'] = $portOrSocket;
135
-			}
136
-			$connectionParams['host'] = $host;
137
-		}
121
+        // adding port support through installer
122
+        if (!empty($this->dbPort)) {
123
+            if (ctype_digit($this->dbPort)) {
124
+                $connectionParams['port'] = $this->dbPort;
125
+            } else {
126
+                $connectionParams['unix_socket'] = $this->dbPort;
127
+            }
128
+        } elseif (strpos($this->dbHost, ':')) {
129
+            // Host variable may carry a port or socket.
130
+            list($host, $portOrSocket) = explode(':', $this->dbHost, 2);
131
+            if (ctype_digit($portOrSocket)) {
132
+                $connectionParams['port'] = $portOrSocket;
133
+            } else {
134
+                $connectionParams['unix_socket'] = $portOrSocket;
135
+            }
136
+            $connectionParams['host'] = $host;
137
+        }
138 138
 
139
-		$connectionParams = array_merge($connectionParams, $configOverwrite);
140
-		$cf = new ConnectionFactory($this->config);
141
-		return $cf->getConnection($this->config->getValue('dbtype', 'sqlite'), $connectionParams);
142
-	}
139
+        $connectionParams = array_merge($connectionParams, $configOverwrite);
140
+        $cf = new ConnectionFactory($this->config);
141
+        return $cf->getConnection($this->config->getValue('dbtype', 'sqlite'), $connectionParams);
142
+    }
143 143
 
144
-	/**
145
-	 * @param string $userName
146
-	 */
147
-	abstract public function setupDatabase($userName);
144
+    /**
145
+     * @param string $userName
146
+     */
147
+    abstract public function setupDatabase($userName);
148 148
 
149
-	public function runMigrations() {
150
-		if (!is_dir(\OC::$SERVERROOT."/core/Migrations")) {
151
-			return;
152
-		}
153
-		$ms = new MigrationService('core', \OC::$server->get(Connection::class));
154
-		$ms->migrate('latest', true);
155
-	}
149
+    public function runMigrations() {
150
+        if (!is_dir(\OC::$SERVERROOT."/core/Migrations")) {
151
+            return;
152
+        }
153
+        $ms = new MigrationService('core', \OC::$server->get(Connection::class));
154
+        $ms->migrate('latest', true);
155
+    }
156 156
 }
Please login to merge, or discard this patch.
lib/private/Setup/MySQL.php 2 patches
Indentation   +153 added lines, -153 removed lines patch added patch discarded remove patch
@@ -38,157 +38,157 @@
 block discarded – undo
38 38
 use Doctrine\DBAL\Platforms\MySQL80Platform;
39 39
 
40 40
 class MySQL extends AbstractDatabase {
41
-	public $dbprettyname = 'MySQL/MariaDB';
42
-
43
-	public function setupDatabase($username) {
44
-		//check if the database user has admin right
45
-		$connection = $this->connect(['dbname' => null]);
46
-
47
-		// detect mb4
48
-		$tools = new MySqlTools();
49
-		if ($tools->supports4ByteCharset(new ConnectionAdapter($connection))) {
50
-			$this->config->setValue('mysql.utf8mb4', true);
51
-			$connection = $this->connect(['dbname' => null]);
52
-		}
53
-
54
-		$this->createSpecificUser($username, new ConnectionAdapter($connection));
55
-
56
-		//create the database
57
-		$this->createDatabase($connection);
58
-
59
-		//fill the database if needed
60
-		$query = 'select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
61
-		$connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
62
-
63
-		$connection->close();
64
-		$connection = $this->connect();
65
-		try {
66
-			$connection->connect();
67
-		} catch (\Exception $e) {
68
-			$this->logger->logException($e);
69
-			throw new \OC\DatabaseSetupException($this->trans->t('MySQL username and/or password not valid'),
70
-				$this->trans->t('You need to enter details of an existing account.'), 0, $e);
71
-		}
72
-	}
73
-
74
-	/**
75
-	 * @param \OC\DB\Connection $connection
76
-	 */
77
-	private function createDatabase($connection) {
78
-		try {
79
-			$name = $this->dbName;
80
-			$user = $this->dbUser;
81
-			//we can't use OC_DB functions here because we need to connect as the administrative user.
82
-			$characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
83
-			$query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
84
-			$connection->executeUpdate($query);
85
-		} catch (\Exception $ex) {
86
-			$this->logger->logException($ex, [
87
-				'message' => 'Database creation failed.',
88
-				'level' => ILogger::ERROR,
89
-				'app' => 'mysql.setup',
90
-			]);
91
-			return;
92
-		}
93
-
94
-		try {
95
-			//this query will fail if there aren't the right permissions, ignore the error
96
-			$query = "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, REFERENCES, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, EVENT, TRIGGER ON `$name` . * TO '$user'";
97
-			$connection->executeUpdate($query);
98
-		} catch (\Exception $ex) {
99
-			$this->logger->logException($ex, [
100
-				'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
101
-				'level' => ILogger::DEBUG,
102
-				'app' => 'mysql.setup',
103
-			]);
104
-		}
105
-	}
106
-
107
-	/**
108
-	 * @param IDBConnection $connection
109
-	 * @throws \OC\DatabaseSetupException
110
-	 */
111
-	private function createDBUser($connection) {
112
-		try {
113
-			$name = $this->dbUser;
114
-			$password = $this->dbPassword;
115
-			// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
116
-			// the anonymous user would take precedence when there is one.
117
-
118
-			if ($connection->getDatabasePlatform() instanceof Mysql80Platform) {
119
-				$query = "CREATE USER '$name'@'localhost' IDENTIFIED WITH mysql_native_password BY '$password'";
120
-				$connection->executeUpdate($query);
121
-				$query = "CREATE USER '$name'@'%' IDENTIFIED WITH mysql_native_password BY '$password'";
122
-				$connection->executeUpdate($query);
123
-			} else {
124
-				$query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
125
-				$connection->executeUpdate($query);
126
-				$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
127
-				$connection->executeUpdate($query);
128
-			}
129
-		} catch (\Exception $ex) {
130
-			$this->logger->logException($ex, [
131
-				'message' => 'Database user creation failed.',
132
-				'level' => ILogger::ERROR,
133
-				'app' => 'mysql.setup',
134
-			]);
135
-		}
136
-	}
137
-
138
-	/**
139
-	 * @param $username
140
-	 * @param IDBConnection $connection
141
-	 * @return array
142
-	 */
143
-	private function createSpecificUser($username, $connection) {
144
-		try {
145
-			//user already specified in config
146
-			$oldUser = $this->config->getValue('dbuser', false);
147
-
148
-			//we don't have a dbuser specified in config
149
-			if ($this->dbUser !== $oldUser) {
150
-				//add prefix to the admin username to prevent collisions
151
-				$adminUser = substr('oc_' . $username, 0, 16);
152
-
153
-				$i = 1;
154
-				while (true) {
155
-					//this should be enough to check for admin rights in mysql
156
-					$query = 'SELECT user FROM mysql.user WHERE user=?';
157
-					$result = $connection->executeQuery($query, [$adminUser]);
158
-
159
-					//current dbuser has admin rights
160
-					$data = $result->fetchAll();
161
-					$result->closeCursor();
162
-					//new dbuser does not exist
163
-					if (count($data) === 0) {
164
-						//use the admin login data for the new database user
165
-						$this->dbUser = $adminUser;
166
-
167
-						//create a random password so we don't need to store the admin password in the config file
168
-						$this->dbPassword = $this->random->generate(30);
169
-
170
-						$this->createDBUser($connection);
171
-
172
-						break;
173
-					} else {
174
-						//repeat with different username
175
-						$length = strlen((string)$i);
176
-						$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
177
-						$i++;
178
-					}
179
-				}
180
-			}
181
-		} catch (\Exception $ex) {
182
-			$this->logger->logException($ex, [
183
-				'message' => 'Can not create a new MySQL user, will continue with the provided user.',
184
-				'level' => ILogger::INFO,
185
-				'app' => 'mysql.setup',
186
-			]);
187
-		}
188
-
189
-		$this->config->setValues([
190
-			'dbuser' => $this->dbUser,
191
-			'dbpassword' => $this->dbPassword,
192
-		]);
193
-	}
41
+    public $dbprettyname = 'MySQL/MariaDB';
42
+
43
+    public function setupDatabase($username) {
44
+        //check if the database user has admin right
45
+        $connection = $this->connect(['dbname' => null]);
46
+
47
+        // detect mb4
48
+        $tools = new MySqlTools();
49
+        if ($tools->supports4ByteCharset(new ConnectionAdapter($connection))) {
50
+            $this->config->setValue('mysql.utf8mb4', true);
51
+            $connection = $this->connect(['dbname' => null]);
52
+        }
53
+
54
+        $this->createSpecificUser($username, new ConnectionAdapter($connection));
55
+
56
+        //create the database
57
+        $this->createDatabase($connection);
58
+
59
+        //fill the database if needed
60
+        $query = 'select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
61
+        $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
62
+
63
+        $connection->close();
64
+        $connection = $this->connect();
65
+        try {
66
+            $connection->connect();
67
+        } catch (\Exception $e) {
68
+            $this->logger->logException($e);
69
+            throw new \OC\DatabaseSetupException($this->trans->t('MySQL username and/or password not valid'),
70
+                $this->trans->t('You need to enter details of an existing account.'), 0, $e);
71
+        }
72
+    }
73
+
74
+    /**
75
+     * @param \OC\DB\Connection $connection
76
+     */
77
+    private function createDatabase($connection) {
78
+        try {
79
+            $name = $this->dbName;
80
+            $user = $this->dbUser;
81
+            //we can't use OC_DB functions here because we need to connect as the administrative user.
82
+            $characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
83
+            $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
84
+            $connection->executeUpdate($query);
85
+        } catch (\Exception $ex) {
86
+            $this->logger->logException($ex, [
87
+                'message' => 'Database creation failed.',
88
+                'level' => ILogger::ERROR,
89
+                'app' => 'mysql.setup',
90
+            ]);
91
+            return;
92
+        }
93
+
94
+        try {
95
+            //this query will fail if there aren't the right permissions, ignore the error
96
+            $query = "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, REFERENCES, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, EVENT, TRIGGER ON `$name` . * TO '$user'";
97
+            $connection->executeUpdate($query);
98
+        } catch (\Exception $ex) {
99
+            $this->logger->logException($ex, [
100
+                'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
101
+                'level' => ILogger::DEBUG,
102
+                'app' => 'mysql.setup',
103
+            ]);
104
+        }
105
+    }
106
+
107
+    /**
108
+     * @param IDBConnection $connection
109
+     * @throws \OC\DatabaseSetupException
110
+     */
111
+    private function createDBUser($connection) {
112
+        try {
113
+            $name = $this->dbUser;
114
+            $password = $this->dbPassword;
115
+            // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
116
+            // the anonymous user would take precedence when there is one.
117
+
118
+            if ($connection->getDatabasePlatform() instanceof Mysql80Platform) {
119
+                $query = "CREATE USER '$name'@'localhost' IDENTIFIED WITH mysql_native_password BY '$password'";
120
+                $connection->executeUpdate($query);
121
+                $query = "CREATE USER '$name'@'%' IDENTIFIED WITH mysql_native_password BY '$password'";
122
+                $connection->executeUpdate($query);
123
+            } else {
124
+                $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
125
+                $connection->executeUpdate($query);
126
+                $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
127
+                $connection->executeUpdate($query);
128
+            }
129
+        } catch (\Exception $ex) {
130
+            $this->logger->logException($ex, [
131
+                'message' => 'Database user creation failed.',
132
+                'level' => ILogger::ERROR,
133
+                'app' => 'mysql.setup',
134
+            ]);
135
+        }
136
+    }
137
+
138
+    /**
139
+     * @param $username
140
+     * @param IDBConnection $connection
141
+     * @return array
142
+     */
143
+    private function createSpecificUser($username, $connection) {
144
+        try {
145
+            //user already specified in config
146
+            $oldUser = $this->config->getValue('dbuser', false);
147
+
148
+            //we don't have a dbuser specified in config
149
+            if ($this->dbUser !== $oldUser) {
150
+                //add prefix to the admin username to prevent collisions
151
+                $adminUser = substr('oc_' . $username, 0, 16);
152
+
153
+                $i = 1;
154
+                while (true) {
155
+                    //this should be enough to check for admin rights in mysql
156
+                    $query = 'SELECT user FROM mysql.user WHERE user=?';
157
+                    $result = $connection->executeQuery($query, [$adminUser]);
158
+
159
+                    //current dbuser has admin rights
160
+                    $data = $result->fetchAll();
161
+                    $result->closeCursor();
162
+                    //new dbuser does not exist
163
+                    if (count($data) === 0) {
164
+                        //use the admin login data for the new database user
165
+                        $this->dbUser = $adminUser;
166
+
167
+                        //create a random password so we don't need to store the admin password in the config file
168
+                        $this->dbPassword = $this->random->generate(30);
169
+
170
+                        $this->createDBUser($connection);
171
+
172
+                        break;
173
+                    } else {
174
+                        //repeat with different username
175
+                        $length = strlen((string)$i);
176
+                        $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
177
+                        $i++;
178
+                    }
179
+                }
180
+            }
181
+        } catch (\Exception $ex) {
182
+            $this->logger->logException($ex, [
183
+                'message' => 'Can not create a new MySQL user, will continue with the provided user.',
184
+                'level' => ILogger::INFO,
185
+                'app' => 'mysql.setup',
186
+            ]);
187
+        }
188
+
189
+        $this->config->setValues([
190
+            'dbuser' => $this->dbUser,
191
+            'dbpassword' => $this->dbPassword,
192
+        ]);
193
+    }
194 194
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
 			//we don't have a dbuser specified in config
149 149
 			if ($this->dbUser !== $oldUser) {
150 150
 				//add prefix to the admin username to prevent collisions
151
-				$adminUser = substr('oc_' . $username, 0, 16);
151
+				$adminUser = substr('oc_'.$username, 0, 16);
152 152
 
153 153
 				$i = 1;
154 154
 				while (true) {
@@ -172,8 +172,8 @@  discard block
 block discarded – undo
172 172
 						break;
173 173
 					} else {
174 174
 						//repeat with different username
175
-						$length = strlen((string)$i);
176
-						$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
175
+						$length = strlen((string) $i);
176
+						$adminUser = substr('oc_'.$username, 0, 16 - $length).$i;
177 177
 						$i++;
178 178
 					}
179 179
 				}
Please login to merge, or discard this patch.