Passed
Push — master ( 2911df...737931 )
by Joas
14:09 queued 12s
created
lib/private/Authentication/Token/TokenCleanupJob.php 1 patch
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -25,17 +25,17 @@
 block discarded – undo
25 25
 use OCP\BackgroundJob\TimedJob;
26 26
 
27 27
 class TokenCleanupJob extends TimedJob {
28
-	private IProvider $provider;
28
+    private IProvider $provider;
29 29
 
30
-	public function __construct(ITimeFactory $time, IProvider $provider) {
31
-		parent::__construct($time);
32
-		$this->provider = $provider;
33
-		// Run once a day at off-peak time
34
-		$this->setInterval(24 * 60 * 60);
35
-		$this->setTimeSensitivity(self::TIME_INSENSITIVE);
36
-	}
30
+    public function __construct(ITimeFactory $time, IProvider $provider) {
31
+        parent::__construct($time);
32
+        $this->provider = $provider;
33
+        // Run once a day at off-peak time
34
+        $this->setInterval(24 * 60 * 60);
35
+        $this->setTimeSensitivity(self::TIME_INSENSITIVE);
36
+    }
37 37
 
38
-	protected function run($argument) {
39
-		$this->provider->invalidateOldTokens();
40
-	}
38
+    protected function run($argument) {
39
+        $this->provider->invalidateOldTokens();
40
+    }
41 41
 }
Please login to merge, or discard this patch.
lib/private/Setup.php 1 patch
Indentation   +540 added lines, -540 removed lines patch added patch discarded remove patch
@@ -64,544 +64,544 @@
 block discarded – undo
64 64
 use Psr\Log\LoggerInterface;
65 65
 
66 66
 class Setup {
67
-	/** @var SystemConfig */
68
-	protected $config;
69
-	/** @var IniGetWrapper */
70
-	protected $iniWrapper;
71
-	/** @var IL10N */
72
-	protected $l10n;
73
-	/** @var Defaults */
74
-	protected $defaults;
75
-	/** @var LoggerInterface */
76
-	protected $logger;
77
-	/** @var ISecureRandom */
78
-	protected $random;
79
-	/** @var Installer */
80
-	protected $installer;
81
-
82
-	public function __construct(
83
-		SystemConfig $config,
84
-		IniGetWrapper $iniWrapper,
85
-		IL10N $l10n,
86
-		Defaults $defaults,
87
-		LoggerInterface $logger,
88
-		ISecureRandom $random,
89
-		Installer $installer
90
-	) {
91
-		$this->config = $config;
92
-		$this->iniWrapper = $iniWrapper;
93
-		$this->l10n = $l10n;
94
-		$this->defaults = $defaults;
95
-		$this->logger = $logger;
96
-		$this->random = $random;
97
-		$this->installer = $installer;
98
-	}
99
-
100
-	protected static $dbSetupClasses = [
101
-		'mysql' => \OC\Setup\MySQL::class,
102
-		'pgsql' => \OC\Setup\PostgreSQL::class,
103
-		'oci' => \OC\Setup\OCI::class,
104
-		'sqlite' => \OC\Setup\Sqlite::class,
105
-		'sqlite3' => \OC\Setup\Sqlite::class,
106
-	];
107
-
108
-	/**
109
-	 * Wrapper around the "class_exists" PHP function to be able to mock it
110
-	 *
111
-	 * @param string $name
112
-	 * @return bool
113
-	 */
114
-	protected function class_exists($name) {
115
-		return class_exists($name);
116
-	}
117
-
118
-	/**
119
-	 * Wrapper around the "is_callable" PHP function to be able to mock it
120
-	 *
121
-	 * @param string $name
122
-	 * @return bool
123
-	 */
124
-	protected function is_callable($name) {
125
-		return is_callable($name);
126
-	}
127
-
128
-	/**
129
-	 * Wrapper around \PDO::getAvailableDrivers
130
-	 *
131
-	 * @return array
132
-	 */
133
-	protected function getAvailableDbDriversForPdo() {
134
-		if (class_exists(\PDO::class)) {
135
-			return \PDO::getAvailableDrivers();
136
-		}
137
-		return [];
138
-	}
139
-
140
-	/**
141
-	 * Get the available and supported databases of this instance
142
-	 *
143
-	 * @param bool $allowAllDatabases
144
-	 * @return array
145
-	 * @throws Exception
146
-	 */
147
-	public function getSupportedDatabases($allowAllDatabases = false) {
148
-		$availableDatabases = [
149
-			'sqlite' => [
150
-				'type' => 'pdo',
151
-				'call' => 'sqlite',
152
-				'name' => 'SQLite',
153
-			],
154
-			'mysql' => [
155
-				'type' => 'pdo',
156
-				'call' => 'mysql',
157
-				'name' => 'MySQL/MariaDB',
158
-			],
159
-			'pgsql' => [
160
-				'type' => 'pdo',
161
-				'call' => 'pgsql',
162
-				'name' => 'PostgreSQL',
163
-			],
164
-			'oci' => [
165
-				'type' => 'function',
166
-				'call' => 'oci_connect',
167
-				'name' => 'Oracle',
168
-			],
169
-		];
170
-		if ($allowAllDatabases) {
171
-			$configuredDatabases = array_keys($availableDatabases);
172
-		} else {
173
-			$configuredDatabases = $this->config->getValue('supportedDatabases',
174
-				['sqlite', 'mysql', 'pgsql']);
175
-		}
176
-		if (!is_array($configuredDatabases)) {
177
-			throw new Exception('Supported databases are not properly configured.');
178
-		}
179
-
180
-		$supportedDatabases = [];
181
-
182
-		foreach ($configuredDatabases as $database) {
183
-			if (array_key_exists($database, $availableDatabases)) {
184
-				$working = false;
185
-				$type = $availableDatabases[$database]['type'];
186
-				$call = $availableDatabases[$database]['call'];
187
-
188
-				if ($type === 'function') {
189
-					$working = $this->is_callable($call);
190
-				} elseif ($type === 'pdo') {
191
-					$working = in_array($call, $this->getAvailableDbDriversForPdo(), true);
192
-				}
193
-				if ($working) {
194
-					$supportedDatabases[$database] = $availableDatabases[$database]['name'];
195
-				}
196
-			}
197
-		}
198
-
199
-		return $supportedDatabases;
200
-	}
201
-
202
-	/**
203
-	 * Gathers system information like database type and does
204
-	 * a few system checks.
205
-	 *
206
-	 * @return array of system info, including an "errors" value
207
-	 * in case of errors/warnings
208
-	 */
209
-	public function getSystemInfo($allowAllDatabases = false) {
210
-		$databases = $this->getSupportedDatabases($allowAllDatabases);
211
-
212
-		$dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT . '/data');
213
-
214
-		$errors = [];
215
-
216
-		// Create data directory to test whether the .htaccess works
217
-		// Notice that this is not necessarily the same data directory as the one
218
-		// that will effectively be used.
219
-		if (!file_exists($dataDir)) {
220
-			@mkdir($dataDir);
221
-		}
222
-		$htAccessWorking = true;
223
-		if (is_dir($dataDir) && is_writable($dataDir)) {
224
-			// Protect data directory here, so we can test if the protection is working
225
-			self::protectDataDirectory();
226
-
227
-			try {
228
-				$util = new \OC_Util();
229
-				$htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
230
-			} catch (\OCP\HintException $e) {
231
-				$errors[] = [
232
-					'error' => $e->getMessage(),
233
-					'exception' => $e,
234
-					'hint' => $e->getHint(),
235
-				];
236
-				$htAccessWorking = false;
237
-			}
238
-		}
239
-
240
-		if (\OC_Util::runningOnMac()) {
241
-			$errors[] = [
242
-				'error' => $this->l10n->t(
243
-					'Mac OS X is not supported and %s will not work properly on this platform. ' .
244
-					'Use it at your own risk! ',
245
-					[$this->defaults->getProductName()]
246
-				),
247
-				'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.'),
248
-			];
249
-		}
250
-
251
-		if ($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
252
-			$errors[] = [
253
-				'error' => $this->l10n->t(
254
-					'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
255
-					'This will lead to problems with files over 4 GB and is highly discouraged.',
256
-					[$this->defaults->getProductName()]
257
-				),
258
-				'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.'),
259
-			];
260
-		}
261
-
262
-		return [
263
-			'hasSQLite' => isset($databases['sqlite']),
264
-			'hasMySQL' => isset($databases['mysql']),
265
-			'hasPostgreSQL' => isset($databases['pgsql']),
266
-			'hasOracle' => isset($databases['oci']),
267
-			'databases' => $databases,
268
-			'directory' => $dataDir,
269
-			'htaccessWorking' => $htAccessWorking,
270
-			'errors' => $errors,
271
-		];
272
-	}
273
-
274
-	/**
275
-	 * @param $options
276
-	 * @return array
277
-	 */
278
-	public function install($options) {
279
-		$l = $this->l10n;
280
-
281
-		$error = [];
282
-		$dbType = $options['dbtype'];
283
-
284
-		if (empty($options['adminlogin'])) {
285
-			$error[] = $l->t('Set an admin username.');
286
-		}
287
-		if (empty($options['adminpass'])) {
288
-			$error[] = $l->t('Set an admin password.');
289
-		}
290
-		if (empty($options['directory'])) {
291
-			$options['directory'] = \OC::$SERVERROOT . "/data";
292
-		}
293
-
294
-		if (!isset(self::$dbSetupClasses[$dbType])) {
295
-			$dbType = 'sqlite';
296
-		}
297
-
298
-		$username = htmlspecialchars_decode($options['adminlogin']);
299
-		$password = htmlspecialchars_decode($options['adminpass']);
300
-		$dataDir = htmlspecialchars_decode($options['directory']);
301
-
302
-		$class = self::$dbSetupClasses[$dbType];
303
-		/** @var \OC\Setup\AbstractDatabase $dbSetup */
304
-		$dbSetup = new $class($l, $this->config, $this->logger, $this->random);
305
-		$error = array_merge($error, $dbSetup->validate($options));
306
-
307
-		// validate the data directory
308
-		if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) {
309
-			$error[] = $l->t("Cannot create or write into the data directory %s", [$dataDir]);
310
-		}
311
-
312
-		if (!empty($error)) {
313
-			return $error;
314
-		}
315
-
316
-		$request = \OC::$server->getRequest();
317
-
318
-		//no errors, good
319
-		if (isset($options['trusted_domains'])
320
-			&& is_array($options['trusted_domains'])) {
321
-			$trustedDomains = $options['trusted_domains'];
322
-		} else {
323
-			$trustedDomains = [$request->getInsecureServerHost()];
324
-		}
325
-
326
-		//use sqlite3 when available, otherwise sqlite2 will be used.
327
-		if ($dbType === 'sqlite' && class_exists('SQLite3')) {
328
-			$dbType = 'sqlite3';
329
-		}
330
-
331
-		//generate a random salt that is used to salt the local user passwords
332
-		$salt = $this->random->generate(30);
333
-		// generate a secret
334
-		$secret = $this->random->generate(48);
335
-
336
-		//write the config file
337
-		$newConfigValues = [
338
-			'passwordsalt' => $salt,
339
-			'secret' => $secret,
340
-			'trusted_domains' => $trustedDomains,
341
-			'datadirectory' => $dataDir,
342
-			'dbtype' => $dbType,
343
-			'version' => implode('.', \OCP\Util::getVersion()),
344
-		];
345
-
346
-		if ($this->config->getValue('overwrite.cli.url', null) === null) {
347
-			$newConfigValues['overwrite.cli.url'] = $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT;
348
-		}
349
-
350
-		$this->config->setValues($newConfigValues);
351
-
352
-		$dbSetup->initialize($options);
353
-		try {
354
-			$dbSetup->setupDatabase($username);
355
-		} catch (\OC\DatabaseSetupException $e) {
356
-			$error[] = [
357
-				'error' => $e->getMessage(),
358
-				'exception' => $e,
359
-				'hint' => $e->getHint(),
360
-			];
361
-			return $error;
362
-		} catch (Exception $e) {
363
-			$error[] = [
364
-				'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
365
-				'exception' => $e,
366
-				'hint' => '',
367
-			];
368
-			return $error;
369
-		}
370
-		try {
371
-			// apply necessary migrations
372
-			$dbSetup->runMigrations();
373
-		} catch (Exception $e) {
374
-			$error[] = [
375
-				'error' => 'Error while trying to initialise the database: ' . $e->getMessage(),
376
-				'exception' => $e,
377
-				'hint' => '',
378
-			];
379
-			return $error;
380
-		}
381
-
382
-		//create the user and group
383
-		$user = null;
384
-		try {
385
-			$user = \OC::$server->getUserManager()->createUser($username, $password);
386
-			if (!$user) {
387
-				$error[] = "User <$username> could not be created.";
388
-			}
389
-		} catch (Exception $exception) {
390
-			$error[] = $exception->getMessage();
391
-		}
392
-
393
-		if (empty($error)) {
394
-			$config = \OC::$server->getConfig();
395
-			$config->setAppValue('core', 'installedat', microtime(true));
396
-			$config->setAppValue('core', 'lastupdatedat', microtime(true));
397
-			$config->setAppValue('core', 'vendor', $this->getVendor());
398
-
399
-			$group = \OC::$server->getGroupManager()->createGroup('admin');
400
-			if ($group instanceof IGroup) {
401
-				$group->addUser($user);
402
-			}
403
-
404
-			// Install shipped apps and specified app bundles
405
-			Installer::installShippedApps();
406
-			$bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
407
-			$defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
408
-			foreach ($defaultInstallationBundles as $bundle) {
409
-				try {
410
-					$this->installer->installAppBundle($bundle);
411
-				} catch (Exception $e) {
412
-				}
413
-			}
414
-
415
-			// create empty file in data dir, so we can later find
416
-			// out that this is indeed an ownCloud data directory
417
-			file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
418
-
419
-			// Update .htaccess files
420
-			self::updateHtaccess();
421
-			self::protectDataDirectory();
422
-
423
-			self::installBackgroundJobs();
424
-
425
-			//and we are done
426
-			$config->setSystemValue('installed', true);
427
-
428
-			$bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
429
-			$bootstrapCoordinator->runInitialRegistration();
430
-
431
-			// Create a session token for the newly created user
432
-			// The token provider requires a working db, so it's not injected on setup
433
-			/* @var $userSession User\Session */
434
-			$userSession = \OC::$server->getUserSession();
435
-			$provider = \OC::$server->query(PublicKeyTokenProvider::class);
436
-			$userSession->setTokenProvider($provider);
437
-			$userSession->login($username, $password);
438
-			$userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
439
-
440
-			$session = $userSession->getSession();
441
-			$session->set('last-password-confirm', \OC::$server->query(ITimeFactory::class)->getTime());
442
-
443
-			// Set email for admin
444
-			if (!empty($options['adminemail'])) {
445
-				$user->setSystemEMailAddress($options['adminemail']);
446
-			}
447
-		}
448
-
449
-		return $error;
450
-	}
451
-
452
-	public static function installBackgroundJobs() {
453
-		$jobList = \OC::$server->getJobList();
454
-		$jobList->add(TokenCleanupJob::class);
455
-		$jobList->add(Rotate::class);
456
-		$jobList->add(BackgroundCleanupJob::class);
457
-	}
458
-
459
-	/**
460
-	 * @return string Absolute path to htaccess
461
-	 */
462
-	private function pathToHtaccess() {
463
-		return \OC::$SERVERROOT . '/.htaccess';
464
-	}
465
-
466
-	/**
467
-	 * Find webroot from config
468
-	 *
469
-	 * @param SystemConfig $config
470
-	 * @return string
471
-	 * @throws InvalidArgumentException when invalid value for overwrite.cli.url
472
-	 */
473
-	private static function findWebRoot(SystemConfig $config): string {
474
-		// For CLI read the value from overwrite.cli.url
475
-		if (\OC::$CLI) {
476
-			$webRoot = $config->getValue('overwrite.cli.url', '');
477
-			if ($webRoot === '') {
478
-				throw new InvalidArgumentException('overwrite.cli.url is empty');
479
-			}
480
-			if (!filter_var($webRoot, FILTER_VALIDATE_URL)) {
481
-				throw new InvalidArgumentException('invalid value for overwrite.cli.url');
482
-			}
483
-			$webRoot = rtrim((parse_url($webRoot, PHP_URL_PATH) ?? ''), '/');
484
-		} else {
485
-			$webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
486
-		}
487
-
488
-		return $webRoot;
489
-	}
490
-
491
-	/**
492
-	 * Append the correct ErrorDocument path for Apache hosts
493
-	 *
494
-	 * @return bool True when success, False otherwise
495
-	 * @throws \OCP\AppFramework\QueryException
496
-	 */
497
-	public static function updateHtaccess() {
498
-		$config = \OC::$server->getSystemConfig();
499
-
500
-		try {
501
-			$webRoot = self::findWebRoot($config);
502
-		} catch (InvalidArgumentException $e) {
503
-			return false;
504
-		}
505
-
506
-		$setupHelper = new \OC\Setup(
507
-			$config,
508
-			\OC::$server->get(IniGetWrapper::class),
509
-			\OC::$server->getL10N('lib'),
510
-			\OC::$server->query(Defaults::class),
511
-			\OC::$server->get(LoggerInterface::class),
512
-			\OC::$server->getSecureRandom(),
513
-			\OC::$server->query(Installer::class)
514
-		);
515
-
516
-		$htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
517
-		$content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
518
-		$htaccessContent = explode($content, $htaccessContent, 2)[0];
519
-
520
-		//custom 403 error page
521
-		$content .= "\nErrorDocument 403 " . $webRoot . '/';
522
-
523
-		//custom 404 error page
524
-		$content .= "\nErrorDocument 404 " . $webRoot . '/';
525
-
526
-		// Add rewrite rules if the RewriteBase is configured
527
-		$rewriteBase = $config->getValue('htaccess.RewriteBase', '');
528
-		if ($rewriteBase !== '') {
529
-			$content .= "\n<IfModule mod_rewrite.c>";
530
-			$content .= "\n  Options -MultiViews";
531
-			$content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
532
-			$content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
533
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff2?|ico|jpg|jpeg|map|webm|mp4|mp3|ogg|wav|wasm|tflite)$";
534
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update\\.php";
535
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/img/(favicon\\.ico|manifest\\.json)$";
536
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/(cron|public|remote|status)\\.php";
537
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v(1|2)\\.php";
538
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots\\.txt";
539
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/(ocm-provider|ocs-provider|updater)/";
540
-			$content .= "\n  RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
541
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/richdocumentscode(_arm64)?/proxy.php$";
542
-			$content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
543
-			$content .= "\n  RewriteBase " . $rewriteBase;
544
-			$content .= "\n  <IfModule mod_env.c>";
545
-			$content .= "\n    SetEnv front_controller_active true";
546
-			$content .= "\n    <IfModule mod_dir.c>";
547
-			$content .= "\n      DirectorySlash off";
548
-			$content .= "\n    </IfModule>";
549
-			$content .= "\n  </IfModule>";
550
-			$content .= "\n</IfModule>";
551
-		}
552
-
553
-		if ($content !== '') {
554
-			//suppress errors in case we don't have permissions for it
555
-			return (bool)@file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent . $content . "\n");
556
-		}
557
-
558
-		return false;
559
-	}
560
-
561
-	public static function protectDataDirectory() {
562
-		//Require all denied
563
-		$now = date('Y-m-d H:i:s');
564
-		$content = "# Generated by Nextcloud on $now\n";
565
-		$content .= "# Section for Apache 2.4 to 2.6\n";
566
-		$content .= "<IfModule mod_authz_core.c>\n";
567
-		$content .= "  Require all denied\n";
568
-		$content .= "</IfModule>\n";
569
-		$content .= "<IfModule mod_access_compat.c>\n";
570
-		$content .= "  Order Allow,Deny\n";
571
-		$content .= "  Deny from all\n";
572
-		$content .= "  Satisfy All\n";
573
-		$content .= "</IfModule>\n\n";
574
-		$content .= "# Section for Apache 2.2\n";
575
-		$content .= "<IfModule !mod_authz_core.c>\n";
576
-		$content .= "  <IfModule !mod_access_compat.c>\n";
577
-		$content .= "    <IfModule mod_authz_host.c>\n";
578
-		$content .= "      Order Allow,Deny\n";
579
-		$content .= "      Deny from all\n";
580
-		$content .= "    </IfModule>\n";
581
-		$content .= "    Satisfy All\n";
582
-		$content .= "  </IfModule>\n";
583
-		$content .= "</IfModule>\n\n";
584
-		$content .= "# Section for Apache 2.2 to 2.6\n";
585
-		$content .= "<IfModule mod_autoindex.c>\n";
586
-		$content .= "  IndexIgnore *\n";
587
-		$content .= "</IfModule>";
588
-
589
-		$baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
590
-		file_put_contents($baseDir . '/.htaccess', $content);
591
-		file_put_contents($baseDir . '/index.html', '');
592
-	}
593
-
594
-	/**
595
-	 * Return vendor from which this version was published
596
-	 *
597
-	 * @return string Get the vendor
598
-	 *
599
-	 * Copy of \OC\Updater::getVendor()
600
-	 */
601
-	private function getVendor() {
602
-		// this should really be a JSON file
603
-		require \OC::$SERVERROOT . '/version.php';
604
-		/** @var string $vendor */
605
-		return (string)$vendor;
606
-	}
67
+    /** @var SystemConfig */
68
+    protected $config;
69
+    /** @var IniGetWrapper */
70
+    protected $iniWrapper;
71
+    /** @var IL10N */
72
+    protected $l10n;
73
+    /** @var Defaults */
74
+    protected $defaults;
75
+    /** @var LoggerInterface */
76
+    protected $logger;
77
+    /** @var ISecureRandom */
78
+    protected $random;
79
+    /** @var Installer */
80
+    protected $installer;
81
+
82
+    public function __construct(
83
+        SystemConfig $config,
84
+        IniGetWrapper $iniWrapper,
85
+        IL10N $l10n,
86
+        Defaults $defaults,
87
+        LoggerInterface $logger,
88
+        ISecureRandom $random,
89
+        Installer $installer
90
+    ) {
91
+        $this->config = $config;
92
+        $this->iniWrapper = $iniWrapper;
93
+        $this->l10n = $l10n;
94
+        $this->defaults = $defaults;
95
+        $this->logger = $logger;
96
+        $this->random = $random;
97
+        $this->installer = $installer;
98
+    }
99
+
100
+    protected static $dbSetupClasses = [
101
+        'mysql' => \OC\Setup\MySQL::class,
102
+        'pgsql' => \OC\Setup\PostgreSQL::class,
103
+        'oci' => \OC\Setup\OCI::class,
104
+        'sqlite' => \OC\Setup\Sqlite::class,
105
+        'sqlite3' => \OC\Setup\Sqlite::class,
106
+    ];
107
+
108
+    /**
109
+     * Wrapper around the "class_exists" PHP function to be able to mock it
110
+     *
111
+     * @param string $name
112
+     * @return bool
113
+     */
114
+    protected function class_exists($name) {
115
+        return class_exists($name);
116
+    }
117
+
118
+    /**
119
+     * Wrapper around the "is_callable" PHP function to be able to mock it
120
+     *
121
+     * @param string $name
122
+     * @return bool
123
+     */
124
+    protected function is_callable($name) {
125
+        return is_callable($name);
126
+    }
127
+
128
+    /**
129
+     * Wrapper around \PDO::getAvailableDrivers
130
+     *
131
+     * @return array
132
+     */
133
+    protected function getAvailableDbDriversForPdo() {
134
+        if (class_exists(\PDO::class)) {
135
+            return \PDO::getAvailableDrivers();
136
+        }
137
+        return [];
138
+    }
139
+
140
+    /**
141
+     * Get the available and supported databases of this instance
142
+     *
143
+     * @param bool $allowAllDatabases
144
+     * @return array
145
+     * @throws Exception
146
+     */
147
+    public function getSupportedDatabases($allowAllDatabases = false) {
148
+        $availableDatabases = [
149
+            'sqlite' => [
150
+                'type' => 'pdo',
151
+                'call' => 'sqlite',
152
+                'name' => 'SQLite',
153
+            ],
154
+            'mysql' => [
155
+                'type' => 'pdo',
156
+                'call' => 'mysql',
157
+                'name' => 'MySQL/MariaDB',
158
+            ],
159
+            'pgsql' => [
160
+                'type' => 'pdo',
161
+                'call' => 'pgsql',
162
+                'name' => 'PostgreSQL',
163
+            ],
164
+            'oci' => [
165
+                'type' => 'function',
166
+                'call' => 'oci_connect',
167
+                'name' => 'Oracle',
168
+            ],
169
+        ];
170
+        if ($allowAllDatabases) {
171
+            $configuredDatabases = array_keys($availableDatabases);
172
+        } else {
173
+            $configuredDatabases = $this->config->getValue('supportedDatabases',
174
+                ['sqlite', 'mysql', 'pgsql']);
175
+        }
176
+        if (!is_array($configuredDatabases)) {
177
+            throw new Exception('Supported databases are not properly configured.');
178
+        }
179
+
180
+        $supportedDatabases = [];
181
+
182
+        foreach ($configuredDatabases as $database) {
183
+            if (array_key_exists($database, $availableDatabases)) {
184
+                $working = false;
185
+                $type = $availableDatabases[$database]['type'];
186
+                $call = $availableDatabases[$database]['call'];
187
+
188
+                if ($type === 'function') {
189
+                    $working = $this->is_callable($call);
190
+                } elseif ($type === 'pdo') {
191
+                    $working = in_array($call, $this->getAvailableDbDriversForPdo(), true);
192
+                }
193
+                if ($working) {
194
+                    $supportedDatabases[$database] = $availableDatabases[$database]['name'];
195
+                }
196
+            }
197
+        }
198
+
199
+        return $supportedDatabases;
200
+    }
201
+
202
+    /**
203
+     * Gathers system information like database type and does
204
+     * a few system checks.
205
+     *
206
+     * @return array of system info, including an "errors" value
207
+     * in case of errors/warnings
208
+     */
209
+    public function getSystemInfo($allowAllDatabases = false) {
210
+        $databases = $this->getSupportedDatabases($allowAllDatabases);
211
+
212
+        $dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT . '/data');
213
+
214
+        $errors = [];
215
+
216
+        // Create data directory to test whether the .htaccess works
217
+        // Notice that this is not necessarily the same data directory as the one
218
+        // that will effectively be used.
219
+        if (!file_exists($dataDir)) {
220
+            @mkdir($dataDir);
221
+        }
222
+        $htAccessWorking = true;
223
+        if (is_dir($dataDir) && is_writable($dataDir)) {
224
+            // Protect data directory here, so we can test if the protection is working
225
+            self::protectDataDirectory();
226
+
227
+            try {
228
+                $util = new \OC_Util();
229
+                $htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
230
+            } catch (\OCP\HintException $e) {
231
+                $errors[] = [
232
+                    'error' => $e->getMessage(),
233
+                    'exception' => $e,
234
+                    'hint' => $e->getHint(),
235
+                ];
236
+                $htAccessWorking = false;
237
+            }
238
+        }
239
+
240
+        if (\OC_Util::runningOnMac()) {
241
+            $errors[] = [
242
+                'error' => $this->l10n->t(
243
+                    'Mac OS X is not supported and %s will not work properly on this platform. ' .
244
+                    'Use it at your own risk! ',
245
+                    [$this->defaults->getProductName()]
246
+                ),
247
+                'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.'),
248
+            ];
249
+        }
250
+
251
+        if ($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
252
+            $errors[] = [
253
+                'error' => $this->l10n->t(
254
+                    'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
255
+                    'This will lead to problems with files over 4 GB and is highly discouraged.',
256
+                    [$this->defaults->getProductName()]
257
+                ),
258
+                'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.'),
259
+            ];
260
+        }
261
+
262
+        return [
263
+            'hasSQLite' => isset($databases['sqlite']),
264
+            'hasMySQL' => isset($databases['mysql']),
265
+            'hasPostgreSQL' => isset($databases['pgsql']),
266
+            'hasOracle' => isset($databases['oci']),
267
+            'databases' => $databases,
268
+            'directory' => $dataDir,
269
+            'htaccessWorking' => $htAccessWorking,
270
+            'errors' => $errors,
271
+        ];
272
+    }
273
+
274
+    /**
275
+     * @param $options
276
+     * @return array
277
+     */
278
+    public function install($options) {
279
+        $l = $this->l10n;
280
+
281
+        $error = [];
282
+        $dbType = $options['dbtype'];
283
+
284
+        if (empty($options['adminlogin'])) {
285
+            $error[] = $l->t('Set an admin username.');
286
+        }
287
+        if (empty($options['adminpass'])) {
288
+            $error[] = $l->t('Set an admin password.');
289
+        }
290
+        if (empty($options['directory'])) {
291
+            $options['directory'] = \OC::$SERVERROOT . "/data";
292
+        }
293
+
294
+        if (!isset(self::$dbSetupClasses[$dbType])) {
295
+            $dbType = 'sqlite';
296
+        }
297
+
298
+        $username = htmlspecialchars_decode($options['adminlogin']);
299
+        $password = htmlspecialchars_decode($options['adminpass']);
300
+        $dataDir = htmlspecialchars_decode($options['directory']);
301
+
302
+        $class = self::$dbSetupClasses[$dbType];
303
+        /** @var \OC\Setup\AbstractDatabase $dbSetup */
304
+        $dbSetup = new $class($l, $this->config, $this->logger, $this->random);
305
+        $error = array_merge($error, $dbSetup->validate($options));
306
+
307
+        // validate the data directory
308
+        if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) {
309
+            $error[] = $l->t("Cannot create or write into the data directory %s", [$dataDir]);
310
+        }
311
+
312
+        if (!empty($error)) {
313
+            return $error;
314
+        }
315
+
316
+        $request = \OC::$server->getRequest();
317
+
318
+        //no errors, good
319
+        if (isset($options['trusted_domains'])
320
+            && is_array($options['trusted_domains'])) {
321
+            $trustedDomains = $options['trusted_domains'];
322
+        } else {
323
+            $trustedDomains = [$request->getInsecureServerHost()];
324
+        }
325
+
326
+        //use sqlite3 when available, otherwise sqlite2 will be used.
327
+        if ($dbType === 'sqlite' && class_exists('SQLite3')) {
328
+            $dbType = 'sqlite3';
329
+        }
330
+
331
+        //generate a random salt that is used to salt the local user passwords
332
+        $salt = $this->random->generate(30);
333
+        // generate a secret
334
+        $secret = $this->random->generate(48);
335
+
336
+        //write the config file
337
+        $newConfigValues = [
338
+            'passwordsalt' => $salt,
339
+            'secret' => $secret,
340
+            'trusted_domains' => $trustedDomains,
341
+            'datadirectory' => $dataDir,
342
+            'dbtype' => $dbType,
343
+            'version' => implode('.', \OCP\Util::getVersion()),
344
+        ];
345
+
346
+        if ($this->config->getValue('overwrite.cli.url', null) === null) {
347
+            $newConfigValues['overwrite.cli.url'] = $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT;
348
+        }
349
+
350
+        $this->config->setValues($newConfigValues);
351
+
352
+        $dbSetup->initialize($options);
353
+        try {
354
+            $dbSetup->setupDatabase($username);
355
+        } catch (\OC\DatabaseSetupException $e) {
356
+            $error[] = [
357
+                'error' => $e->getMessage(),
358
+                'exception' => $e,
359
+                'hint' => $e->getHint(),
360
+            ];
361
+            return $error;
362
+        } catch (Exception $e) {
363
+            $error[] = [
364
+                'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
365
+                'exception' => $e,
366
+                'hint' => '',
367
+            ];
368
+            return $error;
369
+        }
370
+        try {
371
+            // apply necessary migrations
372
+            $dbSetup->runMigrations();
373
+        } catch (Exception $e) {
374
+            $error[] = [
375
+                'error' => 'Error while trying to initialise the database: ' . $e->getMessage(),
376
+                'exception' => $e,
377
+                'hint' => '',
378
+            ];
379
+            return $error;
380
+        }
381
+
382
+        //create the user and group
383
+        $user = null;
384
+        try {
385
+            $user = \OC::$server->getUserManager()->createUser($username, $password);
386
+            if (!$user) {
387
+                $error[] = "User <$username> could not be created.";
388
+            }
389
+        } catch (Exception $exception) {
390
+            $error[] = $exception->getMessage();
391
+        }
392
+
393
+        if (empty($error)) {
394
+            $config = \OC::$server->getConfig();
395
+            $config->setAppValue('core', 'installedat', microtime(true));
396
+            $config->setAppValue('core', 'lastupdatedat', microtime(true));
397
+            $config->setAppValue('core', 'vendor', $this->getVendor());
398
+
399
+            $group = \OC::$server->getGroupManager()->createGroup('admin');
400
+            if ($group instanceof IGroup) {
401
+                $group->addUser($user);
402
+            }
403
+
404
+            // Install shipped apps and specified app bundles
405
+            Installer::installShippedApps();
406
+            $bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
407
+            $defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
408
+            foreach ($defaultInstallationBundles as $bundle) {
409
+                try {
410
+                    $this->installer->installAppBundle($bundle);
411
+                } catch (Exception $e) {
412
+                }
413
+            }
414
+
415
+            // create empty file in data dir, so we can later find
416
+            // out that this is indeed an ownCloud data directory
417
+            file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
418
+
419
+            // Update .htaccess files
420
+            self::updateHtaccess();
421
+            self::protectDataDirectory();
422
+
423
+            self::installBackgroundJobs();
424
+
425
+            //and we are done
426
+            $config->setSystemValue('installed', true);
427
+
428
+            $bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
429
+            $bootstrapCoordinator->runInitialRegistration();
430
+
431
+            // Create a session token for the newly created user
432
+            // The token provider requires a working db, so it's not injected on setup
433
+            /* @var $userSession User\Session */
434
+            $userSession = \OC::$server->getUserSession();
435
+            $provider = \OC::$server->query(PublicKeyTokenProvider::class);
436
+            $userSession->setTokenProvider($provider);
437
+            $userSession->login($username, $password);
438
+            $userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
439
+
440
+            $session = $userSession->getSession();
441
+            $session->set('last-password-confirm', \OC::$server->query(ITimeFactory::class)->getTime());
442
+
443
+            // Set email for admin
444
+            if (!empty($options['adminemail'])) {
445
+                $user->setSystemEMailAddress($options['adminemail']);
446
+            }
447
+        }
448
+
449
+        return $error;
450
+    }
451
+
452
+    public static function installBackgroundJobs() {
453
+        $jobList = \OC::$server->getJobList();
454
+        $jobList->add(TokenCleanupJob::class);
455
+        $jobList->add(Rotate::class);
456
+        $jobList->add(BackgroundCleanupJob::class);
457
+    }
458
+
459
+    /**
460
+     * @return string Absolute path to htaccess
461
+     */
462
+    private function pathToHtaccess() {
463
+        return \OC::$SERVERROOT . '/.htaccess';
464
+    }
465
+
466
+    /**
467
+     * Find webroot from config
468
+     *
469
+     * @param SystemConfig $config
470
+     * @return string
471
+     * @throws InvalidArgumentException when invalid value for overwrite.cli.url
472
+     */
473
+    private static function findWebRoot(SystemConfig $config): string {
474
+        // For CLI read the value from overwrite.cli.url
475
+        if (\OC::$CLI) {
476
+            $webRoot = $config->getValue('overwrite.cli.url', '');
477
+            if ($webRoot === '') {
478
+                throw new InvalidArgumentException('overwrite.cli.url is empty');
479
+            }
480
+            if (!filter_var($webRoot, FILTER_VALIDATE_URL)) {
481
+                throw new InvalidArgumentException('invalid value for overwrite.cli.url');
482
+            }
483
+            $webRoot = rtrim((parse_url($webRoot, PHP_URL_PATH) ?? ''), '/');
484
+        } else {
485
+            $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
486
+        }
487
+
488
+        return $webRoot;
489
+    }
490
+
491
+    /**
492
+     * Append the correct ErrorDocument path for Apache hosts
493
+     *
494
+     * @return bool True when success, False otherwise
495
+     * @throws \OCP\AppFramework\QueryException
496
+     */
497
+    public static function updateHtaccess() {
498
+        $config = \OC::$server->getSystemConfig();
499
+
500
+        try {
501
+            $webRoot = self::findWebRoot($config);
502
+        } catch (InvalidArgumentException $e) {
503
+            return false;
504
+        }
505
+
506
+        $setupHelper = new \OC\Setup(
507
+            $config,
508
+            \OC::$server->get(IniGetWrapper::class),
509
+            \OC::$server->getL10N('lib'),
510
+            \OC::$server->query(Defaults::class),
511
+            \OC::$server->get(LoggerInterface::class),
512
+            \OC::$server->getSecureRandom(),
513
+            \OC::$server->query(Installer::class)
514
+        );
515
+
516
+        $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
517
+        $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
518
+        $htaccessContent = explode($content, $htaccessContent, 2)[0];
519
+
520
+        //custom 403 error page
521
+        $content .= "\nErrorDocument 403 " . $webRoot . '/';
522
+
523
+        //custom 404 error page
524
+        $content .= "\nErrorDocument 404 " . $webRoot . '/';
525
+
526
+        // Add rewrite rules if the RewriteBase is configured
527
+        $rewriteBase = $config->getValue('htaccess.RewriteBase', '');
528
+        if ($rewriteBase !== '') {
529
+            $content .= "\n<IfModule mod_rewrite.c>";
530
+            $content .= "\n  Options -MultiViews";
531
+            $content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
532
+            $content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
533
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff2?|ico|jpg|jpeg|map|webm|mp4|mp3|ogg|wav|wasm|tflite)$";
534
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update\\.php";
535
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/img/(favicon\\.ico|manifest\\.json)$";
536
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/(cron|public|remote|status)\\.php";
537
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v(1|2)\\.php";
538
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots\\.txt";
539
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/(ocm-provider|ocs-provider|updater)/";
540
+            $content .= "\n  RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
541
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/richdocumentscode(_arm64)?/proxy.php$";
542
+            $content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
543
+            $content .= "\n  RewriteBase " . $rewriteBase;
544
+            $content .= "\n  <IfModule mod_env.c>";
545
+            $content .= "\n    SetEnv front_controller_active true";
546
+            $content .= "\n    <IfModule mod_dir.c>";
547
+            $content .= "\n      DirectorySlash off";
548
+            $content .= "\n    </IfModule>";
549
+            $content .= "\n  </IfModule>";
550
+            $content .= "\n</IfModule>";
551
+        }
552
+
553
+        if ($content !== '') {
554
+            //suppress errors in case we don't have permissions for it
555
+            return (bool)@file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent . $content . "\n");
556
+        }
557
+
558
+        return false;
559
+    }
560
+
561
+    public static function protectDataDirectory() {
562
+        //Require all denied
563
+        $now = date('Y-m-d H:i:s');
564
+        $content = "# Generated by Nextcloud on $now\n";
565
+        $content .= "# Section for Apache 2.4 to 2.6\n";
566
+        $content .= "<IfModule mod_authz_core.c>\n";
567
+        $content .= "  Require all denied\n";
568
+        $content .= "</IfModule>\n";
569
+        $content .= "<IfModule mod_access_compat.c>\n";
570
+        $content .= "  Order Allow,Deny\n";
571
+        $content .= "  Deny from all\n";
572
+        $content .= "  Satisfy All\n";
573
+        $content .= "</IfModule>\n\n";
574
+        $content .= "# Section for Apache 2.2\n";
575
+        $content .= "<IfModule !mod_authz_core.c>\n";
576
+        $content .= "  <IfModule !mod_access_compat.c>\n";
577
+        $content .= "    <IfModule mod_authz_host.c>\n";
578
+        $content .= "      Order Allow,Deny\n";
579
+        $content .= "      Deny from all\n";
580
+        $content .= "    </IfModule>\n";
581
+        $content .= "    Satisfy All\n";
582
+        $content .= "  </IfModule>\n";
583
+        $content .= "</IfModule>\n\n";
584
+        $content .= "# Section for Apache 2.2 to 2.6\n";
585
+        $content .= "<IfModule mod_autoindex.c>\n";
586
+        $content .= "  IndexIgnore *\n";
587
+        $content .= "</IfModule>";
588
+
589
+        $baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
590
+        file_put_contents($baseDir . '/.htaccess', $content);
591
+        file_put_contents($baseDir . '/index.html', '');
592
+    }
593
+
594
+    /**
595
+     * Return vendor from which this version was published
596
+     *
597
+     * @return string Get the vendor
598
+     *
599
+     * Copy of \OC\Updater::getVendor()
600
+     */
601
+    private function getVendor() {
602
+        // this should really be a JSON file
603
+        require \OC::$SERVERROOT . '/version.php';
604
+        /** @var string $vendor */
605
+        return (string)$vendor;
606
+    }
607 607
 }
Please login to merge, or discard this patch.
lib/private/Repair/NC24/AddTokenCleanupJob.php 1 patch
Indentation   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -31,17 +31,17 @@
 block discarded – undo
31 31
 use OCP\Migration\IRepairStep;
32 32
 
33 33
 class AddTokenCleanupJob implements IRepairStep {
34
-	private IJobList $jobList;
34
+    private IJobList $jobList;
35 35
 
36
-	public function __construct(IJobList $jobList) {
37
-		$this->jobList = $jobList;
38
-	}
36
+    public function __construct(IJobList $jobList) {
37
+        $this->jobList = $jobList;
38
+    }
39 39
 
40
-	public function getName(): string {
41
-		return 'Add token cleanup job';
42
-	}
40
+    public function getName(): string {
41
+        return 'Add token cleanup job';
42
+    }
43 43
 
44
-	public function run(IOutput $output) {
45
-		$this->jobList->add(TokenCleanupJob::class);
46
-	}
44
+    public function run(IOutput $output) {
45
+        $this->jobList->add(TokenCleanupJob::class);
46
+    }
47 47
 }
Please login to merge, or discard this patch.
lib/private/Repair.php 1 patch
Indentation   +195 added lines, -195 removed lines patch added patch discarded remove patch
@@ -85,217 +85,217 @@
 block discarded – undo
85 85
 
86 86
 class Repair implements IOutput {
87 87
 
88
-	/** @var IRepairStep[] */
89
-	private $repairSteps;
88
+    /** @var IRepairStep[] */
89
+    private $repairSteps;
90 90
 
91
-	/** @var EventDispatcherInterface */
92
-	private $dispatcher;
91
+    /** @var EventDispatcherInterface */
92
+    private $dispatcher;
93 93
 
94
-	/** @var string */
95
-	private $currentStep;
94
+    /** @var string */
95
+    private $currentStep;
96 96
 
97
-	private LoggerInterface $logger;
97
+    private LoggerInterface $logger;
98 98
 
99
-	/**
100
-	 * Creates a new repair step runner
101
-	 *
102
-	 * @param IRepairStep[] $repairSteps array of RepairStep instances
103
-	 */
104
-	public function __construct(array $repairSteps, EventDispatcherInterface $dispatcher, LoggerInterface $logger) {
105
-		$this->repairSteps = $repairSteps;
106
-		$this->dispatcher = $dispatcher;
107
-		$this->logger = $logger;
108
-	}
99
+    /**
100
+     * Creates a new repair step runner
101
+     *
102
+     * @param IRepairStep[] $repairSteps array of RepairStep instances
103
+     */
104
+    public function __construct(array $repairSteps, EventDispatcherInterface $dispatcher, LoggerInterface $logger) {
105
+        $this->repairSteps = $repairSteps;
106
+        $this->dispatcher = $dispatcher;
107
+        $this->logger = $logger;
108
+    }
109 109
 
110
-	/**
111
-	 * Run a series of repair steps for common problems
112
-	 */
113
-	public function run() {
114
-		if (count($this->repairSteps) === 0) {
115
-			$this->emit('\OC\Repair', 'info', ['No repair steps available']);
110
+    /**
111
+     * Run a series of repair steps for common problems
112
+     */
113
+    public function run() {
114
+        if (count($this->repairSteps) === 0) {
115
+            $this->emit('\OC\Repair', 'info', ['No repair steps available']);
116 116
 
117
-			return;
118
-		}
119
-		// run each repair step
120
-		foreach ($this->repairSteps as $step) {
121
-			$this->currentStep = $step->getName();
122
-			$this->emit('\OC\Repair', 'step', [$this->currentStep]);
123
-			try {
124
-				$step->run($this);
125
-			} catch (\Exception $e) {
126
-				$this->logger->error("Exception while executing repair step " . $step->getName(), ['exception' => $e]);
127
-				$this->emit('\OC\Repair', 'error', [$e->getMessage()]);
128
-			}
129
-		}
130
-	}
117
+            return;
118
+        }
119
+        // run each repair step
120
+        foreach ($this->repairSteps as $step) {
121
+            $this->currentStep = $step->getName();
122
+            $this->emit('\OC\Repair', 'step', [$this->currentStep]);
123
+            try {
124
+                $step->run($this);
125
+            } catch (\Exception $e) {
126
+                $this->logger->error("Exception while executing repair step " . $step->getName(), ['exception' => $e]);
127
+                $this->emit('\OC\Repair', 'error', [$e->getMessage()]);
128
+            }
129
+        }
130
+    }
131 131
 
132
-	/**
133
-	 * Add repair step
134
-	 *
135
-	 * @param IRepairStep|string $repairStep repair step
136
-	 * @throws \Exception
137
-	 */
138
-	public function addStep($repairStep) {
139
-		if (is_string($repairStep)) {
140
-			try {
141
-				$s = \OC::$server->query($repairStep);
142
-			} catch (QueryException $e) {
143
-				if (class_exists($repairStep)) {
144
-					try {
145
-						// Last resort: hope there are no constructor arguments
146
-						$s = new $repairStep();
147
-					} catch (Throwable $inner) {
148
-						// Well, it was worth a try
149
-						throw new \Exception("Repair step '$repairStep' can't be instantiated: " . $e->getMessage(), 0, $e);
150
-					}
151
-				} else {
152
-					throw new \Exception("Repair step '$repairStep' is unknown", 0, $e);
153
-				}
154
-			}
132
+    /**
133
+     * Add repair step
134
+     *
135
+     * @param IRepairStep|string $repairStep repair step
136
+     * @throws \Exception
137
+     */
138
+    public function addStep($repairStep) {
139
+        if (is_string($repairStep)) {
140
+            try {
141
+                $s = \OC::$server->query($repairStep);
142
+            } catch (QueryException $e) {
143
+                if (class_exists($repairStep)) {
144
+                    try {
145
+                        // Last resort: hope there are no constructor arguments
146
+                        $s = new $repairStep();
147
+                    } catch (Throwable $inner) {
148
+                        // Well, it was worth a try
149
+                        throw new \Exception("Repair step '$repairStep' can't be instantiated: " . $e->getMessage(), 0, $e);
150
+                    }
151
+                } else {
152
+                    throw new \Exception("Repair step '$repairStep' is unknown", 0, $e);
153
+                }
154
+            }
155 155
 
156
-			if ($s instanceof IRepairStep) {
157
-				$this->repairSteps[] = $s;
158
-			} else {
159
-				throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
160
-			}
161
-		} else {
162
-			$this->repairSteps[] = $repairStep;
163
-		}
164
-	}
156
+            if ($s instanceof IRepairStep) {
157
+                $this->repairSteps[] = $s;
158
+            } else {
159
+                throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
160
+            }
161
+        } else {
162
+            $this->repairSteps[] = $repairStep;
163
+        }
164
+    }
165 165
 
166
-	/**
167
-	 * Returns the default repair steps to be run on the
168
-	 * command line or after an upgrade.
169
-	 *
170
-	 * @return IRepairStep[]
171
-	 */
172
-	public static function getRepairSteps() {
173
-		return [
174
-			new Collation(\OC::$server->getConfig(), \OC::$server->get(LoggerInterface::class), \OC::$server->getDatabaseConnection(), false),
175
-			new RepairMimeTypes(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
176
-			new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
177
-			new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
178
-			new MoveUpdaterStepFile(\OC::$server->getConfig()),
179
-			new MoveAvatars(
180
-				\OC::$server->getJobList(),
181
-				\OC::$server->getConfig()
182
-			),
183
-			new CleanPreviews(
184
-				\OC::$server->getJobList(),
185
-				\OC::$server->getUserManager(),
186
-				\OC::$server->getConfig()
187
-			),
188
-			new MigrateOauthTables(\OC::$server->get(Connection::class)),
189
-			new FixMountStorages(\OC::$server->getDatabaseConnection()),
190
-			new UpdateLanguageCodes(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
191
-			new InstallCoreBundle(
192
-				\OC::$server->query(BundleFetcher::class),
193
-				\OC::$server->getConfig(),
194
-				\OC::$server->query(Installer::class)
195
-			),
196
-			new AddLogRotateJob(\OC::$server->getJobList()),
197
-			new ClearFrontendCaches(\OC::$server->getMemCacheFactory(), \OC::$server->query(JSCombiner::class)),
198
-			new ClearGeneratedAvatarCache(\OC::$server->getConfig(), \OC::$server->query(AvatarManager::class)),
199
-			new AddPreviewBackgroundCleanupJob(\OC::$server->getJobList()),
200
-			new AddCleanupUpdaterBackupsJob(\OC::$server->getJobList()),
201
-			new CleanupCardDAVPhotoCache(\OC::$server->getConfig(), \OC::$server->getAppDataDir('dav-photocache'), \OC::$server->get(LoggerInterface::class)),
202
-			new AddClenupLoginFlowV2BackgroundJob(\OC::$server->getJobList()),
203
-			new RemoveLinkShares(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig(), \OC::$server->getGroupManager(), \OC::$server->getNotificationManager(), \OC::$server->query(ITimeFactory::class)),
204
-			new ClearCollectionsAccessCache(\OC::$server->getConfig(), \OC::$server->query(IManager::class)),
205
-			\OC::$server->query(ResetGeneratedAvatarFlag::class),
206
-			\OC::$server->query(EncryptionLegacyCipher::class),
207
-			\OC::$server->query(EncryptionMigration::class),
208
-			\OC::$server->get(ShippedDashboardEnable::class),
209
-			\OC::$server->get(AddBruteForceCleanupJob::class),
210
-			\OC::$server->get(AddCheckForUserCertificatesJob::class),
211
-			\OC::$server->get(RepairDavShares::class),
212
-			\OC::$server->get(LookupServerSendCheck::class),
213
-			\OC::$server->get(AddTokenCleanupJob::class),
214
-		];
215
-	}
166
+    /**
167
+     * Returns the default repair steps to be run on the
168
+     * command line or after an upgrade.
169
+     *
170
+     * @return IRepairStep[]
171
+     */
172
+    public static function getRepairSteps() {
173
+        return [
174
+            new Collation(\OC::$server->getConfig(), \OC::$server->get(LoggerInterface::class), \OC::$server->getDatabaseConnection(), false),
175
+            new RepairMimeTypes(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
176
+            new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
177
+            new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
178
+            new MoveUpdaterStepFile(\OC::$server->getConfig()),
179
+            new MoveAvatars(
180
+                \OC::$server->getJobList(),
181
+                \OC::$server->getConfig()
182
+            ),
183
+            new CleanPreviews(
184
+                \OC::$server->getJobList(),
185
+                \OC::$server->getUserManager(),
186
+                \OC::$server->getConfig()
187
+            ),
188
+            new MigrateOauthTables(\OC::$server->get(Connection::class)),
189
+            new FixMountStorages(\OC::$server->getDatabaseConnection()),
190
+            new UpdateLanguageCodes(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
191
+            new InstallCoreBundle(
192
+                \OC::$server->query(BundleFetcher::class),
193
+                \OC::$server->getConfig(),
194
+                \OC::$server->query(Installer::class)
195
+            ),
196
+            new AddLogRotateJob(\OC::$server->getJobList()),
197
+            new ClearFrontendCaches(\OC::$server->getMemCacheFactory(), \OC::$server->query(JSCombiner::class)),
198
+            new ClearGeneratedAvatarCache(\OC::$server->getConfig(), \OC::$server->query(AvatarManager::class)),
199
+            new AddPreviewBackgroundCleanupJob(\OC::$server->getJobList()),
200
+            new AddCleanupUpdaterBackupsJob(\OC::$server->getJobList()),
201
+            new CleanupCardDAVPhotoCache(\OC::$server->getConfig(), \OC::$server->getAppDataDir('dav-photocache'), \OC::$server->get(LoggerInterface::class)),
202
+            new AddClenupLoginFlowV2BackgroundJob(\OC::$server->getJobList()),
203
+            new RemoveLinkShares(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig(), \OC::$server->getGroupManager(), \OC::$server->getNotificationManager(), \OC::$server->query(ITimeFactory::class)),
204
+            new ClearCollectionsAccessCache(\OC::$server->getConfig(), \OC::$server->query(IManager::class)),
205
+            \OC::$server->query(ResetGeneratedAvatarFlag::class),
206
+            \OC::$server->query(EncryptionLegacyCipher::class),
207
+            \OC::$server->query(EncryptionMigration::class),
208
+            \OC::$server->get(ShippedDashboardEnable::class),
209
+            \OC::$server->get(AddBruteForceCleanupJob::class),
210
+            \OC::$server->get(AddCheckForUserCertificatesJob::class),
211
+            \OC::$server->get(RepairDavShares::class),
212
+            \OC::$server->get(LookupServerSendCheck::class),
213
+            \OC::$server->get(AddTokenCleanupJob::class),
214
+        ];
215
+    }
216 216
 
217
-	/**
218
-	 * Returns expensive repair steps to be run on the
219
-	 * command line with a special option.
220
-	 *
221
-	 * @return IRepairStep[]
222
-	 */
223
-	public static function getExpensiveRepairSteps() {
224
-		return [
225
-			new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager()),
226
-			\OC::$server->get(ValidatePhoneNumber::class),
227
-		];
228
-	}
217
+    /**
218
+     * Returns expensive repair steps to be run on the
219
+     * command line with a special option.
220
+     *
221
+     * @return IRepairStep[]
222
+     */
223
+    public static function getExpensiveRepairSteps() {
224
+        return [
225
+            new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager()),
226
+            \OC::$server->get(ValidatePhoneNumber::class),
227
+        ];
228
+    }
229 229
 
230
-	/**
231
-	 * Returns the repair steps to be run before an
232
-	 * upgrade.
233
-	 *
234
-	 * @return IRepairStep[]
235
-	 */
236
-	public static function getBeforeUpgradeRepairSteps() {
237
-		/** @var Connection $connection */
238
-		$connection = \OC::$server->get(Connection::class);
239
-		/** @var ConnectionAdapter $connectionAdapter */
240
-		$connectionAdapter = \OC::$server->get(ConnectionAdapter::class);
241
-		$config = \OC::$server->getConfig();
242
-		$steps = [
243
-			new Collation(\OC::$server->getConfig(), \OC::$server->get(LoggerInterface::class), $connectionAdapter, true),
244
-			new SqliteAutoincrement($connection),
245
-			new SaveAccountsTableData($connectionAdapter, $config),
246
-			new DropAccountTermsTable($connectionAdapter),
247
-		];
230
+    /**
231
+     * Returns the repair steps to be run before an
232
+     * upgrade.
233
+     *
234
+     * @return IRepairStep[]
235
+     */
236
+    public static function getBeforeUpgradeRepairSteps() {
237
+        /** @var Connection $connection */
238
+        $connection = \OC::$server->get(Connection::class);
239
+        /** @var ConnectionAdapter $connectionAdapter */
240
+        $connectionAdapter = \OC::$server->get(ConnectionAdapter::class);
241
+        $config = \OC::$server->getConfig();
242
+        $steps = [
243
+            new Collation(\OC::$server->getConfig(), \OC::$server->get(LoggerInterface::class), $connectionAdapter, true),
244
+            new SqliteAutoincrement($connection),
245
+            new SaveAccountsTableData($connectionAdapter, $config),
246
+            new DropAccountTermsTable($connectionAdapter),
247
+        ];
248 248
 
249
-		return $steps;
250
-	}
249
+        return $steps;
250
+    }
251 251
 
252
-	/**
253
-	 * @param string $scope
254
-	 * @param string $method
255
-	 * @param array $arguments
256
-	 */
257
-	public function emit($scope, $method, array $arguments = []) {
258
-		if (!is_null($this->dispatcher)) {
259
-			$this->dispatcher->dispatch("$scope::$method",
260
-				new GenericEvent("$scope::$method", $arguments));
261
-		}
262
-	}
252
+    /**
253
+     * @param string $scope
254
+     * @param string $method
255
+     * @param array $arguments
256
+     */
257
+    public function emit($scope, $method, array $arguments = []) {
258
+        if (!is_null($this->dispatcher)) {
259
+            $this->dispatcher->dispatch("$scope::$method",
260
+                new GenericEvent("$scope::$method", $arguments));
261
+        }
262
+    }
263 263
 
264
-	public function info($string) {
265
-		// for now just emit as we did in the past
266
-		$this->emit('\OC\Repair', 'info', [$string]);
267
-	}
264
+    public function info($string) {
265
+        // for now just emit as we did in the past
266
+        $this->emit('\OC\Repair', 'info', [$string]);
267
+    }
268 268
 
269
-	/**
270
-	 * @param string $message
271
-	 */
272
-	public function warning($message) {
273
-		// for now just emit as we did in the past
274
-		$this->emit('\OC\Repair', 'warning', [$message]);
275
-	}
269
+    /**
270
+     * @param string $message
271
+     */
272
+    public function warning($message) {
273
+        // for now just emit as we did in the past
274
+        $this->emit('\OC\Repair', 'warning', [$message]);
275
+    }
276 276
 
277
-	/**
278
-	 * @param int $max
279
-	 */
280
-	public function startProgress($max = 0) {
281
-		// for now just emit as we did in the past
282
-		$this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
283
-	}
277
+    /**
278
+     * @param int $max
279
+     */
280
+    public function startProgress($max = 0) {
281
+        // for now just emit as we did in the past
282
+        $this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
283
+    }
284 284
 
285
-	/**
286
-	 * @param int $step
287
-	 * @param string $description
288
-	 */
289
-	public function advance($step = 1, $description = '') {
290
-		// for now just emit as we did in the past
291
-		$this->emit('\OC\Repair', 'advance', [$step, $description]);
292
-	}
285
+    /**
286
+     * @param int $step
287
+     * @param string $description
288
+     */
289
+    public function advance($step = 1, $description = '') {
290
+        // for now just emit as we did in the past
291
+        $this->emit('\OC\Repair', 'advance', [$step, $description]);
292
+    }
293 293
 
294
-	/**
295
-	 * @param int $max
296
-	 */
297
-	public function finishProgress() {
298
-		// for now just emit as we did in the past
299
-		$this->emit('\OC\Repair', 'finishProgress', []);
300
-	}
294
+    /**
295
+     * @param int $max
296
+     */
297
+    public function finishProgress() {
298
+        // for now just emit as we did in the past
299
+        $this->emit('\OC\Repair', 'finishProgress', []);
300
+    }
301 301
 }
Please login to merge, or discard this patch.