Passed
Push — master ( 730001...fe2e0a )
by Maxence
19:02 queued 15s
created
public.php 1 patch
Indentation   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -33,62 +33,62 @@
 block discarded – undo
33 33
 require_once __DIR__ . '/lib/versioncheck.php';
34 34
 
35 35
 try {
36
-	require_once __DIR__ . '/lib/base.php';
37
-	if (\OCP\Util::needUpgrade()) {
38
-		// since the behavior of apps or remotes are unpredictable during
39
-		// an upgrade, return a 503 directly
40
-		OC_Template::printErrorPage('Service unavailable', '', 503);
41
-		exit;
42
-	}
36
+    require_once __DIR__ . '/lib/base.php';
37
+    if (\OCP\Util::needUpgrade()) {
38
+        // since the behavior of apps or remotes are unpredictable during
39
+        // an upgrade, return a 503 directly
40
+        OC_Template::printErrorPage('Service unavailable', '', 503);
41
+        exit;
42
+    }
43 43
 
44
-	OC::checkMaintenanceMode(\OC::$server->get(\OC\SystemConfig::class));
45
-	$request = \OC::$server->getRequest();
46
-	$pathInfo = $request->getPathInfo();
44
+    OC::checkMaintenanceMode(\OC::$server->get(\OC\SystemConfig::class));
45
+    $request = \OC::$server->getRequest();
46
+    $pathInfo = $request->getPathInfo();
47 47
 
48
-	if (!$pathInfo && $request->getParam('service', '') === '') {
49
-		http_response_code(404);
50
-		exit;
51
-	} elseif ($request->getParam('service', '')) {
52
-		$service = $request->getParam('service', '');
53
-	} else {
54
-		$pathInfo = trim($pathInfo, '/');
55
-		[$service] = explode('/', $pathInfo);
56
-	}
57
-	$file = \OC::$server->getConfig()->getAppValue('core', 'public_' . strip_tags($service));
58
-	if ($file === '') {
59
-		http_response_code(404);
60
-		exit;
61
-	}
48
+    if (!$pathInfo && $request->getParam('service', '') === '') {
49
+        http_response_code(404);
50
+        exit;
51
+    } elseif ($request->getParam('service', '')) {
52
+        $service = $request->getParam('service', '');
53
+    } else {
54
+        $pathInfo = trim($pathInfo, '/');
55
+        [$service] = explode('/', $pathInfo);
56
+    }
57
+    $file = \OC::$server->getConfig()->getAppValue('core', 'public_' . strip_tags($service));
58
+    if ($file === '') {
59
+        http_response_code(404);
60
+        exit;
61
+    }
62 62
 
63
-	$parts = explode('/', $file, 2);
64
-	$app = $parts[0];
63
+    $parts = explode('/', $file, 2);
64
+    $app = $parts[0];
65 65
 
66
-	// Load all required applications
67
-	\OC::$REQUESTEDAPP = $app;
68
-	OC_App::loadApps(['authentication']);
69
-	OC_App::loadApps(['extended_authentication']);
70
-	OC_App::loadApps(['filesystem', 'logging']);
66
+    // Load all required applications
67
+    \OC::$REQUESTEDAPP = $app;
68
+    OC_App::loadApps(['authentication']);
69
+    OC_App::loadApps(['extended_authentication']);
70
+    OC_App::loadApps(['filesystem', 'logging']);
71 71
 
72
-	if (!\OC::$server->getAppManager()->isInstalled($app)) {
73
-		http_response_code(404);
74
-		exit;
75
-	}
76
-	OC_App::loadApp($app);
77
-	OC_User::setIncognitoMode(true);
72
+    if (!\OC::$server->getAppManager()->isInstalled($app)) {
73
+        http_response_code(404);
74
+        exit;
75
+    }
76
+    OC_App::loadApp($app);
77
+    OC_User::setIncognitoMode(true);
78 78
 
79
-	$baseuri = OC::$WEBROOT . '/public.php/' . $service . '/';
79
+    $baseuri = OC::$WEBROOT . '/public.php/' . $service . '/';
80 80
 
81
-	require_once OC_App::getAppPath($app) . '/' . $parts[1];
81
+    require_once OC_App::getAppPath($app) . '/' . $parts[1];
82 82
 } catch (Exception $ex) {
83
-	$status = 500;
84
-	if ($ex instanceof \OC\ServiceUnavailableException) {
85
-		$status = 503;
86
-	}
87
-	//show the user a detailed error page
88
-	\OC::$server->getLogger()->logException($ex, ['app' => 'public']);
89
-	OC_Template::printExceptionErrorPage($ex, $status);
83
+    $status = 500;
84
+    if ($ex instanceof \OC\ServiceUnavailableException) {
85
+        $status = 503;
86
+    }
87
+    //show the user a detailed error page
88
+    \OC::$server->getLogger()->logException($ex, ['app' => 'public']);
89
+    OC_Template::printExceptionErrorPage($ex, $status);
90 90
 } catch (Error $ex) {
91
-	//show the user a detailed error page
92
-	\OC::$server->getLogger()->logException($ex, ['app' => 'public']);
93
-	OC_Template::printExceptionErrorPage($ex, 500);
91
+    //show the user a detailed error page
92
+    \OC::$server->getLogger()->logException($ex, ['app' => 'public']);
93
+    OC_Template::printExceptionErrorPage($ex, 500);
94 94
 }
Please login to merge, or discard this patch.
remote.php 1 patch
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -50,47 +50,47 @@  discard block
 block discarded – undo
50 50
  * @param Exception|Error $e
51 51
  */
52 52
 function handleException($e) {
53
-	try {
54
-		$request = \OC::$server->getRequest();
55
-		// in case the request content type is text/xml - we assume it's a WebDAV request
56
-		$isXmlContentType = strpos($request->getHeader('Content-Type'), 'text/xml');
57
-		if ($isXmlContentType === 0) {
58
-			// fire up a simple server to properly process the exception
59
-			$server = new Server();
60
-			if (!($e instanceof RemoteException)) {
61
-				// we shall not log on RemoteException
62
-				$server->addPlugin(new ExceptionLoggerPlugin('webdav', \OC::$server->get(LoggerInterface::class)));
63
-			}
64
-			$server->on('beforeMethod:*', function () use ($e) {
65
-				if ($e instanceof RemoteException) {
66
-					switch ($e->getCode()) {
67
-						case 503:
68
-							throw new ServiceUnavailable($e->getMessage());
69
-						case 404:
70
-							throw new \Sabre\DAV\Exception\NotFound($e->getMessage());
71
-					}
72
-				}
73
-				$class = get_class($e);
74
-				$msg = $e->getMessage();
75
-				throw new ServiceUnavailable("$class: $msg");
76
-			});
77
-			$server->exec();
78
-		} else {
79
-			$statusCode = 500;
80
-			if ($e instanceof \OC\ServiceUnavailableException) {
81
-				$statusCode = 503;
82
-			}
83
-			if ($e instanceof RemoteException) {
84
-				// we shall not log on RemoteException
85
-				OC_Template::printErrorPage($e->getMessage(), '', $e->getCode());
86
-			} else {
87
-				\OC::$server->get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'remote','exception' => $e]);
88
-				OC_Template::printExceptionErrorPage($e, $statusCode);
89
-			}
90
-		}
91
-	} catch (\Exception $e) {
92
-		OC_Template::printExceptionErrorPage($e, 500);
93
-	}
53
+    try {
54
+        $request = \OC::$server->getRequest();
55
+        // in case the request content type is text/xml - we assume it's a WebDAV request
56
+        $isXmlContentType = strpos($request->getHeader('Content-Type'), 'text/xml');
57
+        if ($isXmlContentType === 0) {
58
+            // fire up a simple server to properly process the exception
59
+            $server = new Server();
60
+            if (!($e instanceof RemoteException)) {
61
+                // we shall not log on RemoteException
62
+                $server->addPlugin(new ExceptionLoggerPlugin('webdav', \OC::$server->get(LoggerInterface::class)));
63
+            }
64
+            $server->on('beforeMethod:*', function () use ($e) {
65
+                if ($e instanceof RemoteException) {
66
+                    switch ($e->getCode()) {
67
+                        case 503:
68
+                            throw new ServiceUnavailable($e->getMessage());
69
+                        case 404:
70
+                            throw new \Sabre\DAV\Exception\NotFound($e->getMessage());
71
+                    }
72
+                }
73
+                $class = get_class($e);
74
+                $msg = $e->getMessage();
75
+                throw new ServiceUnavailable("$class: $msg");
76
+            });
77
+            $server->exec();
78
+        } else {
79
+            $statusCode = 500;
80
+            if ($e instanceof \OC\ServiceUnavailableException) {
81
+                $statusCode = 503;
82
+            }
83
+            if ($e instanceof RemoteException) {
84
+                // we shall not log on RemoteException
85
+                OC_Template::printErrorPage($e->getMessage(), '', $e->getCode());
86
+            } else {
87
+                \OC::$server->get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'remote','exception' => $e]);
88
+                OC_Template::printExceptionErrorPage($e, $statusCode);
89
+            }
90
+        }
91
+    } catch (\Exception $e) {
92
+        OC_Template::printExceptionErrorPage($e, 500);
93
+    }
94 94
 }
95 95
 
96 96
 /**
@@ -98,80 +98,80 @@  discard block
 block discarded – undo
98 98
  * @return string
99 99
  */
100 100
 function resolveService($service) {
101
-	$services = [
102
-		'webdav' => 'dav/appinfo/v1/webdav.php',
103
-		'dav' => 'dav/appinfo/v2/remote.php',
104
-		'caldav' => 'dav/appinfo/v1/caldav.php',
105
-		'calendar' => 'dav/appinfo/v1/caldav.php',
106
-		'carddav' => 'dav/appinfo/v1/carddav.php',
107
-		'contacts' => 'dav/appinfo/v1/carddav.php',
108
-		'files' => 'dav/appinfo/v1/webdav.php',
109
-		'direct' => 'dav/appinfo/v2/direct.php',
110
-	];
111
-	if (isset($services[$service])) {
112
-		return $services[$service];
113
-	}
101
+    $services = [
102
+        'webdav' => 'dav/appinfo/v1/webdav.php',
103
+        'dav' => 'dav/appinfo/v2/remote.php',
104
+        'caldav' => 'dav/appinfo/v1/caldav.php',
105
+        'calendar' => 'dav/appinfo/v1/caldav.php',
106
+        'carddav' => 'dav/appinfo/v1/carddav.php',
107
+        'contacts' => 'dav/appinfo/v1/carddav.php',
108
+        'files' => 'dav/appinfo/v1/webdav.php',
109
+        'direct' => 'dav/appinfo/v2/direct.php',
110
+    ];
111
+    if (isset($services[$service])) {
112
+        return $services[$service];
113
+    }
114 114
 
115
-	return \OC::$server->getConfig()->getAppValue('core', 'remote_' . $service);
115
+    return \OC::$server->getConfig()->getAppValue('core', 'remote_' . $service);
116 116
 }
117 117
 
118 118
 try {
119
-	require_once __DIR__ . '/lib/base.php';
119
+    require_once __DIR__ . '/lib/base.php';
120 120
 
121
-	// All resources served via the DAV endpoint should have the strictest possible
122
-	// policy. Exempted from this is the SabreDAV browser plugin which overwrites
123
-	// this policy with a softer one if debug mode is enabled.
124
-	header("Content-Security-Policy: default-src 'none';");
121
+    // All resources served via the DAV endpoint should have the strictest possible
122
+    // policy. Exempted from this is the SabreDAV browser plugin which overwrites
123
+    // this policy with a softer one if debug mode is enabled.
124
+    header("Content-Security-Policy: default-src 'none';");
125 125
 
126
-	if (\OCP\Util::needUpgrade()) {
127
-		// since the behavior of apps or remotes are unpredictable during
128
-		// an upgrade, return a 503 directly
129
-		throw new RemoteException('Service unavailable', 503);
130
-	}
126
+    if (\OCP\Util::needUpgrade()) {
127
+        // since the behavior of apps or remotes are unpredictable during
128
+        // an upgrade, return a 503 directly
129
+        throw new RemoteException('Service unavailable', 503);
130
+    }
131 131
 
132
-	$request = \OC::$server->getRequest();
133
-	$pathInfo = $request->getPathInfo();
134
-	if ($pathInfo === false || $pathInfo === '') {
135
-		throw new RemoteException('Path not found', 404);
136
-	}
137
-	if (!$pos = strpos($pathInfo, '/', 1)) {
138
-		$pos = strlen($pathInfo);
139
-	}
140
-	$service = substr($pathInfo, 1, $pos - 1);
132
+    $request = \OC::$server->getRequest();
133
+    $pathInfo = $request->getPathInfo();
134
+    if ($pathInfo === false || $pathInfo === '') {
135
+        throw new RemoteException('Path not found', 404);
136
+    }
137
+    if (!$pos = strpos($pathInfo, '/', 1)) {
138
+        $pos = strlen($pathInfo);
139
+    }
140
+    $service = substr($pathInfo, 1, $pos - 1);
141 141
 
142
-	$file = resolveService($service);
142
+    $file = resolveService($service);
143 143
 
144
-	if (is_null($file)) {
145
-		throw new RemoteException('Path not found', 404);
146
-	}
144
+    if (is_null($file)) {
145
+        throw new RemoteException('Path not found', 404);
146
+    }
147 147
 
148
-	$file = ltrim($file, '/');
148
+    $file = ltrim($file, '/');
149 149
 
150
-	$parts = explode('/', $file, 2);
151
-	$app = $parts[0];
150
+    $parts = explode('/', $file, 2);
151
+    $app = $parts[0];
152 152
 
153
-	// Load all required applications
154
-	\OC::$REQUESTEDAPP = $app;
155
-	OC_App::loadApps(['authentication']);
156
-	OC_App::loadApps(['extended_authentication']);
157
-	OC_App::loadApps(['filesystem', 'logging']);
153
+    // Load all required applications
154
+    \OC::$REQUESTEDAPP = $app;
155
+    OC_App::loadApps(['authentication']);
156
+    OC_App::loadApps(['extended_authentication']);
157
+    OC_App::loadApps(['filesystem', 'logging']);
158 158
 
159
-	switch ($app) {
160
-		case 'core':
161
-			$file = OC::$SERVERROOT .'/'. $file;
162
-			break;
163
-		default:
164
-			if (!\OC::$server->getAppManager()->isInstalled($app)) {
165
-				throw new RemoteException('App not installed: ' . $app);
166
-			}
167
-			OC_App::loadApp($app);
168
-			$file = OC_App::getAppPath($app) .'/'. $parts[1];
169
-			break;
170
-	}
171
-	$baseuri = OC::$WEBROOT . '/remote.php/'.$service.'/';
172
-	require_once $file;
159
+    switch ($app) {
160
+        case 'core':
161
+            $file = OC::$SERVERROOT .'/'. $file;
162
+            break;
163
+        default:
164
+            if (!\OC::$server->getAppManager()->isInstalled($app)) {
165
+                throw new RemoteException('App not installed: ' . $app);
166
+            }
167
+            OC_App::loadApp($app);
168
+            $file = OC_App::getAppPath($app) .'/'. $parts[1];
169
+            break;
170
+    }
171
+    $baseuri = OC::$WEBROOT . '/remote.php/'.$service.'/';
172
+    require_once $file;
173 173
 } catch (Exception $ex) {
174
-	handleException($ex);
174
+    handleException($ex);
175 175
 } catch (Error $e) {
176
-	handleException($e);
176
+    handleException($e);
177 177
 }
Please login to merge, or discard this patch.
lib/private/Updater.php 1 patch
Indentation   +468 added lines, -468 removed lines patch added patch discarded remove patch
@@ -72,472 +72,472 @@
 block discarded – undo
72 72
  *  - failure(string $message)
73 73
  */
74 74
 class Updater extends BasicEmitter {
75
-	/** @var LoggerInterface */
76
-	private $log;
77
-
78
-	/** @var IConfig */
79
-	private $config;
80
-
81
-	/** @var Checker */
82
-	private $checker;
83
-
84
-	/** @var Installer */
85
-	private $installer;
86
-
87
-	private $logLevelNames = [
88
-		0 => 'Debug',
89
-		1 => 'Info',
90
-		2 => 'Warning',
91
-		3 => 'Error',
92
-		4 => 'Fatal',
93
-	];
94
-
95
-	public function __construct(IConfig $config,
96
-								Checker $checker,
97
-								?LoggerInterface $log,
98
-								Installer $installer) {
99
-		$this->log = $log;
100
-		$this->config = $config;
101
-		$this->checker = $checker;
102
-		$this->installer = $installer;
103
-	}
104
-
105
-	/**
106
-	 * runs the update actions in maintenance mode, does not upgrade the source files
107
-	 * except the main .htaccess file
108
-	 *
109
-	 * @return bool true if the operation succeeded, false otherwise
110
-	 */
111
-	public function upgrade(): bool {
112
-		$this->logAllEvents();
113
-
114
-		$logLevel = $this->config->getSystemValue('loglevel', ILogger::WARN);
115
-		$this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
116
-		$this->config->setSystemValue('loglevel', ILogger::DEBUG);
117
-
118
-		$wasMaintenanceModeEnabled = $this->config->getSystemValueBool('maintenance');
119
-
120
-		if (!$wasMaintenanceModeEnabled) {
121
-			$this->config->setSystemValue('maintenance', true);
122
-			$this->emit('\OC\Updater', 'maintenanceEnabled');
123
-		}
124
-
125
-		// Clear CAN_INSTALL file if not on git
126
-		if (\OC_Util::getChannel() !== 'git' && is_file(\OC::$configDir.'/CAN_INSTALL')) {
127
-			if (!unlink(\OC::$configDir . '/CAN_INSTALL')) {
128
-				$this->log->error('Could not cleanup CAN_INSTALL from your config folder. Please remove this file manually.');
129
-			}
130
-		}
131
-
132
-		$installedVersion = $this->config->getSystemValue('version', '0.0.0');
133
-		$currentVersion = implode('.', \OCP\Util::getVersion());
134
-
135
-		$this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, ['app' => 'core']);
136
-
137
-		$success = true;
138
-		try {
139
-			$this->doUpgrade($currentVersion, $installedVersion);
140
-		} catch (HintException $exception) {
141
-			$this->log->error($exception->getMessage(), [
142
-				'exception' => $exception,
143
-			]);
144
-			$this->emit('\OC\Updater', 'failure', [$exception->getMessage() . ': ' .$exception->getHint()]);
145
-			$success = false;
146
-		} catch (\Exception $exception) {
147
-			$this->log->error($exception->getMessage(), [
148
-				'exception' => $exception,
149
-			]);
150
-			$this->emit('\OC\Updater', 'failure', [get_class($exception) . ': ' .$exception->getMessage()]);
151
-			$success = false;
152
-		}
153
-
154
-		$this->emit('\OC\Updater', 'updateEnd', [$success]);
155
-
156
-		if (!$wasMaintenanceModeEnabled && $success) {
157
-			$this->config->setSystemValue('maintenance', false);
158
-			$this->emit('\OC\Updater', 'maintenanceDisabled');
159
-		} else {
160
-			$this->emit('\OC\Updater', 'maintenanceActive');
161
-		}
162
-
163
-		$this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
164
-		$this->config->setSystemValue('loglevel', $logLevel);
165
-		$this->config->setSystemValue('installed', true);
166
-
167
-		return $success;
168
-	}
169
-
170
-	/**
171
-	 * Return version from which this version is allowed to upgrade from
172
-	 *
173
-	 * @return array allowed previous versions per vendor
174
-	 */
175
-	private function getAllowedPreviousVersions(): array {
176
-		// this should really be a JSON file
177
-		require \OC::$SERVERROOT . '/version.php';
178
-		/** @var array $OC_VersionCanBeUpgradedFrom */
179
-		return $OC_VersionCanBeUpgradedFrom;
180
-	}
181
-
182
-	/**
183
-	 * Return vendor from which this version was published
184
-	 *
185
-	 * @return string Get the vendor
186
-	 */
187
-	private function getVendor(): string {
188
-		// this should really be a JSON file
189
-		require \OC::$SERVERROOT . '/version.php';
190
-		/** @var string $vendor */
191
-		return (string) $vendor;
192
-	}
193
-
194
-	/**
195
-	 * Whether an upgrade to a specified version is possible
196
-	 * @param string $oldVersion
197
-	 * @param string $newVersion
198
-	 * @param array $allowedPreviousVersions
199
-	 * @return bool
200
-	 */
201
-	public function isUpgradePossible(string $oldVersion, string $newVersion, array $allowedPreviousVersions): bool {
202
-		$version = explode('.', $oldVersion);
203
-		$majorMinor = $version[0] . '.' . $version[1];
204
-
205
-		$currentVendor = $this->config->getAppValue('core', 'vendor', '');
206
-
207
-		// Vendor was not set correctly on install, so we have to white-list known versions
208
-		if ($currentVendor === '' && (
209
-			isset($allowedPreviousVersions['owncloud'][$oldVersion]) ||
210
-			isset($allowedPreviousVersions['owncloud'][$majorMinor])
211
-		)) {
212
-			$currentVendor = 'owncloud';
213
-			$this->config->setAppValue('core', 'vendor', $currentVendor);
214
-		}
215
-
216
-		if ($currentVendor === 'nextcloud') {
217
-			return isset($allowedPreviousVersions[$currentVendor][$majorMinor])
218
-				&& (version_compare($oldVersion, $newVersion, '<=') ||
219
-					$this->config->getSystemValue('debug', false));
220
-		}
221
-
222
-		// Check if the instance can be migrated
223
-		return isset($allowedPreviousVersions[$currentVendor][$majorMinor]) ||
224
-			isset($allowedPreviousVersions[$currentVendor][$oldVersion]);
225
-	}
226
-
227
-	/**
228
-	 * runs the update actions in maintenance mode, does not upgrade the source files
229
-	 * except the main .htaccess file
230
-	 *
231
-	 * @param string $currentVersion current version to upgrade to
232
-	 * @param string $installedVersion previous version from which to upgrade from
233
-	 *
234
-	 * @throws \Exception
235
-	 */
236
-	private function doUpgrade(string $currentVersion, string $installedVersion): void {
237
-		// Stop update if the update is over several major versions
238
-		$allowedPreviousVersions = $this->getAllowedPreviousVersions();
239
-		if (!$this->isUpgradePossible($installedVersion, $currentVersion, $allowedPreviousVersions)) {
240
-			throw new \Exception('Updates between multiple major versions and downgrades are unsupported.');
241
-		}
242
-
243
-		// Update .htaccess files
244
-		try {
245
-			Setup::updateHtaccess();
246
-			Setup::protectDataDirectory();
247
-		} catch (\Exception $e) {
248
-			throw new \Exception($e->getMessage());
249
-		}
250
-
251
-		// create empty file in data dir, so we can later find
252
-		// out that this is indeed an ownCloud data directory
253
-		// (in case it didn't exist before)
254
-		file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
255
-
256
-		// pre-upgrade repairs
257
-		$repair = new Repair(Repair::getBeforeUpgradeRepairSteps(), \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
258
-		$repair->run();
259
-
260
-		$this->doCoreUpgrade();
261
-
262
-		try {
263
-			// TODO: replace with the new repair step mechanism https://github.com/owncloud/core/pull/24378
264
-			Setup::installBackgroundJobs();
265
-		} catch (\Exception $e) {
266
-			throw new \Exception($e->getMessage());
267
-		}
268
-
269
-		// update all shipped apps
270
-		$this->checkAppsRequirements();
271
-		$this->doAppUpgrade();
272
-
273
-		// Update the appfetchers version so it downloads the correct list from the appstore
274
-		\OC::$server->getAppFetcher()->setVersion($currentVersion);
275
-
276
-		/** @var AppManager $appManager */
277
-		$appManager = \OC::$server->getAppManager();
278
-
279
-		// upgrade appstore apps
280
-		$this->upgradeAppStoreApps($appManager->getInstalledApps());
281
-		$autoDisabledApps = $appManager->getAutoDisabledApps();
282
-		if (!empty($autoDisabledApps)) {
283
-			$this->upgradeAppStoreApps(array_keys($autoDisabledApps), $autoDisabledApps);
284
-		}
285
-
286
-		// install new shipped apps on upgrade
287
-		$errors = Installer::installShippedApps(true);
288
-		foreach ($errors as $appId => $exception) {
289
-			/** @var \Exception $exception */
290
-			$this->log->error($exception->getMessage(), [
291
-				'exception' => $exception,
292
-				'app' => $appId,
293
-			]);
294
-			$this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
295
-		}
296
-
297
-		// post-upgrade repairs
298
-		$repair = new Repair(Repair::getRepairSteps(), \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
299
-		$repair->run();
300
-
301
-		//Invalidate update feed
302
-		$this->config->setAppValue('core', 'lastupdatedat', '0');
303
-
304
-		// Check for code integrity if not disabled
305
-		if (\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
306
-			$this->emit('\OC\Updater', 'startCheckCodeIntegrity');
307
-			$this->checker->runInstanceVerification();
308
-			$this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
309
-		}
310
-
311
-		// only set the final version if everything went well
312
-		$this->config->setSystemValue('version', implode('.', Util::getVersion()));
313
-		$this->config->setAppValue('core', 'vendor', $this->getVendor());
314
-	}
315
-
316
-	protected function doCoreUpgrade(): void {
317
-		$this->emit('\OC\Updater', 'dbUpgradeBefore');
318
-
319
-		// execute core migrations
320
-		$ms = new MigrationService('core', \OC::$server->get(Connection::class));
321
-		$ms->migrate();
322
-
323
-		$this->emit('\OC\Updater', 'dbUpgrade');
324
-	}
325
-
326
-	/**
327
-	 * upgrades all apps within a major ownCloud upgrade. Also loads "priority"
328
-	 * (types authentication, filesystem, logging, in that order) afterwards.
329
-	 *
330
-	 * @throws NeedsUpdateException
331
-	 */
332
-	protected function doAppUpgrade(): void {
333
-		$apps = \OC_App::getEnabledApps();
334
-		$priorityTypes = ['authentication', 'extended_authentication', 'filesystem', 'logging'];
335
-		$pseudoOtherType = 'other';
336
-		$stacks = [$pseudoOtherType => []];
337
-
338
-		foreach ($apps as $appId) {
339
-			$priorityType = false;
340
-			foreach ($priorityTypes as $type) {
341
-				if (!isset($stacks[$type])) {
342
-					$stacks[$type] = [];
343
-				}
344
-				if (\OC_App::isType($appId, [$type])) {
345
-					$stacks[$type][] = $appId;
346
-					$priorityType = true;
347
-					break;
348
-				}
349
-			}
350
-			if (!$priorityType) {
351
-				$stacks[$pseudoOtherType][] = $appId;
352
-			}
353
-		}
354
-		foreach (array_merge($priorityTypes, [$pseudoOtherType]) as $type) {
355
-			$stack = $stacks[$type];
356
-			foreach ($stack as $appId) {
357
-				if (\OC_App::shouldUpgrade($appId)) {
358
-					$this->emit('\OC\Updater', 'appUpgradeStarted', [$appId, \OC_App::getAppVersion($appId)]);
359
-					\OC_App::updateApp($appId);
360
-					$this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]);
361
-				}
362
-				if ($type !== $pseudoOtherType) {
363
-					// load authentication, filesystem and logging apps after
364
-					// upgrading them. Other apps my need to rely on modifying
365
-					// user and/or filesystem aspects.
366
-					\OC_App::loadApp($appId);
367
-				}
368
-			}
369
-		}
370
-	}
371
-
372
-	/**
373
-	 * check if the current enabled apps are compatible with the current
374
-	 * ownCloud version. disable them if not.
375
-	 * This is important if you upgrade ownCloud and have non ported 3rd
376
-	 * party apps installed.
377
-	 *
378
-	 * @throws \Exception
379
-	 */
380
-	private function checkAppsRequirements(): void {
381
-		$isCoreUpgrade = $this->isCodeUpgrade();
382
-		$apps = OC_App::getEnabledApps();
383
-		$version = implode('.', Util::getVersion());
384
-		$appManager = \OC::$server->getAppManager();
385
-		foreach ($apps as $app) {
386
-			// check if the app is compatible with this version of Nextcloud
387
-			$info = $appManager->getAppInfo($app);
388
-			if ($info === null || !OC_App::isAppCompatible($version, $info)) {
389
-				if ($appManager->isShipped($app)) {
390
-					throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update');
391
-				}
392
-				$appManager->disableApp($app, true);
393
-				$this->emit('\OC\Updater', 'incompatibleAppDisabled', [$app]);
394
-			}
395
-		}
396
-	}
397
-
398
-	/**
399
-	 * @return bool
400
-	 */
401
-	private function isCodeUpgrade(): bool {
402
-		$installedVersion = $this->config->getSystemValue('version', '0.0.0');
403
-		$currentVersion = implode('.', Util::getVersion());
404
-		if (version_compare($currentVersion, $installedVersion, '>')) {
405
-			return true;
406
-		}
407
-		return false;
408
-	}
409
-
410
-	/**
411
-	 * @param array $apps
412
-	 * @param array $previousEnableStates
413
-	 * @throws \Exception
414
-	 */
415
-	private function upgradeAppStoreApps(array $apps, array $previousEnableStates = []): void {
416
-		foreach ($apps as $app) {
417
-			try {
418
-				$this->emit('\OC\Updater', 'checkAppStoreAppBefore', [$app]);
419
-				if ($this->installer->isUpdateAvailable($app)) {
420
-					$this->emit('\OC\Updater', 'upgradeAppStoreApp', [$app]);
421
-					$this->installer->updateAppstoreApp($app);
422
-				}
423
-				$this->emit('\OC\Updater', 'checkAppStoreApp', [$app]);
424
-
425
-				if (!empty($previousEnableStates)) {
426
-					$ocApp = new \OC_App();
427
-					if (!empty($previousEnableStates[$app]) && is_array($previousEnableStates[$app])) {
428
-						$ocApp->enable($app, $previousEnableStates[$app]);
429
-					} else {
430
-						$ocApp->enable($app);
431
-					}
432
-				}
433
-			} catch (\Exception $ex) {
434
-				$this->log->error($ex->getMessage(), [
435
-					'exception' => $ex,
436
-				]);
437
-			}
438
-		}
439
-	}
440
-
441
-	private function logAllEvents(): void {
442
-		$log = $this->log;
443
-
444
-		/** @var IEventDispatcher $dispatcher */
445
-		$dispatcher = \OC::$server->get(IEventDispatcher::class);
446
-		$dispatcher->addListener(
447
-			MigratorExecuteSqlEvent::class,
448
-			function (MigratorExecuteSqlEvent $event) use ($log): void {
449
-				$log->info(get_class($event).': ' . $event->getSql() . ' (' . $event->getCurrentStep() . ' of ' . $event->getMaxStep() . ')', ['app' => 'updater']);
450
-			}
451
-		);
452
-
453
-		$repairListener = function (Event $event) use ($log): void {
454
-			if ($event instanceof RepairStartEvent) {
455
-				$log->info(get_class($event).': Starting ... ' . $event->getMaxStep() .  ' (' . $event->getCurrentStepName() . ')', ['app' => 'updater']);
456
-			} elseif ($event instanceof RepairAdvanceEvent) {
457
-				$desc = $event->getDescription();
458
-				if (empty($desc)) {
459
-					$desc = '';
460
-				}
461
-				$log->info(get_class($event).': ' . $desc . ' (' . $event->getIncrement() . ')', ['app' => 'updater']);
462
-			} elseif ($event instanceof RepairFinishEvent) {
463
-				$log->info(get_class($event), ['app' => 'updater']);
464
-			} elseif ($event instanceof RepairStepEvent) {
465
-				$log->info(get_class($event).': Repair step: ' . $event->getStepName(), ['app' => 'updater']);
466
-			} elseif ($event instanceof RepairInfoEvent) {
467
-				$log->info(get_class($event).': Repair info: ' . $event->getMessage(), ['app' => 'updater']);
468
-			} elseif ($event instanceof RepairWarningEvent) {
469
-				$log->warning(get_class($event).': Repair warning: ' . $event->getMessage(), ['app' => 'updater']);
470
-			} elseif ($event instanceof RepairErrorEvent) {
471
-				$log->error(get_class($event).': Repair error: ' . $event->getMessage(), ['app' => 'updater']);
472
-			}
473
-		};
474
-
475
-		$dispatcher->addListener(RepairStartEvent::class, $repairListener);
476
-		$dispatcher->addListener(RepairAdvanceEvent::class, $repairListener);
477
-		$dispatcher->addListener(RepairFinishEvent::class, $repairListener);
478
-		$dispatcher->addListener(RepairStepEvent::class, $repairListener);
479
-		$dispatcher->addListener(RepairInfoEvent::class, $repairListener);
480
-		$dispatcher->addListener(RepairWarningEvent::class, $repairListener);
481
-		$dispatcher->addListener(RepairErrorEvent::class, $repairListener);
482
-
483
-
484
-		$this->listen('\OC\Updater', 'maintenanceEnabled', function () use ($log) {
485
-			$log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']);
486
-		});
487
-		$this->listen('\OC\Updater', 'maintenanceDisabled', function () use ($log) {
488
-			$log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']);
489
-		});
490
-		$this->listen('\OC\Updater', 'maintenanceActive', function () use ($log) {
491
-			$log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']);
492
-		});
493
-		$this->listen('\OC\Updater', 'updateEnd', function ($success) use ($log) {
494
-			if ($success) {
495
-				$log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']);
496
-			} else {
497
-				$log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']);
498
-			}
499
-		});
500
-		$this->listen('\OC\Updater', 'dbUpgradeBefore', function () use ($log) {
501
-			$log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']);
502
-		});
503
-		$this->listen('\OC\Updater', 'dbUpgrade', function () use ($log) {
504
-			$log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']);
505
-		});
506
-		$this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use ($log) {
507
-			$log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']);
508
-		});
509
-		$this->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($log) {
510
-			$log->debug('\OC\Updater::checkAppStoreAppBefore: Checking for update of app "' . $app . '" in appstore', ['app' => 'updater']);
511
-		});
512
-		$this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($log) {
513
-			$log->info('\OC\Updater::upgradeAppStoreApp: Update app "' . $app . '" from appstore', ['app' => 'updater']);
514
-		});
515
-		$this->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($log) {
516
-			$log->debug('\OC\Updater::checkAppStoreApp: Checked for update of app "' . $app . '" in appstore', ['app' => 'updater']);
517
-		});
518
-		$this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) {
519
-			$log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <' . $app . '> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
520
-		});
521
-		$this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) {
522
-			$log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']);
523
-		});
524
-		$this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) {
525
-			$log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']);
526
-		});
527
-		$this->listen('\OC\Updater', 'failure', function ($message) use ($log) {
528
-			$log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']);
529
-		});
530
-		$this->listen('\OC\Updater', 'setDebugLogLevel', function () use ($log) {
531
-			$log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']);
532
-		});
533
-		$this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use ($log) {
534
-			$log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']);
535
-		});
536
-		$this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use ($log) {
537
-			$log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']);
538
-		});
539
-		$this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use ($log) {
540
-			$log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']);
541
-		});
542
-	}
75
+    /** @var LoggerInterface */
76
+    private $log;
77
+
78
+    /** @var IConfig */
79
+    private $config;
80
+
81
+    /** @var Checker */
82
+    private $checker;
83
+
84
+    /** @var Installer */
85
+    private $installer;
86
+
87
+    private $logLevelNames = [
88
+        0 => 'Debug',
89
+        1 => 'Info',
90
+        2 => 'Warning',
91
+        3 => 'Error',
92
+        4 => 'Fatal',
93
+    ];
94
+
95
+    public function __construct(IConfig $config,
96
+                                Checker $checker,
97
+                                ?LoggerInterface $log,
98
+                                Installer $installer) {
99
+        $this->log = $log;
100
+        $this->config = $config;
101
+        $this->checker = $checker;
102
+        $this->installer = $installer;
103
+    }
104
+
105
+    /**
106
+     * runs the update actions in maintenance mode, does not upgrade the source files
107
+     * except the main .htaccess file
108
+     *
109
+     * @return bool true if the operation succeeded, false otherwise
110
+     */
111
+    public function upgrade(): bool {
112
+        $this->logAllEvents();
113
+
114
+        $logLevel = $this->config->getSystemValue('loglevel', ILogger::WARN);
115
+        $this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
116
+        $this->config->setSystemValue('loglevel', ILogger::DEBUG);
117
+
118
+        $wasMaintenanceModeEnabled = $this->config->getSystemValueBool('maintenance');
119
+
120
+        if (!$wasMaintenanceModeEnabled) {
121
+            $this->config->setSystemValue('maintenance', true);
122
+            $this->emit('\OC\Updater', 'maintenanceEnabled');
123
+        }
124
+
125
+        // Clear CAN_INSTALL file if not on git
126
+        if (\OC_Util::getChannel() !== 'git' && is_file(\OC::$configDir.'/CAN_INSTALL')) {
127
+            if (!unlink(\OC::$configDir . '/CAN_INSTALL')) {
128
+                $this->log->error('Could not cleanup CAN_INSTALL from your config folder. Please remove this file manually.');
129
+            }
130
+        }
131
+
132
+        $installedVersion = $this->config->getSystemValue('version', '0.0.0');
133
+        $currentVersion = implode('.', \OCP\Util::getVersion());
134
+
135
+        $this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, ['app' => 'core']);
136
+
137
+        $success = true;
138
+        try {
139
+            $this->doUpgrade($currentVersion, $installedVersion);
140
+        } catch (HintException $exception) {
141
+            $this->log->error($exception->getMessage(), [
142
+                'exception' => $exception,
143
+            ]);
144
+            $this->emit('\OC\Updater', 'failure', [$exception->getMessage() . ': ' .$exception->getHint()]);
145
+            $success = false;
146
+        } catch (\Exception $exception) {
147
+            $this->log->error($exception->getMessage(), [
148
+                'exception' => $exception,
149
+            ]);
150
+            $this->emit('\OC\Updater', 'failure', [get_class($exception) . ': ' .$exception->getMessage()]);
151
+            $success = false;
152
+        }
153
+
154
+        $this->emit('\OC\Updater', 'updateEnd', [$success]);
155
+
156
+        if (!$wasMaintenanceModeEnabled && $success) {
157
+            $this->config->setSystemValue('maintenance', false);
158
+            $this->emit('\OC\Updater', 'maintenanceDisabled');
159
+        } else {
160
+            $this->emit('\OC\Updater', 'maintenanceActive');
161
+        }
162
+
163
+        $this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
164
+        $this->config->setSystemValue('loglevel', $logLevel);
165
+        $this->config->setSystemValue('installed', true);
166
+
167
+        return $success;
168
+    }
169
+
170
+    /**
171
+     * Return version from which this version is allowed to upgrade from
172
+     *
173
+     * @return array allowed previous versions per vendor
174
+     */
175
+    private function getAllowedPreviousVersions(): array {
176
+        // this should really be a JSON file
177
+        require \OC::$SERVERROOT . '/version.php';
178
+        /** @var array $OC_VersionCanBeUpgradedFrom */
179
+        return $OC_VersionCanBeUpgradedFrom;
180
+    }
181
+
182
+    /**
183
+     * Return vendor from which this version was published
184
+     *
185
+     * @return string Get the vendor
186
+     */
187
+    private function getVendor(): string {
188
+        // this should really be a JSON file
189
+        require \OC::$SERVERROOT . '/version.php';
190
+        /** @var string $vendor */
191
+        return (string) $vendor;
192
+    }
193
+
194
+    /**
195
+     * Whether an upgrade to a specified version is possible
196
+     * @param string $oldVersion
197
+     * @param string $newVersion
198
+     * @param array $allowedPreviousVersions
199
+     * @return bool
200
+     */
201
+    public function isUpgradePossible(string $oldVersion, string $newVersion, array $allowedPreviousVersions): bool {
202
+        $version = explode('.', $oldVersion);
203
+        $majorMinor = $version[0] . '.' . $version[1];
204
+
205
+        $currentVendor = $this->config->getAppValue('core', 'vendor', '');
206
+
207
+        // Vendor was not set correctly on install, so we have to white-list known versions
208
+        if ($currentVendor === '' && (
209
+            isset($allowedPreviousVersions['owncloud'][$oldVersion]) ||
210
+            isset($allowedPreviousVersions['owncloud'][$majorMinor])
211
+        )) {
212
+            $currentVendor = 'owncloud';
213
+            $this->config->setAppValue('core', 'vendor', $currentVendor);
214
+        }
215
+
216
+        if ($currentVendor === 'nextcloud') {
217
+            return isset($allowedPreviousVersions[$currentVendor][$majorMinor])
218
+                && (version_compare($oldVersion, $newVersion, '<=') ||
219
+                    $this->config->getSystemValue('debug', false));
220
+        }
221
+
222
+        // Check if the instance can be migrated
223
+        return isset($allowedPreviousVersions[$currentVendor][$majorMinor]) ||
224
+            isset($allowedPreviousVersions[$currentVendor][$oldVersion]);
225
+    }
226
+
227
+    /**
228
+     * runs the update actions in maintenance mode, does not upgrade the source files
229
+     * except the main .htaccess file
230
+     *
231
+     * @param string $currentVersion current version to upgrade to
232
+     * @param string $installedVersion previous version from which to upgrade from
233
+     *
234
+     * @throws \Exception
235
+     */
236
+    private function doUpgrade(string $currentVersion, string $installedVersion): void {
237
+        // Stop update if the update is over several major versions
238
+        $allowedPreviousVersions = $this->getAllowedPreviousVersions();
239
+        if (!$this->isUpgradePossible($installedVersion, $currentVersion, $allowedPreviousVersions)) {
240
+            throw new \Exception('Updates between multiple major versions and downgrades are unsupported.');
241
+        }
242
+
243
+        // Update .htaccess files
244
+        try {
245
+            Setup::updateHtaccess();
246
+            Setup::protectDataDirectory();
247
+        } catch (\Exception $e) {
248
+            throw new \Exception($e->getMessage());
249
+        }
250
+
251
+        // create empty file in data dir, so we can later find
252
+        // out that this is indeed an ownCloud data directory
253
+        // (in case it didn't exist before)
254
+        file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
255
+
256
+        // pre-upgrade repairs
257
+        $repair = new Repair(Repair::getBeforeUpgradeRepairSteps(), \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
258
+        $repair->run();
259
+
260
+        $this->doCoreUpgrade();
261
+
262
+        try {
263
+            // TODO: replace with the new repair step mechanism https://github.com/owncloud/core/pull/24378
264
+            Setup::installBackgroundJobs();
265
+        } catch (\Exception $e) {
266
+            throw new \Exception($e->getMessage());
267
+        }
268
+
269
+        // update all shipped apps
270
+        $this->checkAppsRequirements();
271
+        $this->doAppUpgrade();
272
+
273
+        // Update the appfetchers version so it downloads the correct list from the appstore
274
+        \OC::$server->getAppFetcher()->setVersion($currentVersion);
275
+
276
+        /** @var AppManager $appManager */
277
+        $appManager = \OC::$server->getAppManager();
278
+
279
+        // upgrade appstore apps
280
+        $this->upgradeAppStoreApps($appManager->getInstalledApps());
281
+        $autoDisabledApps = $appManager->getAutoDisabledApps();
282
+        if (!empty($autoDisabledApps)) {
283
+            $this->upgradeAppStoreApps(array_keys($autoDisabledApps), $autoDisabledApps);
284
+        }
285
+
286
+        // install new shipped apps on upgrade
287
+        $errors = Installer::installShippedApps(true);
288
+        foreach ($errors as $appId => $exception) {
289
+            /** @var \Exception $exception */
290
+            $this->log->error($exception->getMessage(), [
291
+                'exception' => $exception,
292
+                'app' => $appId,
293
+            ]);
294
+            $this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
295
+        }
296
+
297
+        // post-upgrade repairs
298
+        $repair = new Repair(Repair::getRepairSteps(), \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
299
+        $repair->run();
300
+
301
+        //Invalidate update feed
302
+        $this->config->setAppValue('core', 'lastupdatedat', '0');
303
+
304
+        // Check for code integrity if not disabled
305
+        if (\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
306
+            $this->emit('\OC\Updater', 'startCheckCodeIntegrity');
307
+            $this->checker->runInstanceVerification();
308
+            $this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
309
+        }
310
+
311
+        // only set the final version if everything went well
312
+        $this->config->setSystemValue('version', implode('.', Util::getVersion()));
313
+        $this->config->setAppValue('core', 'vendor', $this->getVendor());
314
+    }
315
+
316
+    protected function doCoreUpgrade(): void {
317
+        $this->emit('\OC\Updater', 'dbUpgradeBefore');
318
+
319
+        // execute core migrations
320
+        $ms = new MigrationService('core', \OC::$server->get(Connection::class));
321
+        $ms->migrate();
322
+
323
+        $this->emit('\OC\Updater', 'dbUpgrade');
324
+    }
325
+
326
+    /**
327
+     * upgrades all apps within a major ownCloud upgrade. Also loads "priority"
328
+     * (types authentication, filesystem, logging, in that order) afterwards.
329
+     *
330
+     * @throws NeedsUpdateException
331
+     */
332
+    protected function doAppUpgrade(): void {
333
+        $apps = \OC_App::getEnabledApps();
334
+        $priorityTypes = ['authentication', 'extended_authentication', 'filesystem', 'logging'];
335
+        $pseudoOtherType = 'other';
336
+        $stacks = [$pseudoOtherType => []];
337
+
338
+        foreach ($apps as $appId) {
339
+            $priorityType = false;
340
+            foreach ($priorityTypes as $type) {
341
+                if (!isset($stacks[$type])) {
342
+                    $stacks[$type] = [];
343
+                }
344
+                if (\OC_App::isType($appId, [$type])) {
345
+                    $stacks[$type][] = $appId;
346
+                    $priorityType = true;
347
+                    break;
348
+                }
349
+            }
350
+            if (!$priorityType) {
351
+                $stacks[$pseudoOtherType][] = $appId;
352
+            }
353
+        }
354
+        foreach (array_merge($priorityTypes, [$pseudoOtherType]) as $type) {
355
+            $stack = $stacks[$type];
356
+            foreach ($stack as $appId) {
357
+                if (\OC_App::shouldUpgrade($appId)) {
358
+                    $this->emit('\OC\Updater', 'appUpgradeStarted', [$appId, \OC_App::getAppVersion($appId)]);
359
+                    \OC_App::updateApp($appId);
360
+                    $this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]);
361
+                }
362
+                if ($type !== $pseudoOtherType) {
363
+                    // load authentication, filesystem and logging apps after
364
+                    // upgrading them. Other apps my need to rely on modifying
365
+                    // user and/or filesystem aspects.
366
+                    \OC_App::loadApp($appId);
367
+                }
368
+            }
369
+        }
370
+    }
371
+
372
+    /**
373
+     * check if the current enabled apps are compatible with the current
374
+     * ownCloud version. disable them if not.
375
+     * This is important if you upgrade ownCloud and have non ported 3rd
376
+     * party apps installed.
377
+     *
378
+     * @throws \Exception
379
+     */
380
+    private function checkAppsRequirements(): void {
381
+        $isCoreUpgrade = $this->isCodeUpgrade();
382
+        $apps = OC_App::getEnabledApps();
383
+        $version = implode('.', Util::getVersion());
384
+        $appManager = \OC::$server->getAppManager();
385
+        foreach ($apps as $app) {
386
+            // check if the app is compatible with this version of Nextcloud
387
+            $info = $appManager->getAppInfo($app);
388
+            if ($info === null || !OC_App::isAppCompatible($version, $info)) {
389
+                if ($appManager->isShipped($app)) {
390
+                    throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update');
391
+                }
392
+                $appManager->disableApp($app, true);
393
+                $this->emit('\OC\Updater', 'incompatibleAppDisabled', [$app]);
394
+            }
395
+        }
396
+    }
397
+
398
+    /**
399
+     * @return bool
400
+     */
401
+    private function isCodeUpgrade(): bool {
402
+        $installedVersion = $this->config->getSystemValue('version', '0.0.0');
403
+        $currentVersion = implode('.', Util::getVersion());
404
+        if (version_compare($currentVersion, $installedVersion, '>')) {
405
+            return true;
406
+        }
407
+        return false;
408
+    }
409
+
410
+    /**
411
+     * @param array $apps
412
+     * @param array $previousEnableStates
413
+     * @throws \Exception
414
+     */
415
+    private function upgradeAppStoreApps(array $apps, array $previousEnableStates = []): void {
416
+        foreach ($apps as $app) {
417
+            try {
418
+                $this->emit('\OC\Updater', 'checkAppStoreAppBefore', [$app]);
419
+                if ($this->installer->isUpdateAvailable($app)) {
420
+                    $this->emit('\OC\Updater', 'upgradeAppStoreApp', [$app]);
421
+                    $this->installer->updateAppstoreApp($app);
422
+                }
423
+                $this->emit('\OC\Updater', 'checkAppStoreApp', [$app]);
424
+
425
+                if (!empty($previousEnableStates)) {
426
+                    $ocApp = new \OC_App();
427
+                    if (!empty($previousEnableStates[$app]) && is_array($previousEnableStates[$app])) {
428
+                        $ocApp->enable($app, $previousEnableStates[$app]);
429
+                    } else {
430
+                        $ocApp->enable($app);
431
+                    }
432
+                }
433
+            } catch (\Exception $ex) {
434
+                $this->log->error($ex->getMessage(), [
435
+                    'exception' => $ex,
436
+                ]);
437
+            }
438
+        }
439
+    }
440
+
441
+    private function logAllEvents(): void {
442
+        $log = $this->log;
443
+
444
+        /** @var IEventDispatcher $dispatcher */
445
+        $dispatcher = \OC::$server->get(IEventDispatcher::class);
446
+        $dispatcher->addListener(
447
+            MigratorExecuteSqlEvent::class,
448
+            function (MigratorExecuteSqlEvent $event) use ($log): void {
449
+                $log->info(get_class($event).': ' . $event->getSql() . ' (' . $event->getCurrentStep() . ' of ' . $event->getMaxStep() . ')', ['app' => 'updater']);
450
+            }
451
+        );
452
+
453
+        $repairListener = function (Event $event) use ($log): void {
454
+            if ($event instanceof RepairStartEvent) {
455
+                $log->info(get_class($event).': Starting ... ' . $event->getMaxStep() .  ' (' . $event->getCurrentStepName() . ')', ['app' => 'updater']);
456
+            } elseif ($event instanceof RepairAdvanceEvent) {
457
+                $desc = $event->getDescription();
458
+                if (empty($desc)) {
459
+                    $desc = '';
460
+                }
461
+                $log->info(get_class($event).': ' . $desc . ' (' . $event->getIncrement() . ')', ['app' => 'updater']);
462
+            } elseif ($event instanceof RepairFinishEvent) {
463
+                $log->info(get_class($event), ['app' => 'updater']);
464
+            } elseif ($event instanceof RepairStepEvent) {
465
+                $log->info(get_class($event).': Repair step: ' . $event->getStepName(), ['app' => 'updater']);
466
+            } elseif ($event instanceof RepairInfoEvent) {
467
+                $log->info(get_class($event).': Repair info: ' . $event->getMessage(), ['app' => 'updater']);
468
+            } elseif ($event instanceof RepairWarningEvent) {
469
+                $log->warning(get_class($event).': Repair warning: ' . $event->getMessage(), ['app' => 'updater']);
470
+            } elseif ($event instanceof RepairErrorEvent) {
471
+                $log->error(get_class($event).': Repair error: ' . $event->getMessage(), ['app' => 'updater']);
472
+            }
473
+        };
474
+
475
+        $dispatcher->addListener(RepairStartEvent::class, $repairListener);
476
+        $dispatcher->addListener(RepairAdvanceEvent::class, $repairListener);
477
+        $dispatcher->addListener(RepairFinishEvent::class, $repairListener);
478
+        $dispatcher->addListener(RepairStepEvent::class, $repairListener);
479
+        $dispatcher->addListener(RepairInfoEvent::class, $repairListener);
480
+        $dispatcher->addListener(RepairWarningEvent::class, $repairListener);
481
+        $dispatcher->addListener(RepairErrorEvent::class, $repairListener);
482
+
483
+
484
+        $this->listen('\OC\Updater', 'maintenanceEnabled', function () use ($log) {
485
+            $log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']);
486
+        });
487
+        $this->listen('\OC\Updater', 'maintenanceDisabled', function () use ($log) {
488
+            $log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']);
489
+        });
490
+        $this->listen('\OC\Updater', 'maintenanceActive', function () use ($log) {
491
+            $log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']);
492
+        });
493
+        $this->listen('\OC\Updater', 'updateEnd', function ($success) use ($log) {
494
+            if ($success) {
495
+                $log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']);
496
+            } else {
497
+                $log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']);
498
+            }
499
+        });
500
+        $this->listen('\OC\Updater', 'dbUpgradeBefore', function () use ($log) {
501
+            $log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']);
502
+        });
503
+        $this->listen('\OC\Updater', 'dbUpgrade', function () use ($log) {
504
+            $log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']);
505
+        });
506
+        $this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use ($log) {
507
+            $log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']);
508
+        });
509
+        $this->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($log) {
510
+            $log->debug('\OC\Updater::checkAppStoreAppBefore: Checking for update of app "' . $app . '" in appstore', ['app' => 'updater']);
511
+        });
512
+        $this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($log) {
513
+            $log->info('\OC\Updater::upgradeAppStoreApp: Update app "' . $app . '" from appstore', ['app' => 'updater']);
514
+        });
515
+        $this->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($log) {
516
+            $log->debug('\OC\Updater::checkAppStoreApp: Checked for update of app "' . $app . '" in appstore', ['app' => 'updater']);
517
+        });
518
+        $this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) {
519
+            $log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <' . $app . '> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
520
+        });
521
+        $this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) {
522
+            $log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']);
523
+        });
524
+        $this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) {
525
+            $log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']);
526
+        });
527
+        $this->listen('\OC\Updater', 'failure', function ($message) use ($log) {
528
+            $log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']);
529
+        });
530
+        $this->listen('\OC\Updater', 'setDebugLogLevel', function () use ($log) {
531
+            $log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']);
532
+        });
533
+        $this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use ($log) {
534
+            $log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']);
535
+        });
536
+        $this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use ($log) {
537
+            $log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']);
538
+        });
539
+        $this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use ($log) {
540
+            $log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']);
541
+        });
542
+    }
543 543
 }
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +1070 added lines, -1070 removed lines patch added patch discarded remove patch
@@ -91,1076 +91,1076 @@
 block discarded – undo
91 91
  * OC_autoload!
92 92
  */
93 93
 class OC {
94
-	/**
95
-	 * Associative array for autoloading. classname => filename
96
-	 */
97
-	public static array $CLASSPATH = [];
98
-	/**
99
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
100
-	 */
101
-	public static string $SERVERROOT = '';
102
-	/**
103
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
104
-	 */
105
-	private static string $SUBURI = '';
106
-	/**
107
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
108
-	 */
109
-	public static string $WEBROOT = '';
110
-	/**
111
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
112
-	 * web path in 'url'
113
-	 */
114
-	public static array $APPSROOTS = [];
115
-
116
-	public static string $configDir;
117
-
118
-	/**
119
-	 * requested app
120
-	 */
121
-	public static string $REQUESTEDAPP = '';
122
-
123
-	/**
124
-	 * check if Nextcloud runs in cli mode
125
-	 */
126
-	public static bool $CLI = false;
127
-
128
-	public static \OC\Autoloader $loader;
129
-
130
-	public static \Composer\Autoload\ClassLoader $composerAutoloader;
131
-
132
-	public static \OC\Server $server;
133
-
134
-	private static \OC\Config $config;
135
-
136
-	/**
137
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
138
-	 * the app path list is empty or contains an invalid path
139
-	 */
140
-	public static function initPaths(): void {
141
-		if (defined('PHPUNIT_CONFIG_DIR')) {
142
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
143
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
144
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
145
-		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
146
-			self::$configDir = rtrim($dir, '/') . '/';
147
-		} else {
148
-			self::$configDir = OC::$SERVERROOT . '/config/';
149
-		}
150
-		self::$config = new \OC\Config(self::$configDir);
151
-
152
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"] ?? ''), strlen(OC::$SERVERROOT)));
153
-		/**
154
-		 * FIXME: The following lines are required because we can't yet instantiate
155
-		 *        Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist.
156
-		 */
157
-		$params = [
158
-			'server' => [
159
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null,
160
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null,
161
-			],
162
-		];
163
-		$fakeRequest = new \OC\AppFramework\Http\Request(
164
-			$params,
165
-			new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
166
-			new \OC\AllConfig(new \OC\SystemConfig(self::$config))
167
-		);
168
-		$scriptName = $fakeRequest->getScriptName();
169
-		if (substr($scriptName, -1) == '/') {
170
-			$scriptName .= 'index.php';
171
-			//make sure suburi follows the same rules as scriptName
172
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
173
-				if (substr(OC::$SUBURI, -1) != '/') {
174
-					OC::$SUBURI = OC::$SUBURI . '/';
175
-				}
176
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
177
-			}
178
-		}
179
-
180
-
181
-		if (OC::$CLI) {
182
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
183
-		} else {
184
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
185
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
186
-
187
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
188
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
189
-				}
190
-			} else {
191
-				// The scriptName is not ending with OC::$SUBURI
192
-				// This most likely means that we are calling from CLI.
193
-				// However some cron jobs still need to generate
194
-				// a web URL, so we use overwritewebroot as a fallback.
195
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
196
-			}
197
-
198
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
199
-			// slash which is required by URL generation.
200
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
201
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
202
-				header('Location: '.\OC::$WEBROOT.'/');
203
-				exit();
204
-			}
205
-		}
206
-
207
-		// search the apps folder
208
-		$config_paths = self::$config->getValue('apps_paths', []);
209
-		if (!empty($config_paths)) {
210
-			foreach ($config_paths as $paths) {
211
-				if (isset($paths['url']) && isset($paths['path'])) {
212
-					$paths['url'] = rtrim($paths['url'], '/');
213
-					$paths['path'] = rtrim($paths['path'], '/');
214
-					OC::$APPSROOTS[] = $paths;
215
-				}
216
-			}
217
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
218
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
219
-		}
220
-
221
-		if (empty(OC::$APPSROOTS)) {
222
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
223
-				. '. You can also configure the location in the config.php file.');
224
-		}
225
-		$paths = [];
226
-		foreach (OC::$APPSROOTS as $path) {
227
-			$paths[] = $path['path'];
228
-			if (!is_dir($path['path'])) {
229
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
230
-					. ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
231
-			}
232
-		}
233
-
234
-		// set the right include path
235
-		set_include_path(
236
-			implode(PATH_SEPARATOR, $paths)
237
-		);
238
-	}
239
-
240
-	public static function checkConfig(): void {
241
-		$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
242
-
243
-		// Create config if it does not already exist
244
-		$configFilePath = self::$configDir .'/config.php';
245
-		if (!file_exists($configFilePath)) {
246
-			@touch($configFilePath);
247
-		}
248
-
249
-		// Check if config is writable
250
-		$configFileWritable = is_writable($configFilePath);
251
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
252
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
253
-			$urlGenerator = Server::get(IURLGenerator::class);
254
-
255
-			if (self::$CLI) {
256
-				echo $l->t('Cannot write into "config" directory!')."\n";
257
-				echo $l->t('This can usually be fixed by giving the web server write access to the config directory.')."\n";
258
-				echo "\n";
259
-				echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
260
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
261
-				exit;
262
-			} else {
263
-				OC_Template::printErrorPage(
264
-					$l->t('Cannot write into "config" directory!'),
265
-					$l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
266
-					. $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
267
-					. $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
268
-					503
269
-				);
270
-			}
271
-		}
272
-	}
273
-
274
-	public static function checkInstalled(\OC\SystemConfig $systemConfig): void {
275
-		if (defined('OC_CONSOLE')) {
276
-			return;
277
-		}
278
-		// Redirect to installer if not installed
279
-		if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
280
-			if (OC::$CLI) {
281
-				throw new Exception('Not installed');
282
-			} else {
283
-				$url = OC::$WEBROOT . '/index.php';
284
-				header('Location: ' . $url);
285
-			}
286
-			exit();
287
-		}
288
-	}
289
-
290
-	public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void {
291
-		// Allow ajax update script to execute without being stopped
292
-		if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
293
-			// send http status 503
294
-			http_response_code(503);
295
-			header('X-Nextcloud-Maintenance-Mode: 1');
296
-			header('Retry-After: 120');
297
-
298
-			// render error page
299
-			$template = new OC_Template('', 'update.user', 'guest');
300
-			\OCP\Util::addScript('core', 'maintenance');
301
-			\OCP\Util::addStyle('core', 'guest');
302
-			$template->printPage();
303
-			die();
304
-		}
305
-	}
306
-
307
-	/**
308
-	 * Prints the upgrade page
309
-	 */
310
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
311
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
312
-		$tooBig = false;
313
-		if (!$disableWebUpdater) {
314
-			$apps = Server::get(\OCP\App\IAppManager::class);
315
-			if ($apps->isInstalled('user_ldap')) {
316
-				$qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
317
-
318
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
319
-					->from('ldap_user_mapping')
320
-					->executeQuery();
321
-				$row = $result->fetch();
322
-				$result->closeCursor();
323
-
324
-				$tooBig = ($row['user_count'] > 50);
325
-			}
326
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
327
-				$qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
328
-
329
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
330
-					->from('user_saml_users')
331
-					->executeQuery();
332
-				$row = $result->fetch();
333
-				$result->closeCursor();
334
-
335
-				$tooBig = ($row['user_count'] > 50);
336
-			}
337
-			if (!$tooBig) {
338
-				// count users
339
-				$stats = Server::get(\OCP\IUserManager::class)->countUsers();
340
-				$totalUsers = array_sum($stats);
341
-				$tooBig = ($totalUsers > 50);
342
-			}
343
-		}
344
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
345
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
346
-
347
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
348
-			// send http status 503
349
-			http_response_code(503);
350
-			header('Retry-After: 120');
351
-
352
-			// render error page
353
-			$template = new OC_Template('', 'update.use-cli', 'guest');
354
-			$template->assign('productName', 'nextcloud'); // for now
355
-			$template->assign('version', OC_Util::getVersionString());
356
-			$template->assign('tooBig', $tooBig);
357
-
358
-			$template->printPage();
359
-			die();
360
-		}
361
-
362
-		// check whether this is a core update or apps update
363
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
364
-		$currentVersion = implode('.', \OCP\Util::getVersion());
365
-
366
-		// if not a core upgrade, then it's apps upgrade
367
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
368
-
369
-		$oldTheme = $systemConfig->getValue('theme');
370
-		$systemConfig->setValue('theme', '');
371
-		\OCP\Util::addScript('core', 'common');
372
-		\OCP\Util::addScript('core', 'main');
373
-		\OCP\Util::addTranslations('core');
374
-		\OCP\Util::addScript('core', 'update');
375
-
376
-		/** @var \OC\App\AppManager $appManager */
377
-		$appManager = Server::get(\OCP\App\IAppManager::class);
378
-
379
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
380
-		$tmpl->assign('version', OC_Util::getVersionString());
381
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
382
-
383
-		// get third party apps
384
-		$ocVersion = \OCP\Util::getVersion();
385
-		$ocVersion = implode('.', $ocVersion);
386
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
387
-		$incompatibleShippedApps = [];
388
-		foreach ($incompatibleApps as $appInfo) {
389
-			if ($appManager->isShipped($appInfo['id'])) {
390
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
391
-			}
392
-		}
393
-
394
-		if (!empty($incompatibleShippedApps)) {
395
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('core');
396
-			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
397
-			throw new \OCP\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
398
-		}
399
-
400
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
401
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
402
-		try {
403
-			$defaults = new \OC_Defaults();
404
-			$tmpl->assign('productName', $defaults->getName());
405
-		} catch (Throwable $error) {
406
-			$tmpl->assign('productName', 'Nextcloud');
407
-		}
408
-		$tmpl->assign('oldTheme', $oldTheme);
409
-		$tmpl->printPage();
410
-	}
411
-
412
-	public static function initSession(): void {
413
-		$request = Server::get(IRequest::class);
414
-
415
-		// TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies
416
-		// TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments
417
-		// TODO: for further information.
418
-		// $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0;
419
-		// if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) {
420
-		// setcookie('cookie_test', 'test', time() + 3600);
421
-		// // Do not initialize the session if a request is authenticated directly
422
-		// // unless there is a session cookie already sent along
423
-		// return;
424
-		// }
425
-
426
-		if ($request->getServerProtocol() === 'https') {
427
-			ini_set('session.cookie_secure', 'true');
428
-		}
429
-
430
-		// prevents javascript from accessing php session cookies
431
-		ini_set('session.cookie_httponly', 'true');
432
-
433
-		// set the cookie path to the Nextcloud directory
434
-		$cookie_path = OC::$WEBROOT ? : '/';
435
-		ini_set('session.cookie_path', $cookie_path);
436
-
437
-		// Let the session name be changed in the initSession Hook
438
-		$sessionName = OC_Util::getInstanceId();
439
-
440
-		try {
441
-			// set the session name to the instance id - which is unique
442
-			$session = new \OC\Session\Internal($sessionName);
443
-
444
-			$cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class);
445
-			$session = $cryptoWrapper->wrapSession($session);
446
-			self::$server->setSession($session);
447
-
448
-			// if session can't be started break with http 500 error
449
-		} catch (Exception $e) {
450
-			Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
451
-			//show the user a detailed error page
452
-			OC_Template::printExceptionErrorPage($e, 500);
453
-			die();
454
-		}
455
-
456
-		//try to set the session lifetime
457
-		$sessionLifeTime = self::getSessionLifeTime();
458
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
459
-
460
-		// session timeout
461
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
462
-			if (isset($_COOKIE[session_name()])) {
463
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
464
-			}
465
-			Server::get(IUserSession::class)->logout();
466
-		}
467
-
468
-		if (!self::hasSessionRelaxedExpiry()) {
469
-			$session->set('LAST_ACTIVITY', time());
470
-		}
471
-		$session->close();
472
-	}
473
-
474
-	private static function getSessionLifeTime(): int {
475
-		return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24);
476
-	}
477
-
478
-	/**
479
-	 * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
480
-	 */
481
-	public static function hasSessionRelaxedExpiry(): bool {
482
-		return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false);
483
-	}
484
-
485
-	/**
486
-	 * Try to set some values to the required Nextcloud default
487
-	 */
488
-	public static function setRequiredIniValues(): void {
489
-		@ini_set('default_charset', 'UTF-8');
490
-		@ini_set('gd.jpeg_ignore_warning', '1');
491
-	}
492
-
493
-	/**
494
-	 * Send the same site cookies
495
-	 */
496
-	private static function sendSameSiteCookies(): void {
497
-		$cookieParams = session_get_cookie_params();
498
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
499
-		$policies = [
500
-			'lax',
501
-			'strict',
502
-		];
503
-
504
-		// Append __Host to the cookie if it meets the requirements
505
-		$cookiePrefix = '';
506
-		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
507
-			$cookiePrefix = '__Host-';
508
-		}
509
-
510
-		foreach ($policies as $policy) {
511
-			header(
512
-				sprintf(
513
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
514
-					$cookiePrefix,
515
-					$policy,
516
-					$cookieParams['path'],
517
-					$policy
518
-				),
519
-				false
520
-			);
521
-		}
522
-	}
523
-
524
-	/**
525
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
526
-	 * be set in every request if cookies are sent to add a second level of
527
-	 * defense against CSRF.
528
-	 *
529
-	 * If the cookie is not sent this will set the cookie and reload the page.
530
-	 * We use an additional cookie since we want to protect logout CSRF and
531
-	 * also we can't directly interfere with PHP's session mechanism.
532
-	 */
533
-	private static function performSameSiteCookieProtection(\OCP\IConfig $config): void {
534
-		$request = Server::get(IRequest::class);
535
-
536
-		// Some user agents are notorious and don't really properly follow HTTP
537
-		// specifications. For those, have an automated opt-out. Since the protection
538
-		// for remote.php is applied in base.php as starting point we need to opt out
539
-		// here.
540
-		$incompatibleUserAgents = $config->getSystemValue('csrf.optout');
541
-
542
-		// Fallback, if csrf.optout is unset
543
-		if (!is_array($incompatibleUserAgents)) {
544
-			$incompatibleUserAgents = [
545
-				// OS X Finder
546
-				'/^WebDAVFS/',
547
-				// Windows webdav drive
548
-				'/^Microsoft-WebDAV-MiniRedir/',
549
-			];
550
-		}
551
-
552
-		if ($request->isUserAgent($incompatibleUserAgents)) {
553
-			return;
554
-		}
555
-
556
-		if (count($_COOKIE) > 0) {
557
-			$requestUri = $request->getScriptName();
558
-			$processingScript = explode('/', $requestUri);
559
-			$processingScript = $processingScript[count($processingScript) - 1];
560
-
561
-			// index.php routes are handled in the middleware
562
-			if ($processingScript === 'index.php') {
563
-				return;
564
-			}
565
-
566
-			// All other endpoints require the lax and the strict cookie
567
-			if (!$request->passesStrictCookieCheck()) {
568
-				logger('core')->warning('Request does not pass strict cookie check');
569
-				self::sendSameSiteCookies();
570
-				// Debug mode gets access to the resources without strict cookie
571
-				// due to the fact that the SabreDAV browser also lives there.
572
-				if (!$config->getSystemValue('debug', false)) {
573
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
574
-					exit();
575
-				}
576
-			}
577
-		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
578
-			self::sendSameSiteCookies();
579
-		}
580
-	}
581
-
582
-	public static function init(): void {
583
-		// calculate the root directories
584
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
585
-
586
-		// register autoloader
587
-		$loaderStart = microtime(true);
588
-		require_once __DIR__ . '/autoloader.php';
589
-		self::$loader = new \OC\Autoloader([
590
-			OC::$SERVERROOT . '/lib/private/legacy',
591
-		]);
592
-		if (defined('PHPUNIT_RUN')) {
593
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
594
-		}
595
-		spl_autoload_register([self::$loader, 'load']);
596
-		$loaderEnd = microtime(true);
597
-
598
-		self::$CLI = (php_sapi_name() == 'cli');
599
-
600
-		// Add default composer PSR-4 autoloader
601
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
602
-		self::$composerAutoloader->setApcuPrefix('composer_autoload');
603
-
604
-		try {
605
-			self::initPaths();
606
-			// setup 3rdparty autoloader
607
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
608
-			if (!file_exists($vendorAutoLoad)) {
609
-				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
610
-			}
611
-			require_once $vendorAutoLoad;
612
-		} catch (\RuntimeException $e) {
613
-			if (!self::$CLI) {
614
-				http_response_code(503);
615
-			}
616
-			// we can't use the template error page here, because this needs the
617
-			// DI container which isn't available yet
618
-			print($e->getMessage());
619
-			exit();
620
-		}
621
-
622
-		// setup the basic server
623
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
624
-		self::$server->boot();
625
-
626
-		$eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
627
-		$eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
628
-		$eventLogger->start('boot', 'Initialize');
629
-
630
-		// Override php.ini and log everything if we're troubleshooting
631
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
632
-			error_reporting(E_ALL);
633
-		}
634
-
635
-		// Don't display errors and log them
636
-		@ini_set('display_errors', '0');
637
-		@ini_set('log_errors', '1');
638
-
639
-		if (!date_default_timezone_set('UTC')) {
640
-			throw new \RuntimeException('Could not set timezone to UTC');
641
-		}
642
-
643
-
644
-		//try to configure php to enable big file uploads.
645
-		//this doesn´t work always depending on the webserver and php configuration.
646
-		//Let´s try to overwrite some defaults if they are smaller than 1 hour
647
-
648
-		if (intval(@ini_get('max_execution_time') ?? 0) < 3600) {
649
-			@ini_set('max_execution_time', strval(3600));
650
-		}
651
-
652
-		if (intval(@ini_get('max_input_time') ?? 0) < 3600) {
653
-			@ini_set('max_input_time', strval(3600));
654
-		}
655
-
656
-		//try to set the maximum execution time to the largest time limit we have
657
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
658
-			@set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
659
-		}
660
-
661
-		self::setRequiredIniValues();
662
-		self::handleAuthHeaders();
663
-		$systemConfig = Server::get(\OC\SystemConfig::class);
664
-		self::registerAutoloaderCache($systemConfig);
665
-
666
-		// initialize intl fallback if necessary
667
-		OC_Util::isSetLocaleWorking();
668
-
669
-		$config = Server::get(\OCP\IConfig::class);
670
-		if (!defined('PHPUNIT_RUN')) {
671
-			$errorHandler = new OC\Log\ErrorHandler(
672
-				\OCP\Server::get(\Psr\Log\LoggerInterface::class),
673
-			);
674
-			$exceptionHandler = [$errorHandler, 'onException'];
675
-			if ($config->getSystemValue('debug', false)) {
676
-				set_error_handler([$errorHandler, 'onAll'], E_ALL);
677
-				if (\OC::$CLI) {
678
-					$exceptionHandler = ['OC_Template', 'printExceptionErrorPage'];
679
-				}
680
-			} else {
681
-				set_error_handler([$errorHandler, 'onError']);
682
-			}
683
-			register_shutdown_function([$errorHandler, 'onShutdown']);
684
-			set_exception_handler($exceptionHandler);
685
-		}
686
-
687
-		/** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
688
-		$bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
689
-		$bootstrapCoordinator->runInitialRegistration();
690
-
691
-		$eventLogger->start('init_session', 'Initialize session');
692
-		OC_App::loadApps(['session']);
693
-		if (!self::$CLI) {
694
-			self::initSession();
695
-		}
696
-		$eventLogger->end('init_session');
697
-		self::checkConfig();
698
-		self::checkInstalled($systemConfig);
699
-
700
-		OC_Response::addSecurityHeaders();
701
-
702
-		self::performSameSiteCookieProtection($config);
703
-
704
-		if (!defined('OC_CONSOLE')) {
705
-			$errors = OC_Util::checkServer($systemConfig);
706
-			if (count($errors) > 0) {
707
-				if (!self::$CLI) {
708
-					http_response_code(503);
709
-					OC_Util::addStyle('guest');
710
-					try {
711
-						OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
712
-						exit;
713
-					} catch (\Exception $e) {
714
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
715
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
716
-					}
717
-				}
718
-
719
-				// Convert l10n string into regular string for usage in database
720
-				$staticErrors = [];
721
-				foreach ($errors as $error) {
722
-					echo $error['error'] . "\n";
723
-					echo $error['hint'] . "\n\n";
724
-					$staticErrors[] = [
725
-						'error' => (string)$error['error'],
726
-						'hint' => (string)$error['hint'],
727
-					];
728
-				}
729
-
730
-				try {
731
-					$config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
732
-				} catch (\Exception $e) {
733
-					echo('Writing to database failed');
734
-				}
735
-				exit(1);
736
-			} elseif (self::$CLI && $config->getSystemValue('installed', false)) {
737
-				$config->deleteAppValue('core', 'cronErrors');
738
-			}
739
-		}
740
-
741
-		// User and Groups
742
-		if (!$systemConfig->getValue("installed", false)) {
743
-			self::$server->getSession()->set('user_id', '');
744
-		}
745
-
746
-		OC_User::useBackend(new \OC\User\Database());
747
-		Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
748
-
749
-		// Subscribe to the hook
750
-		\OCP\Util::connectHook(
751
-			'\OCA\Files_Sharing\API\Server2Server',
752
-			'preLoginNameUsedAsUserName',
753
-			'\OC\User\Database',
754
-			'preLoginNameUsedAsUserName'
755
-		);
756
-
757
-		//setup extra user backends
758
-		if (!\OCP\Util::needUpgrade()) {
759
-			OC_User::setupBackends();
760
-		} else {
761
-			// Run upgrades in incognito mode
762
-			OC_User::setIncognitoMode(true);
763
-		}
764
-
765
-		self::registerCleanupHooks($systemConfig);
766
-		self::registerShareHooks($systemConfig);
767
-		self::registerEncryptionWrapperAndHooks();
768
-		self::registerAccountHooks();
769
-		self::registerResourceCollectionHooks();
770
-		self::registerFileReferenceEventListener();
771
-		self::registerRenderReferenceEventListener();
772
-		self::registerAppRestrictionsHooks();
773
-
774
-		// Make sure that the application class is not loaded before the database is setup
775
-		if ($systemConfig->getValue("installed", false)) {
776
-			OC_App::loadApp('settings');
777
-			/* Build core application to make sure that listeners are registered */
778
-			Server::get(\OC\Core\Application::class);
779
-		}
780
-
781
-		//make sure temporary files are cleaned up
782
-		$tmpManager = Server::get(\OCP\ITempManager::class);
783
-		register_shutdown_function([$tmpManager, 'clean']);
784
-		$lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
785
-		register_shutdown_function([$lockProvider, 'releaseAll']);
786
-
787
-		// Check whether the sample configuration has been copied
788
-		if ($systemConfig->getValue('copied_sample_config', false)) {
789
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
790
-			OC_Template::printErrorPage(
791
-				$l->t('Sample configuration detected'),
792
-				$l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
793
-				503
794
-			);
795
-			return;
796
-		}
797
-
798
-		$request = Server::get(IRequest::class);
799
-		$host = $request->getInsecureServerHost();
800
-		/**
801
-		 * if the host passed in headers isn't trusted
802
-		 * FIXME: Should not be in here at all :see_no_evil:
803
-		 */
804
-		if (!OC::$CLI
805
-			&& !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
806
-			&& $config->getSystemValue('installed', false)
807
-		) {
808
-			// Allow access to CSS resources
809
-			$isScssRequest = false;
810
-			if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
811
-				$isScssRequest = true;
812
-			}
813
-
814
-			if (substr($request->getRequestUri(), -11) === '/status.php') {
815
-				http_response_code(400);
816
-				header('Content-Type: application/json');
817
-				echo '{"error": "Trusted domain error.", "code": 15}';
818
-				exit();
819
-			}
820
-
821
-			if (!$isScssRequest) {
822
-				http_response_code(400);
823
-				Server::get(LoggerInterface::class)->info(
824
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
825
-					[
826
-						'app' => 'core',
827
-						'remoteAddress' => $request->getRemoteAddress(),
828
-						'host' => $host,
829
-					]
830
-				);
831
-
832
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
833
-				$tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
834
-				$tmpl->printPage();
835
-
836
-				exit();
837
-			}
838
-		}
839
-		$eventLogger->end('boot');
840
-		$eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
841
-		$eventLogger->start('runtime', 'Runtime');
842
-		$eventLogger->start('request', 'Full request after boot');
843
-		register_shutdown_function(function () use ($eventLogger) {
844
-			$eventLogger->end('request');
845
-		});
846
-	}
847
-
848
-	/**
849
-	 * register hooks for the cleanup of cache and bruteforce protection
850
-	 */
851
-	public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
852
-		//don't try to do this before we are properly setup
853
-		if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
854
-			// NOTE: This will be replaced to use OCP
855
-			$userSession = Server::get(\OC\User\Session::class);
856
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
857
-				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
858
-					// reset brute force delay for this IP address and username
859
-					$uid = $userSession->getUser()->getUID();
860
-					$request = Server::get(IRequest::class);
861
-					$throttler = Server::get(\OC\Security\Bruteforce\Throttler::class);
862
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
863
-				}
864
-
865
-				try {
866
-					$cache = new \OC\Cache\File();
867
-					$cache->gc();
868
-				} catch (\OC\ServerNotAvailableException $e) {
869
-					// not a GC exception, pass it on
870
-					throw $e;
871
-				} catch (\OC\ForbiddenException $e) {
872
-					// filesystem blocked for this request, ignore
873
-				} catch (\Exception $e) {
874
-					// a GC exception should not prevent users from using OC,
875
-					// so log the exception
876
-					Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
877
-						'app' => 'core',
878
-						'exception' => $e,
879
-					]);
880
-				}
881
-			});
882
-		}
883
-	}
884
-
885
-	private static function registerEncryptionWrapperAndHooks(): void {
886
-		$manager = Server::get(\OCP\Encryption\IManager::class);
887
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
888
-
889
-		$enabled = $manager->isEnabled();
890
-		if ($enabled) {
891
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
892
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
893
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
894
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
895
-		}
896
-	}
897
-
898
-	private static function registerAccountHooks(): void {
899
-		/** @var IEventDispatcher $dispatcher */
900
-		$dispatcher = Server::get(IEventDispatcher::class);
901
-		$dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
902
-	}
903
-
904
-	private static function registerAppRestrictionsHooks(): void {
905
-		/** @var \OC\Group\Manager $groupManager */
906
-		$groupManager = Server::get(\OCP\IGroupManager::class);
907
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
908
-			$appManager = Server::get(\OCP\App\IAppManager::class);
909
-			$apps = $appManager->getEnabledAppsForGroup($group);
910
-			foreach ($apps as $appId) {
911
-				$restrictions = $appManager->getAppRestriction($appId);
912
-				if (empty($restrictions)) {
913
-					continue;
914
-				}
915
-				$key = array_search($group->getGID(), $restrictions);
916
-				unset($restrictions[$key]);
917
-				$restrictions = array_values($restrictions);
918
-				if (empty($restrictions)) {
919
-					$appManager->disableApp($appId);
920
-				} else {
921
-					$appManager->enableAppForGroups($appId, $restrictions);
922
-				}
923
-			}
924
-		});
925
-	}
926
-
927
-	private static function registerResourceCollectionHooks(): void {
928
-		\OC\Collaboration\Resources\Listener::register(Server::get(SymfonyAdapter::class), Server::get(IEventDispatcher::class));
929
-	}
930
-
931
-	private static function registerFileReferenceEventListener(): void {
932
-		\OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
933
-	}
934
-
935
-	private static function registerRenderReferenceEventListener() {
936
-		\OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
937
-	}
938
-
939
-	/**
940
-	 * register hooks for sharing
941
-	 */
942
-	public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
943
-		if ($systemConfig->getValue('installed')) {
944
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
945
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
946
-
947
-			/** @var IEventDispatcher $dispatcher */
948
-			$dispatcher = Server::get(IEventDispatcher::class);
949
-			$dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
950
-		}
951
-	}
952
-
953
-	protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
954
-		// The class loader takes an optional low-latency cache, which MUST be
955
-		// namespaced. The instanceid is used for namespacing, but might be
956
-		// unavailable at this point. Furthermore, it might not be possible to
957
-		// generate an instanceid via \OC_Util::getInstanceId() because the
958
-		// config file may not be writable. As such, we only register a class
959
-		// loader cache if instanceid is available without trying to create one.
960
-		$instanceId = $systemConfig->getValue('instanceid', null);
961
-		if ($instanceId) {
962
-			try {
963
-				$memcacheFactory = Server::get(\OCP\ICacheFactory::class);
964
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
965
-			} catch (\Exception $ex) {
966
-			}
967
-		}
968
-	}
969
-
970
-	/**
971
-	 * Handle the request
972
-	 */
973
-	public static function handleRequest(): void {
974
-		Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
975
-		$systemConfig = Server::get(\OC\SystemConfig::class);
976
-
977
-		// Check if Nextcloud is installed or in maintenance (update) mode
978
-		if (!$systemConfig->getValue('installed', false)) {
979
-			\OC::$server->getSession()->clear();
980
-			$setupHelper = new OC\Setup(
981
-				$systemConfig,
982
-				Server::get(\bantu\IniGetWrapper\IniGetWrapper::class),
983
-				Server::get(\OCP\L10N\IFactory::class)->get('lib'),
984
-				Server::get(\OCP\Defaults::class),
985
-				Server::get(\Psr\Log\LoggerInterface::class),
986
-				Server::get(\OCP\Security\ISecureRandom::class),
987
-				Server::get(\OC\Installer::class)
988
-			);
989
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
990
-			$controller->run($_POST);
991
-			exit();
992
-		}
993
-
994
-		$request = Server::get(IRequest::class);
995
-		$requestPath = $request->getRawPathInfo();
996
-		if ($requestPath === '/heartbeat') {
997
-			return;
998
-		}
999
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
1000
-			self::checkMaintenanceMode($systemConfig);
1001
-
1002
-			if (\OCP\Util::needUpgrade()) {
1003
-				if (function_exists('opcache_reset')) {
1004
-					opcache_reset();
1005
-				}
1006
-				if (!((bool) $systemConfig->getValue('maintenance', false))) {
1007
-					self::printUpgradePage($systemConfig);
1008
-					exit();
1009
-				}
1010
-			}
1011
-		}
1012
-
1013
-		// emergency app disabling
1014
-		if ($requestPath === '/disableapp'
1015
-			&& $request->getMethod() === 'POST'
1016
-		) {
1017
-			\OC_JSON::callCheck();
1018
-			\OC_JSON::checkAdminUser();
1019
-			$appIds = (array)$request->getParam('appid');
1020
-			foreach ($appIds as $appId) {
1021
-				$appId = \OC_App::cleanAppId($appId);
1022
-				Server::get(\OCP\App\IAppManager::class)->disableApp($appId);
1023
-			}
1024
-			\OC_JSON::success();
1025
-			exit();
1026
-		}
1027
-
1028
-		// Always load authentication apps
1029
-		OC_App::loadApps(['authentication']);
1030
-		OC_App::loadApps(['extended_authentication']);
1031
-
1032
-		// Load minimum set of apps
1033
-		if (!\OCP\Util::needUpgrade()
1034
-			&& !((bool) $systemConfig->getValue('maintenance', false))) {
1035
-			// For logged-in users: Load everything
1036
-			if (Server::get(IUserSession::class)->isLoggedIn()) {
1037
-				OC_App::loadApps();
1038
-			} else {
1039
-				// For guests: Load only filesystem and logging
1040
-				OC_App::loadApps(['filesystem', 'logging']);
1041
-
1042
-				// Don't try to login when a client is trying to get a OAuth token.
1043
-				// OAuth needs to support basic auth too, so the login is not valid
1044
-				// inside Nextcloud and the Login exception would ruin it.
1045
-				if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1046
-					self::handleLogin($request);
1047
-				}
1048
-			}
1049
-		}
1050
-
1051
-		if (!self::$CLI) {
1052
-			try {
1053
-				if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1054
-					OC_App::loadApps(['filesystem', 'logging']);
1055
-					OC_App::loadApps();
1056
-				}
1057
-				Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1058
-				return;
1059
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1060
-				//header('HTTP/1.0 404 Not Found');
1061
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1062
-				http_response_code(405);
1063
-				return;
1064
-			}
1065
-		}
1066
-
1067
-		// Handle WebDAV
1068
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1069
-			// not allowed any more to prevent people
1070
-			// mounting this root directly.
1071
-			// Users need to mount remote.php/webdav instead.
1072
-			http_response_code(405);
1073
-			return;
1074
-		}
1075
-
1076
-		// Handle requests for JSON or XML
1077
-		$acceptHeader = $request->getHeader('Accept');
1078
-		if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1079
-			http_response_code(404);
1080
-			return;
1081
-		}
1082
-
1083
-		// Handle resources that can't be found
1084
-		// This prevents browsers from redirecting to the default page and then
1085
-		// attempting to parse HTML as CSS and similar.
1086
-		$destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1087
-		if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1088
-			http_response_code(404);
1089
-			return;
1090
-		}
1091
-
1092
-		// Redirect to the default app or login only as an entry point
1093
-		if ($requestPath === '') {
1094
-			// Someone is logged in
1095
-			if (Server::get(IUserSession::class)->isLoggedIn()) {
1096
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1097
-			} else {
1098
-				// Not handled and not logged in
1099
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1100
-			}
1101
-			return;
1102
-		}
1103
-
1104
-		try {
1105
-			Server::get(\OC\Route\Router::class)->match('/error/404');
1106
-		} catch (\Exception $e) {
1107
-			if (!$e instanceof MethodNotAllowedException) {
1108
-				logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1109
-			}
1110
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
1111
-			OC_Template::printErrorPage(
1112
-				$l->t('404'),
1113
-				$l->t('The page could not be found on the server.'),
1114
-				404
1115
-			);
1116
-		}
1117
-	}
1118
-
1119
-	/**
1120
-	 * Check login: apache auth, auth token, basic auth
1121
-	 */
1122
-	public static function handleLogin(OCP\IRequest $request): bool {
1123
-		$userSession = Server::get(\OC\User\Session::class);
1124
-		if (OC_User::handleApacheAuth()) {
1125
-			return true;
1126
-		}
1127
-		if ($userSession->tryTokenLogin($request)) {
1128
-			return true;
1129
-		}
1130
-		if (isset($_COOKIE['nc_username'])
1131
-			&& isset($_COOKIE['nc_token'])
1132
-			&& isset($_COOKIE['nc_session_id'])
1133
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1134
-			return true;
1135
-		}
1136
-		if ($userSession->tryBasicAuthLogin($request, Server::get(\OC\Security\Bruteforce\Throttler::class))) {
1137
-			return true;
1138
-		}
1139
-		return false;
1140
-	}
1141
-
1142
-	protected static function handleAuthHeaders(): void {
1143
-		//copy http auth headers for apache+php-fcgid work around
1144
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1145
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1146
-		}
1147
-
1148
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1149
-		$vars = [
1150
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1151
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1152
-		];
1153
-		foreach ($vars as $var) {
1154
-			if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1155
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1156
-				if (count($credentials) === 2) {
1157
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1158
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1159
-					break;
1160
-				}
1161
-			}
1162
-		}
1163
-	}
94
+    /**
95
+     * Associative array for autoloading. classname => filename
96
+     */
97
+    public static array $CLASSPATH = [];
98
+    /**
99
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
100
+     */
101
+    public static string $SERVERROOT = '';
102
+    /**
103
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
104
+     */
105
+    private static string $SUBURI = '';
106
+    /**
107
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
108
+     */
109
+    public static string $WEBROOT = '';
110
+    /**
111
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
112
+     * web path in 'url'
113
+     */
114
+    public static array $APPSROOTS = [];
115
+
116
+    public static string $configDir;
117
+
118
+    /**
119
+     * requested app
120
+     */
121
+    public static string $REQUESTEDAPP = '';
122
+
123
+    /**
124
+     * check if Nextcloud runs in cli mode
125
+     */
126
+    public static bool $CLI = false;
127
+
128
+    public static \OC\Autoloader $loader;
129
+
130
+    public static \Composer\Autoload\ClassLoader $composerAutoloader;
131
+
132
+    public static \OC\Server $server;
133
+
134
+    private static \OC\Config $config;
135
+
136
+    /**
137
+     * @throws \RuntimeException when the 3rdparty directory is missing or
138
+     * the app path list is empty or contains an invalid path
139
+     */
140
+    public static function initPaths(): void {
141
+        if (defined('PHPUNIT_CONFIG_DIR')) {
142
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
143
+        } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
144
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
145
+        } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
146
+            self::$configDir = rtrim($dir, '/') . '/';
147
+        } else {
148
+            self::$configDir = OC::$SERVERROOT . '/config/';
149
+        }
150
+        self::$config = new \OC\Config(self::$configDir);
151
+
152
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"] ?? ''), strlen(OC::$SERVERROOT)));
153
+        /**
154
+         * FIXME: The following lines are required because we can't yet instantiate
155
+         *        Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist.
156
+         */
157
+        $params = [
158
+            'server' => [
159
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null,
160
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null,
161
+            ],
162
+        ];
163
+        $fakeRequest = new \OC\AppFramework\Http\Request(
164
+            $params,
165
+            new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
166
+            new \OC\AllConfig(new \OC\SystemConfig(self::$config))
167
+        );
168
+        $scriptName = $fakeRequest->getScriptName();
169
+        if (substr($scriptName, -1) == '/') {
170
+            $scriptName .= 'index.php';
171
+            //make sure suburi follows the same rules as scriptName
172
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
173
+                if (substr(OC::$SUBURI, -1) != '/') {
174
+                    OC::$SUBURI = OC::$SUBURI . '/';
175
+                }
176
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
177
+            }
178
+        }
179
+
180
+
181
+        if (OC::$CLI) {
182
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
183
+        } else {
184
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
185
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
186
+
187
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
188
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
189
+                }
190
+            } else {
191
+                // The scriptName is not ending with OC::$SUBURI
192
+                // This most likely means that we are calling from CLI.
193
+                // However some cron jobs still need to generate
194
+                // a web URL, so we use overwritewebroot as a fallback.
195
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
196
+            }
197
+
198
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
199
+            // slash which is required by URL generation.
200
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
201
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
202
+                header('Location: '.\OC::$WEBROOT.'/');
203
+                exit();
204
+            }
205
+        }
206
+
207
+        // search the apps folder
208
+        $config_paths = self::$config->getValue('apps_paths', []);
209
+        if (!empty($config_paths)) {
210
+            foreach ($config_paths as $paths) {
211
+                if (isset($paths['url']) && isset($paths['path'])) {
212
+                    $paths['url'] = rtrim($paths['url'], '/');
213
+                    $paths['path'] = rtrim($paths['path'], '/');
214
+                    OC::$APPSROOTS[] = $paths;
215
+                }
216
+            }
217
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
218
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
219
+        }
220
+
221
+        if (empty(OC::$APPSROOTS)) {
222
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
223
+                . '. You can also configure the location in the config.php file.');
224
+        }
225
+        $paths = [];
226
+        foreach (OC::$APPSROOTS as $path) {
227
+            $paths[] = $path['path'];
228
+            if (!is_dir($path['path'])) {
229
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
230
+                    . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
231
+            }
232
+        }
233
+
234
+        // set the right include path
235
+        set_include_path(
236
+            implode(PATH_SEPARATOR, $paths)
237
+        );
238
+    }
239
+
240
+    public static function checkConfig(): void {
241
+        $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
242
+
243
+        // Create config if it does not already exist
244
+        $configFilePath = self::$configDir .'/config.php';
245
+        if (!file_exists($configFilePath)) {
246
+            @touch($configFilePath);
247
+        }
248
+
249
+        // Check if config is writable
250
+        $configFileWritable = is_writable($configFilePath);
251
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
252
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
253
+            $urlGenerator = Server::get(IURLGenerator::class);
254
+
255
+            if (self::$CLI) {
256
+                echo $l->t('Cannot write into "config" directory!')."\n";
257
+                echo $l->t('This can usually be fixed by giving the web server write access to the config directory.')."\n";
258
+                echo "\n";
259
+                echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
260
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
261
+                exit;
262
+            } else {
263
+                OC_Template::printErrorPage(
264
+                    $l->t('Cannot write into "config" directory!'),
265
+                    $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
266
+                    . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
267
+                    . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
268
+                    503
269
+                );
270
+            }
271
+        }
272
+    }
273
+
274
+    public static function checkInstalled(\OC\SystemConfig $systemConfig): void {
275
+        if (defined('OC_CONSOLE')) {
276
+            return;
277
+        }
278
+        // Redirect to installer if not installed
279
+        if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
280
+            if (OC::$CLI) {
281
+                throw new Exception('Not installed');
282
+            } else {
283
+                $url = OC::$WEBROOT . '/index.php';
284
+                header('Location: ' . $url);
285
+            }
286
+            exit();
287
+        }
288
+    }
289
+
290
+    public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void {
291
+        // Allow ajax update script to execute without being stopped
292
+        if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
293
+            // send http status 503
294
+            http_response_code(503);
295
+            header('X-Nextcloud-Maintenance-Mode: 1');
296
+            header('Retry-After: 120');
297
+
298
+            // render error page
299
+            $template = new OC_Template('', 'update.user', 'guest');
300
+            \OCP\Util::addScript('core', 'maintenance');
301
+            \OCP\Util::addStyle('core', 'guest');
302
+            $template->printPage();
303
+            die();
304
+        }
305
+    }
306
+
307
+    /**
308
+     * Prints the upgrade page
309
+     */
310
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
311
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
312
+        $tooBig = false;
313
+        if (!$disableWebUpdater) {
314
+            $apps = Server::get(\OCP\App\IAppManager::class);
315
+            if ($apps->isInstalled('user_ldap')) {
316
+                $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
317
+
318
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
319
+                    ->from('ldap_user_mapping')
320
+                    ->executeQuery();
321
+                $row = $result->fetch();
322
+                $result->closeCursor();
323
+
324
+                $tooBig = ($row['user_count'] > 50);
325
+            }
326
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
327
+                $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
328
+
329
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
330
+                    ->from('user_saml_users')
331
+                    ->executeQuery();
332
+                $row = $result->fetch();
333
+                $result->closeCursor();
334
+
335
+                $tooBig = ($row['user_count'] > 50);
336
+            }
337
+            if (!$tooBig) {
338
+                // count users
339
+                $stats = Server::get(\OCP\IUserManager::class)->countUsers();
340
+                $totalUsers = array_sum($stats);
341
+                $tooBig = ($totalUsers > 50);
342
+            }
343
+        }
344
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
345
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
346
+
347
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
348
+            // send http status 503
349
+            http_response_code(503);
350
+            header('Retry-After: 120');
351
+
352
+            // render error page
353
+            $template = new OC_Template('', 'update.use-cli', 'guest');
354
+            $template->assign('productName', 'nextcloud'); // for now
355
+            $template->assign('version', OC_Util::getVersionString());
356
+            $template->assign('tooBig', $tooBig);
357
+
358
+            $template->printPage();
359
+            die();
360
+        }
361
+
362
+        // check whether this is a core update or apps update
363
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
364
+        $currentVersion = implode('.', \OCP\Util::getVersion());
365
+
366
+        // if not a core upgrade, then it's apps upgrade
367
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
368
+
369
+        $oldTheme = $systemConfig->getValue('theme');
370
+        $systemConfig->setValue('theme', '');
371
+        \OCP\Util::addScript('core', 'common');
372
+        \OCP\Util::addScript('core', 'main');
373
+        \OCP\Util::addTranslations('core');
374
+        \OCP\Util::addScript('core', 'update');
375
+
376
+        /** @var \OC\App\AppManager $appManager */
377
+        $appManager = Server::get(\OCP\App\IAppManager::class);
378
+
379
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
380
+        $tmpl->assign('version', OC_Util::getVersionString());
381
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
382
+
383
+        // get third party apps
384
+        $ocVersion = \OCP\Util::getVersion();
385
+        $ocVersion = implode('.', $ocVersion);
386
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
387
+        $incompatibleShippedApps = [];
388
+        foreach ($incompatibleApps as $appInfo) {
389
+            if ($appManager->isShipped($appInfo['id'])) {
390
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
391
+            }
392
+        }
393
+
394
+        if (!empty($incompatibleShippedApps)) {
395
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('core');
396
+            $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
397
+            throw new \OCP\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
398
+        }
399
+
400
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
401
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
402
+        try {
403
+            $defaults = new \OC_Defaults();
404
+            $tmpl->assign('productName', $defaults->getName());
405
+        } catch (Throwable $error) {
406
+            $tmpl->assign('productName', 'Nextcloud');
407
+        }
408
+        $tmpl->assign('oldTheme', $oldTheme);
409
+        $tmpl->printPage();
410
+    }
411
+
412
+    public static function initSession(): void {
413
+        $request = Server::get(IRequest::class);
414
+
415
+        // TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies
416
+        // TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments
417
+        // TODO: for further information.
418
+        // $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0;
419
+        // if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) {
420
+        // setcookie('cookie_test', 'test', time() + 3600);
421
+        // // Do not initialize the session if a request is authenticated directly
422
+        // // unless there is a session cookie already sent along
423
+        // return;
424
+        // }
425
+
426
+        if ($request->getServerProtocol() === 'https') {
427
+            ini_set('session.cookie_secure', 'true');
428
+        }
429
+
430
+        // prevents javascript from accessing php session cookies
431
+        ini_set('session.cookie_httponly', 'true');
432
+
433
+        // set the cookie path to the Nextcloud directory
434
+        $cookie_path = OC::$WEBROOT ? : '/';
435
+        ini_set('session.cookie_path', $cookie_path);
436
+
437
+        // Let the session name be changed in the initSession Hook
438
+        $sessionName = OC_Util::getInstanceId();
439
+
440
+        try {
441
+            // set the session name to the instance id - which is unique
442
+            $session = new \OC\Session\Internal($sessionName);
443
+
444
+            $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class);
445
+            $session = $cryptoWrapper->wrapSession($session);
446
+            self::$server->setSession($session);
447
+
448
+            // if session can't be started break with http 500 error
449
+        } catch (Exception $e) {
450
+            Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
451
+            //show the user a detailed error page
452
+            OC_Template::printExceptionErrorPage($e, 500);
453
+            die();
454
+        }
455
+
456
+        //try to set the session lifetime
457
+        $sessionLifeTime = self::getSessionLifeTime();
458
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
459
+
460
+        // session timeout
461
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
462
+            if (isset($_COOKIE[session_name()])) {
463
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
464
+            }
465
+            Server::get(IUserSession::class)->logout();
466
+        }
467
+
468
+        if (!self::hasSessionRelaxedExpiry()) {
469
+            $session->set('LAST_ACTIVITY', time());
470
+        }
471
+        $session->close();
472
+    }
473
+
474
+    private static function getSessionLifeTime(): int {
475
+        return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24);
476
+    }
477
+
478
+    /**
479
+     * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
480
+     */
481
+    public static function hasSessionRelaxedExpiry(): bool {
482
+        return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false);
483
+    }
484
+
485
+    /**
486
+     * Try to set some values to the required Nextcloud default
487
+     */
488
+    public static function setRequiredIniValues(): void {
489
+        @ini_set('default_charset', 'UTF-8');
490
+        @ini_set('gd.jpeg_ignore_warning', '1');
491
+    }
492
+
493
+    /**
494
+     * Send the same site cookies
495
+     */
496
+    private static function sendSameSiteCookies(): void {
497
+        $cookieParams = session_get_cookie_params();
498
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
499
+        $policies = [
500
+            'lax',
501
+            'strict',
502
+        ];
503
+
504
+        // Append __Host to the cookie if it meets the requirements
505
+        $cookiePrefix = '';
506
+        if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
507
+            $cookiePrefix = '__Host-';
508
+        }
509
+
510
+        foreach ($policies as $policy) {
511
+            header(
512
+                sprintf(
513
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
514
+                    $cookiePrefix,
515
+                    $policy,
516
+                    $cookieParams['path'],
517
+                    $policy
518
+                ),
519
+                false
520
+            );
521
+        }
522
+    }
523
+
524
+    /**
525
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
526
+     * be set in every request if cookies are sent to add a second level of
527
+     * defense against CSRF.
528
+     *
529
+     * If the cookie is not sent this will set the cookie and reload the page.
530
+     * We use an additional cookie since we want to protect logout CSRF and
531
+     * also we can't directly interfere with PHP's session mechanism.
532
+     */
533
+    private static function performSameSiteCookieProtection(\OCP\IConfig $config): void {
534
+        $request = Server::get(IRequest::class);
535
+
536
+        // Some user agents are notorious and don't really properly follow HTTP
537
+        // specifications. For those, have an automated opt-out. Since the protection
538
+        // for remote.php is applied in base.php as starting point we need to opt out
539
+        // here.
540
+        $incompatibleUserAgents = $config->getSystemValue('csrf.optout');
541
+
542
+        // Fallback, if csrf.optout is unset
543
+        if (!is_array($incompatibleUserAgents)) {
544
+            $incompatibleUserAgents = [
545
+                // OS X Finder
546
+                '/^WebDAVFS/',
547
+                // Windows webdav drive
548
+                '/^Microsoft-WebDAV-MiniRedir/',
549
+            ];
550
+        }
551
+
552
+        if ($request->isUserAgent($incompatibleUserAgents)) {
553
+            return;
554
+        }
555
+
556
+        if (count($_COOKIE) > 0) {
557
+            $requestUri = $request->getScriptName();
558
+            $processingScript = explode('/', $requestUri);
559
+            $processingScript = $processingScript[count($processingScript) - 1];
560
+
561
+            // index.php routes are handled in the middleware
562
+            if ($processingScript === 'index.php') {
563
+                return;
564
+            }
565
+
566
+            // All other endpoints require the lax and the strict cookie
567
+            if (!$request->passesStrictCookieCheck()) {
568
+                logger('core')->warning('Request does not pass strict cookie check');
569
+                self::sendSameSiteCookies();
570
+                // Debug mode gets access to the resources without strict cookie
571
+                // due to the fact that the SabreDAV browser also lives there.
572
+                if (!$config->getSystemValue('debug', false)) {
573
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
574
+                    exit();
575
+                }
576
+            }
577
+        } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
578
+            self::sendSameSiteCookies();
579
+        }
580
+    }
581
+
582
+    public static function init(): void {
583
+        // calculate the root directories
584
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
585
+
586
+        // register autoloader
587
+        $loaderStart = microtime(true);
588
+        require_once __DIR__ . '/autoloader.php';
589
+        self::$loader = new \OC\Autoloader([
590
+            OC::$SERVERROOT . '/lib/private/legacy',
591
+        ]);
592
+        if (defined('PHPUNIT_RUN')) {
593
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
594
+        }
595
+        spl_autoload_register([self::$loader, 'load']);
596
+        $loaderEnd = microtime(true);
597
+
598
+        self::$CLI = (php_sapi_name() == 'cli');
599
+
600
+        // Add default composer PSR-4 autoloader
601
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
602
+        self::$composerAutoloader->setApcuPrefix('composer_autoload');
603
+
604
+        try {
605
+            self::initPaths();
606
+            // setup 3rdparty autoloader
607
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
608
+            if (!file_exists($vendorAutoLoad)) {
609
+                throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
610
+            }
611
+            require_once $vendorAutoLoad;
612
+        } catch (\RuntimeException $e) {
613
+            if (!self::$CLI) {
614
+                http_response_code(503);
615
+            }
616
+            // we can't use the template error page here, because this needs the
617
+            // DI container which isn't available yet
618
+            print($e->getMessage());
619
+            exit();
620
+        }
621
+
622
+        // setup the basic server
623
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
624
+        self::$server->boot();
625
+
626
+        $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
627
+        $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
628
+        $eventLogger->start('boot', 'Initialize');
629
+
630
+        // Override php.ini and log everything if we're troubleshooting
631
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
632
+            error_reporting(E_ALL);
633
+        }
634
+
635
+        // Don't display errors and log them
636
+        @ini_set('display_errors', '0');
637
+        @ini_set('log_errors', '1');
638
+
639
+        if (!date_default_timezone_set('UTC')) {
640
+            throw new \RuntimeException('Could not set timezone to UTC');
641
+        }
642
+
643
+
644
+        //try to configure php to enable big file uploads.
645
+        //this doesn´t work always depending on the webserver and php configuration.
646
+        //Let´s try to overwrite some defaults if they are smaller than 1 hour
647
+
648
+        if (intval(@ini_get('max_execution_time') ?? 0) < 3600) {
649
+            @ini_set('max_execution_time', strval(3600));
650
+        }
651
+
652
+        if (intval(@ini_get('max_input_time') ?? 0) < 3600) {
653
+            @ini_set('max_input_time', strval(3600));
654
+        }
655
+
656
+        //try to set the maximum execution time to the largest time limit we have
657
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
658
+            @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
659
+        }
660
+
661
+        self::setRequiredIniValues();
662
+        self::handleAuthHeaders();
663
+        $systemConfig = Server::get(\OC\SystemConfig::class);
664
+        self::registerAutoloaderCache($systemConfig);
665
+
666
+        // initialize intl fallback if necessary
667
+        OC_Util::isSetLocaleWorking();
668
+
669
+        $config = Server::get(\OCP\IConfig::class);
670
+        if (!defined('PHPUNIT_RUN')) {
671
+            $errorHandler = new OC\Log\ErrorHandler(
672
+                \OCP\Server::get(\Psr\Log\LoggerInterface::class),
673
+            );
674
+            $exceptionHandler = [$errorHandler, 'onException'];
675
+            if ($config->getSystemValue('debug', false)) {
676
+                set_error_handler([$errorHandler, 'onAll'], E_ALL);
677
+                if (\OC::$CLI) {
678
+                    $exceptionHandler = ['OC_Template', 'printExceptionErrorPage'];
679
+                }
680
+            } else {
681
+                set_error_handler([$errorHandler, 'onError']);
682
+            }
683
+            register_shutdown_function([$errorHandler, 'onShutdown']);
684
+            set_exception_handler($exceptionHandler);
685
+        }
686
+
687
+        /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
688
+        $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
689
+        $bootstrapCoordinator->runInitialRegistration();
690
+
691
+        $eventLogger->start('init_session', 'Initialize session');
692
+        OC_App::loadApps(['session']);
693
+        if (!self::$CLI) {
694
+            self::initSession();
695
+        }
696
+        $eventLogger->end('init_session');
697
+        self::checkConfig();
698
+        self::checkInstalled($systemConfig);
699
+
700
+        OC_Response::addSecurityHeaders();
701
+
702
+        self::performSameSiteCookieProtection($config);
703
+
704
+        if (!defined('OC_CONSOLE')) {
705
+            $errors = OC_Util::checkServer($systemConfig);
706
+            if (count($errors) > 0) {
707
+                if (!self::$CLI) {
708
+                    http_response_code(503);
709
+                    OC_Util::addStyle('guest');
710
+                    try {
711
+                        OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
712
+                        exit;
713
+                    } catch (\Exception $e) {
714
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
715
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
716
+                    }
717
+                }
718
+
719
+                // Convert l10n string into regular string for usage in database
720
+                $staticErrors = [];
721
+                foreach ($errors as $error) {
722
+                    echo $error['error'] . "\n";
723
+                    echo $error['hint'] . "\n\n";
724
+                    $staticErrors[] = [
725
+                        'error' => (string)$error['error'],
726
+                        'hint' => (string)$error['hint'],
727
+                    ];
728
+                }
729
+
730
+                try {
731
+                    $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
732
+                } catch (\Exception $e) {
733
+                    echo('Writing to database failed');
734
+                }
735
+                exit(1);
736
+            } elseif (self::$CLI && $config->getSystemValue('installed', false)) {
737
+                $config->deleteAppValue('core', 'cronErrors');
738
+            }
739
+        }
740
+
741
+        // User and Groups
742
+        if (!$systemConfig->getValue("installed", false)) {
743
+            self::$server->getSession()->set('user_id', '');
744
+        }
745
+
746
+        OC_User::useBackend(new \OC\User\Database());
747
+        Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
748
+
749
+        // Subscribe to the hook
750
+        \OCP\Util::connectHook(
751
+            '\OCA\Files_Sharing\API\Server2Server',
752
+            'preLoginNameUsedAsUserName',
753
+            '\OC\User\Database',
754
+            'preLoginNameUsedAsUserName'
755
+        );
756
+
757
+        //setup extra user backends
758
+        if (!\OCP\Util::needUpgrade()) {
759
+            OC_User::setupBackends();
760
+        } else {
761
+            // Run upgrades in incognito mode
762
+            OC_User::setIncognitoMode(true);
763
+        }
764
+
765
+        self::registerCleanupHooks($systemConfig);
766
+        self::registerShareHooks($systemConfig);
767
+        self::registerEncryptionWrapperAndHooks();
768
+        self::registerAccountHooks();
769
+        self::registerResourceCollectionHooks();
770
+        self::registerFileReferenceEventListener();
771
+        self::registerRenderReferenceEventListener();
772
+        self::registerAppRestrictionsHooks();
773
+
774
+        // Make sure that the application class is not loaded before the database is setup
775
+        if ($systemConfig->getValue("installed", false)) {
776
+            OC_App::loadApp('settings');
777
+            /* Build core application to make sure that listeners are registered */
778
+            Server::get(\OC\Core\Application::class);
779
+        }
780
+
781
+        //make sure temporary files are cleaned up
782
+        $tmpManager = Server::get(\OCP\ITempManager::class);
783
+        register_shutdown_function([$tmpManager, 'clean']);
784
+        $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
785
+        register_shutdown_function([$lockProvider, 'releaseAll']);
786
+
787
+        // Check whether the sample configuration has been copied
788
+        if ($systemConfig->getValue('copied_sample_config', false)) {
789
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
790
+            OC_Template::printErrorPage(
791
+                $l->t('Sample configuration detected'),
792
+                $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
793
+                503
794
+            );
795
+            return;
796
+        }
797
+
798
+        $request = Server::get(IRequest::class);
799
+        $host = $request->getInsecureServerHost();
800
+        /**
801
+         * if the host passed in headers isn't trusted
802
+         * FIXME: Should not be in here at all :see_no_evil:
803
+         */
804
+        if (!OC::$CLI
805
+            && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
806
+            && $config->getSystemValue('installed', false)
807
+        ) {
808
+            // Allow access to CSS resources
809
+            $isScssRequest = false;
810
+            if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
811
+                $isScssRequest = true;
812
+            }
813
+
814
+            if (substr($request->getRequestUri(), -11) === '/status.php') {
815
+                http_response_code(400);
816
+                header('Content-Type: application/json');
817
+                echo '{"error": "Trusted domain error.", "code": 15}';
818
+                exit();
819
+            }
820
+
821
+            if (!$isScssRequest) {
822
+                http_response_code(400);
823
+                Server::get(LoggerInterface::class)->info(
824
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
825
+                    [
826
+                        'app' => 'core',
827
+                        'remoteAddress' => $request->getRemoteAddress(),
828
+                        'host' => $host,
829
+                    ]
830
+                );
831
+
832
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
833
+                $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
834
+                $tmpl->printPage();
835
+
836
+                exit();
837
+            }
838
+        }
839
+        $eventLogger->end('boot');
840
+        $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
841
+        $eventLogger->start('runtime', 'Runtime');
842
+        $eventLogger->start('request', 'Full request after boot');
843
+        register_shutdown_function(function () use ($eventLogger) {
844
+            $eventLogger->end('request');
845
+        });
846
+    }
847
+
848
+    /**
849
+     * register hooks for the cleanup of cache and bruteforce protection
850
+     */
851
+    public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
852
+        //don't try to do this before we are properly setup
853
+        if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
854
+            // NOTE: This will be replaced to use OCP
855
+            $userSession = Server::get(\OC\User\Session::class);
856
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
857
+                if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
858
+                    // reset brute force delay for this IP address and username
859
+                    $uid = $userSession->getUser()->getUID();
860
+                    $request = Server::get(IRequest::class);
861
+                    $throttler = Server::get(\OC\Security\Bruteforce\Throttler::class);
862
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
863
+                }
864
+
865
+                try {
866
+                    $cache = new \OC\Cache\File();
867
+                    $cache->gc();
868
+                } catch (\OC\ServerNotAvailableException $e) {
869
+                    // not a GC exception, pass it on
870
+                    throw $e;
871
+                } catch (\OC\ForbiddenException $e) {
872
+                    // filesystem blocked for this request, ignore
873
+                } catch (\Exception $e) {
874
+                    // a GC exception should not prevent users from using OC,
875
+                    // so log the exception
876
+                    Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
877
+                        'app' => 'core',
878
+                        'exception' => $e,
879
+                    ]);
880
+                }
881
+            });
882
+        }
883
+    }
884
+
885
+    private static function registerEncryptionWrapperAndHooks(): void {
886
+        $manager = Server::get(\OCP\Encryption\IManager::class);
887
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
888
+
889
+        $enabled = $manager->isEnabled();
890
+        if ($enabled) {
891
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
892
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
893
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
894
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
895
+        }
896
+    }
897
+
898
+    private static function registerAccountHooks(): void {
899
+        /** @var IEventDispatcher $dispatcher */
900
+        $dispatcher = Server::get(IEventDispatcher::class);
901
+        $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
902
+    }
903
+
904
+    private static function registerAppRestrictionsHooks(): void {
905
+        /** @var \OC\Group\Manager $groupManager */
906
+        $groupManager = Server::get(\OCP\IGroupManager::class);
907
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
908
+            $appManager = Server::get(\OCP\App\IAppManager::class);
909
+            $apps = $appManager->getEnabledAppsForGroup($group);
910
+            foreach ($apps as $appId) {
911
+                $restrictions = $appManager->getAppRestriction($appId);
912
+                if (empty($restrictions)) {
913
+                    continue;
914
+                }
915
+                $key = array_search($group->getGID(), $restrictions);
916
+                unset($restrictions[$key]);
917
+                $restrictions = array_values($restrictions);
918
+                if (empty($restrictions)) {
919
+                    $appManager->disableApp($appId);
920
+                } else {
921
+                    $appManager->enableAppForGroups($appId, $restrictions);
922
+                }
923
+            }
924
+        });
925
+    }
926
+
927
+    private static function registerResourceCollectionHooks(): void {
928
+        \OC\Collaboration\Resources\Listener::register(Server::get(SymfonyAdapter::class), Server::get(IEventDispatcher::class));
929
+    }
930
+
931
+    private static function registerFileReferenceEventListener(): void {
932
+        \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
933
+    }
934
+
935
+    private static function registerRenderReferenceEventListener() {
936
+        \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
937
+    }
938
+
939
+    /**
940
+     * register hooks for sharing
941
+     */
942
+    public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
943
+        if ($systemConfig->getValue('installed')) {
944
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
945
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
946
+
947
+            /** @var IEventDispatcher $dispatcher */
948
+            $dispatcher = Server::get(IEventDispatcher::class);
949
+            $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
950
+        }
951
+    }
952
+
953
+    protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
954
+        // The class loader takes an optional low-latency cache, which MUST be
955
+        // namespaced. The instanceid is used for namespacing, but might be
956
+        // unavailable at this point. Furthermore, it might not be possible to
957
+        // generate an instanceid via \OC_Util::getInstanceId() because the
958
+        // config file may not be writable. As such, we only register a class
959
+        // loader cache if instanceid is available without trying to create one.
960
+        $instanceId = $systemConfig->getValue('instanceid', null);
961
+        if ($instanceId) {
962
+            try {
963
+                $memcacheFactory = Server::get(\OCP\ICacheFactory::class);
964
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
965
+            } catch (\Exception $ex) {
966
+            }
967
+        }
968
+    }
969
+
970
+    /**
971
+     * Handle the request
972
+     */
973
+    public static function handleRequest(): void {
974
+        Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
975
+        $systemConfig = Server::get(\OC\SystemConfig::class);
976
+
977
+        // Check if Nextcloud is installed or in maintenance (update) mode
978
+        if (!$systemConfig->getValue('installed', false)) {
979
+            \OC::$server->getSession()->clear();
980
+            $setupHelper = new OC\Setup(
981
+                $systemConfig,
982
+                Server::get(\bantu\IniGetWrapper\IniGetWrapper::class),
983
+                Server::get(\OCP\L10N\IFactory::class)->get('lib'),
984
+                Server::get(\OCP\Defaults::class),
985
+                Server::get(\Psr\Log\LoggerInterface::class),
986
+                Server::get(\OCP\Security\ISecureRandom::class),
987
+                Server::get(\OC\Installer::class)
988
+            );
989
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
990
+            $controller->run($_POST);
991
+            exit();
992
+        }
993
+
994
+        $request = Server::get(IRequest::class);
995
+        $requestPath = $request->getRawPathInfo();
996
+        if ($requestPath === '/heartbeat') {
997
+            return;
998
+        }
999
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
1000
+            self::checkMaintenanceMode($systemConfig);
1001
+
1002
+            if (\OCP\Util::needUpgrade()) {
1003
+                if (function_exists('opcache_reset')) {
1004
+                    opcache_reset();
1005
+                }
1006
+                if (!((bool) $systemConfig->getValue('maintenance', false))) {
1007
+                    self::printUpgradePage($systemConfig);
1008
+                    exit();
1009
+                }
1010
+            }
1011
+        }
1012
+
1013
+        // emergency app disabling
1014
+        if ($requestPath === '/disableapp'
1015
+            && $request->getMethod() === 'POST'
1016
+        ) {
1017
+            \OC_JSON::callCheck();
1018
+            \OC_JSON::checkAdminUser();
1019
+            $appIds = (array)$request->getParam('appid');
1020
+            foreach ($appIds as $appId) {
1021
+                $appId = \OC_App::cleanAppId($appId);
1022
+                Server::get(\OCP\App\IAppManager::class)->disableApp($appId);
1023
+            }
1024
+            \OC_JSON::success();
1025
+            exit();
1026
+        }
1027
+
1028
+        // Always load authentication apps
1029
+        OC_App::loadApps(['authentication']);
1030
+        OC_App::loadApps(['extended_authentication']);
1031
+
1032
+        // Load minimum set of apps
1033
+        if (!\OCP\Util::needUpgrade()
1034
+            && !((bool) $systemConfig->getValue('maintenance', false))) {
1035
+            // For logged-in users: Load everything
1036
+            if (Server::get(IUserSession::class)->isLoggedIn()) {
1037
+                OC_App::loadApps();
1038
+            } else {
1039
+                // For guests: Load only filesystem and logging
1040
+                OC_App::loadApps(['filesystem', 'logging']);
1041
+
1042
+                // Don't try to login when a client is trying to get a OAuth token.
1043
+                // OAuth needs to support basic auth too, so the login is not valid
1044
+                // inside Nextcloud and the Login exception would ruin it.
1045
+                if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1046
+                    self::handleLogin($request);
1047
+                }
1048
+            }
1049
+        }
1050
+
1051
+        if (!self::$CLI) {
1052
+            try {
1053
+                if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1054
+                    OC_App::loadApps(['filesystem', 'logging']);
1055
+                    OC_App::loadApps();
1056
+                }
1057
+                Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1058
+                return;
1059
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1060
+                //header('HTTP/1.0 404 Not Found');
1061
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1062
+                http_response_code(405);
1063
+                return;
1064
+            }
1065
+        }
1066
+
1067
+        // Handle WebDAV
1068
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1069
+            // not allowed any more to prevent people
1070
+            // mounting this root directly.
1071
+            // Users need to mount remote.php/webdav instead.
1072
+            http_response_code(405);
1073
+            return;
1074
+        }
1075
+
1076
+        // Handle requests for JSON or XML
1077
+        $acceptHeader = $request->getHeader('Accept');
1078
+        if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1079
+            http_response_code(404);
1080
+            return;
1081
+        }
1082
+
1083
+        // Handle resources that can't be found
1084
+        // This prevents browsers from redirecting to the default page and then
1085
+        // attempting to parse HTML as CSS and similar.
1086
+        $destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1087
+        if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1088
+            http_response_code(404);
1089
+            return;
1090
+        }
1091
+
1092
+        // Redirect to the default app or login only as an entry point
1093
+        if ($requestPath === '') {
1094
+            // Someone is logged in
1095
+            if (Server::get(IUserSession::class)->isLoggedIn()) {
1096
+                header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1097
+            } else {
1098
+                // Not handled and not logged in
1099
+                header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1100
+            }
1101
+            return;
1102
+        }
1103
+
1104
+        try {
1105
+            Server::get(\OC\Route\Router::class)->match('/error/404');
1106
+        } catch (\Exception $e) {
1107
+            if (!$e instanceof MethodNotAllowedException) {
1108
+                logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1109
+            }
1110
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
1111
+            OC_Template::printErrorPage(
1112
+                $l->t('404'),
1113
+                $l->t('The page could not be found on the server.'),
1114
+                404
1115
+            );
1116
+        }
1117
+    }
1118
+
1119
+    /**
1120
+     * Check login: apache auth, auth token, basic auth
1121
+     */
1122
+    public static function handleLogin(OCP\IRequest $request): bool {
1123
+        $userSession = Server::get(\OC\User\Session::class);
1124
+        if (OC_User::handleApacheAuth()) {
1125
+            return true;
1126
+        }
1127
+        if ($userSession->tryTokenLogin($request)) {
1128
+            return true;
1129
+        }
1130
+        if (isset($_COOKIE['nc_username'])
1131
+            && isset($_COOKIE['nc_token'])
1132
+            && isset($_COOKIE['nc_session_id'])
1133
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1134
+            return true;
1135
+        }
1136
+        if ($userSession->tryBasicAuthLogin($request, Server::get(\OC\Security\Bruteforce\Throttler::class))) {
1137
+            return true;
1138
+        }
1139
+        return false;
1140
+    }
1141
+
1142
+    protected static function handleAuthHeaders(): void {
1143
+        //copy http auth headers for apache+php-fcgid work around
1144
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1145
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1146
+        }
1147
+
1148
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1149
+        $vars = [
1150
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1151
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1152
+        ];
1153
+        foreach ($vars as $var) {
1154
+            if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1155
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1156
+                if (count($credentials) === 2) {
1157
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1158
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1159
+                    break;
1160
+                }
1161
+            }
1162
+        }
1163
+    }
1164 1164
 }
1165 1165
 
1166 1166
 OC::init();
Please login to merge, or discard this patch.
ocs/v1.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -31,14 +31,14 @@  discard block
 block discarded – undo
31 31
 require_once __DIR__ . '/../lib/base.php';
32 32
 
33 33
 if (\OCP\Util::needUpgrade()
34
-	|| \OC::$server->getConfig()->getSystemValueBool('maintenance')) {
35
-	// since the behavior of apps or remotes are unpredictable during
36
-	// an upgrade, return a 503 directly
37
-	http_response_code(503);
38
-	header('X-Nextcloud-Maintenance-Mode: 1');
39
-	$response = new \OC\OCS\Result(null, 503, 'Service unavailable');
40
-	OC_API::respond($response, OC_API::requestedFormat());
41
-	exit;
34
+    || \OC::$server->getConfig()->getSystemValueBool('maintenance')) {
35
+    // since the behavior of apps or remotes are unpredictable during
36
+    // an upgrade, return a 503 directly
37
+    http_response_code(503);
38
+    header('X-Nextcloud-Maintenance-Mode: 1');
39
+    $response = new \OC\OCS\Result(null, 503, 'Service unavailable');
40
+    OC_API::respond($response, OC_API::requestedFormat());
41
+    exit;
42 42
 }
43 43
 
44 44
 use Symfony\Component\Routing\Exception\ResourceNotFoundException;
@@ -48,46 +48,46 @@  discard block
 block discarded – undo
48 48
  * Try the appframework routes
49 49
  */
50 50
 try {
51
-	OC_App::loadApps(['session']);
52
-	OC_App::loadApps(['authentication']);
53
-	OC_App::loadApps(['extended_authentication']);
51
+    OC_App::loadApps(['session']);
52
+    OC_App::loadApps(['authentication']);
53
+    OC_App::loadApps(['extended_authentication']);
54 54
 
55
-	// load all apps to get all api routes properly setup
56
-	// FIXME: this should ideally appear after handleLogin but will cause
57
-	// side effects in existing apps
58
-	OC_App::loadApps();
55
+    // load all apps to get all api routes properly setup
56
+    // FIXME: this should ideally appear after handleLogin but will cause
57
+    // side effects in existing apps
58
+    OC_App::loadApps();
59 59
 
60
-	if (!\OC::$server->getUserSession()->isLoggedIn()) {
61
-		OC::handleLogin(\OC::$server->getRequest());
62
-	}
60
+    if (!\OC::$server->getUserSession()->isLoggedIn()) {
61
+        OC::handleLogin(\OC::$server->getRequest());
62
+    }
63 63
 
64
-	OC::$server->get(\OC\Route\Router::class)->match('/ocsapp'.\OC::$server->getRequest()->getRawPathInfo());
64
+    OC::$server->get(\OC\Route\Router::class)->match('/ocsapp'.\OC::$server->getRequest()->getRawPathInfo());
65 65
 } catch (ResourceNotFoundException $e) {
66
-	OC_API::setContentType();
66
+    OC_API::setContentType();
67 67
 
68
-	$format = \OC::$server->getRequest()->getParam('format', 'xml');
69
-	$txt = 'Invalid query, please check the syntax. API specifications are here:'
70
-		.' http://www.freedesktop.org/wiki/Specifications/open-collaboration-services.'."\n";
71
-	OC_API::respond(new \OC\OCS\Result(null, \OCP\AppFramework\OCSController::RESPOND_NOT_FOUND, $txt), $format);
68
+    $format = \OC::$server->getRequest()->getParam('format', 'xml');
69
+    $txt = 'Invalid query, please check the syntax. API specifications are here:'
70
+        .' http://www.freedesktop.org/wiki/Specifications/open-collaboration-services.'."\n";
71
+    OC_API::respond(new \OC\OCS\Result(null, \OCP\AppFramework\OCSController::RESPOND_NOT_FOUND, $txt), $format);
72 72
 } catch (MethodNotAllowedException $e) {
73
-	OC_API::setContentType();
74
-	http_response_code(405);
73
+    OC_API::setContentType();
74
+    http_response_code(405);
75 75
 } catch (\OC\OCS\Exception $ex) {
76
-	OC_API::respond($ex->getResult(), OC_API::requestedFormat());
76
+    OC_API::respond($ex->getResult(), OC_API::requestedFormat());
77 77
 } catch (\OC\User\LoginException $e) {
78
-	OC_API::respond(new \OC\OCS\Result(null, \OCP\AppFramework\OCSController::RESPOND_UNAUTHORISED, 'Unauthorised'));
78
+    OC_API::respond(new \OC\OCS\Result(null, \OCP\AppFramework\OCSController::RESPOND_UNAUTHORISED, 'Unauthorised'));
79 79
 } catch (\Exception $e) {
80
-	\OC::$server->getLogger()->logException($e);
81
-	OC_API::setContentType();
80
+    \OC::$server->getLogger()->logException($e);
81
+    OC_API::setContentType();
82 82
 
83
-	$format = \OC::$server->getRequest()->getParam('format', 'xml');
84
-	$txt = 'Internal Server Error'."\n";
85
-	try {
86
-		if (\OC::$server->getSystemConfig()->getValue('debug', false)) {
87
-			$txt .= $e->getMessage();
88
-		}
89
-	} catch (\Throwable $e) {
90
-		// Just to be save
91
-	}
92
-	OC_API::respond(new \OC\OCS\Result(null, \OCP\AppFramework\OCSController::RESPOND_SERVER_ERROR, $txt), $format);
83
+    $format = \OC::$server->getRequest()->getParam('format', 'xml');
84
+    $txt = 'Internal Server Error'."\n";
85
+    try {
86
+        if (\OC::$server->getSystemConfig()->getValue('debug', false)) {
87
+            $txt .= $e->getMessage();
88
+        }
89
+    } catch (\Throwable $e) {
90
+        // Just to be save
91
+    }
92
+    OC_API::respond(new \OC\OCS\Result(null, \OCP\AppFramework\OCSController::RESPOND_SERVER_ERROR, $txt), $format);
93 93
 }
Please login to merge, or discard this patch.