Completed
Push — master ( efa2cd...12490b )
by Julius
23:42 queued 16s
created
lib/private/Profiler/BuiltInProfiler.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -13,83 +13,83 @@
 block discarded – undo
13 13
 use OCP\IRequest;
14 14
 
15 15
 class BuiltInProfiler {
16
-	private \ExcimerProfiler $excimer;
16
+    private \ExcimerProfiler $excimer;
17 17
 
18
-	public function __construct(
19
-		private IConfig $config,
20
-		private IRequest $request,
21
-	) {
22
-	}
18
+    public function __construct(
19
+        private IConfig $config,
20
+        private IRequest $request,
21
+    ) {
22
+    }
23 23
 
24
-	public function start(): void {
25
-		if (!extension_loaded('excimer')) {
26
-			return;
27
-		}
24
+    public function start(): void {
25
+        if (!extension_loaded('excimer')) {
26
+            return;
27
+        }
28 28
 
29
-		$shouldProfileSingleRequest = $this->shouldProfileSingleRequest();
30
-		$shouldSample = $this->config->getSystemValueBool('profiling.sample') && !$shouldProfileSingleRequest;
29
+        $shouldProfileSingleRequest = $this->shouldProfileSingleRequest();
30
+        $shouldSample = $this->config->getSystemValueBool('profiling.sample') && !$shouldProfileSingleRequest;
31 31
 
32 32
 
33
-		if (!$shouldProfileSingleRequest && !$shouldSample) {
34
-			return;
35
-		}
33
+        if (!$shouldProfileSingleRequest && !$shouldSample) {
34
+            return;
35
+        }
36 36
 
37
-		$requestRate = $this->config->getSystemValue('profiling.request.rate', 0.001);
38
-		$sampleRate = $this->config->getSystemValue('profiling.sample.rate', 1.0);
39
-		$eventType = $this->config->getSystemValue('profiling.event_type', EXCIMER_REAL);
37
+        $requestRate = $this->config->getSystemValue('profiling.request.rate', 0.001);
38
+        $sampleRate = $this->config->getSystemValue('profiling.sample.rate', 1.0);
39
+        $eventType = $this->config->getSystemValue('profiling.event_type', EXCIMER_REAL);
40 40
 
41 41
 
42
-		$this->excimer = new \ExcimerProfiler();
43
-		$this->excimer->setPeriod($shouldProfileSingleRequest ? $requestRate : $sampleRate);
44
-		$this->excimer->setEventType($eventType);
45
-		$this->excimer->setMaxDepth(250);
42
+        $this->excimer = new \ExcimerProfiler();
43
+        $this->excimer->setPeriod($shouldProfileSingleRequest ? $requestRate : $sampleRate);
44
+        $this->excimer->setEventType($eventType);
45
+        $this->excimer->setMaxDepth(250);
46 46
 
47
-		if ($shouldSample) {
48
-			$this->excimer->setFlushCallback([$this, 'handleSampleFlush'], 1);
49
-		}
47
+        if ($shouldSample) {
48
+            $this->excimer->setFlushCallback([$this, 'handleSampleFlush'], 1);
49
+        }
50 50
 
51
-		$this->excimer->start();
52
-		register_shutdown_function([$this, 'handleShutdown']);
53
-	}
51
+        $this->excimer->start();
52
+        register_shutdown_function([$this, 'handleShutdown']);
53
+    }
54 54
 
55
-	public function handleSampleFlush(\ExcimerLog $log): void {
56
-		file_put_contents($this->getSampleFilename(), $log->formatCollapsed(), FILE_APPEND);
57
-	}
55
+    public function handleSampleFlush(\ExcimerLog $log): void {
56
+        file_put_contents($this->getSampleFilename(), $log->formatCollapsed(), FILE_APPEND);
57
+    }
58 58
 
59
-	public function handleShutdown(): void {
60
-		$this->excimer->stop();
59
+    public function handleShutdown(): void {
60
+        $this->excimer->stop();
61 61
 
62
-		if (!$this->shouldProfileSingleRequest()) {
63
-			$this->excimer->flush();
64
-			return;
65
-		}
62
+        if (!$this->shouldProfileSingleRequest()) {
63
+            $this->excimer->flush();
64
+            return;
65
+        }
66 66
 
67
-		$request = \OCP\Server::get(IRequest::class);
68
-		$data = $this->excimer->getLog()->getSpeedscopeData();
67
+        $request = \OCP\Server::get(IRequest::class);
68
+        $data = $this->excimer->getLog()->getSpeedscopeData();
69 69
 
70
-		$data['profiles'][0]['name'] = $request->getMethod() . ' ' . $request->getRequestUri() . ' ' . $request->getId();
70
+        $data['profiles'][0]['name'] = $request->getMethod() . ' ' . $request->getRequestUri() . ' ' . $request->getId();
71 71
 
72
-		file_put_contents($this->getProfileFilename(), json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
73
-	}
72
+        file_put_contents($this->getProfileFilename(), json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
73
+    }
74 74
 
75
-	private function shouldProfileSingleRequest(): bool {
76
-		$shouldProfileSingleRequest = $this->config->getSystemValueBool('profiling.request', false);
77
-		$profileSecret = $this->config->getSystemValueString('profiling.secret', '');
78
-		$secretParam = $this->request->getParam('profile_secret') ?? null;
79
-		return $shouldProfileSingleRequest || (!empty($profileSecret) && $profileSecret === $secretParam);
80
-	}
75
+    private function shouldProfileSingleRequest(): bool {
76
+        $shouldProfileSingleRequest = $this->config->getSystemValueBool('profiling.request', false);
77
+        $profileSecret = $this->config->getSystemValueString('profiling.secret', '');
78
+        $secretParam = $this->request->getParam('profile_secret') ?? null;
79
+        return $shouldProfileSingleRequest || (!empty($profileSecret) && $profileSecret === $secretParam);
80
+    }
81 81
 
82
-	private function getSampleFilename(): string {
83
-		$profilePath = $this->config->getSystemValueString('profiling.path', '/tmp');
84
-		$sampleRotation = $this->config->getSystemValueInt('profiling.sample.rotation', 60);
85
-		$timestamp = floor(time() / ($sampleRotation * 60)) * ($sampleRotation * 60);
86
-		$sampleName = date('Y-m-d_Hi', (int)$timestamp);
87
-		return $profilePath . '/sample-' . $sampleName . '.log';
88
-	}
82
+    private function getSampleFilename(): string {
83
+        $profilePath = $this->config->getSystemValueString('profiling.path', '/tmp');
84
+        $sampleRotation = $this->config->getSystemValueInt('profiling.sample.rotation', 60);
85
+        $timestamp = floor(time() / ($sampleRotation * 60)) * ($sampleRotation * 60);
86
+        $sampleName = date('Y-m-d_Hi', (int)$timestamp);
87
+        return $profilePath . '/sample-' . $sampleName . '.log';
88
+    }
89 89
 
90
-	private function getProfileFilename(): string {
91
-		$profilePath = $this->config->getSystemValueString('profiling.path', '/tmp');
92
-		$requestId = $this->request->getId();
93
-		return $profilePath . '/profile-' . (new DateTime)->format('Y-m-d_His_v') . '-' . $requestId . '.json';
94
-	}
90
+    private function getProfileFilename(): string {
91
+        $profilePath = $this->config->getSystemValueString('profiling.path', '/tmp');
92
+        $requestId = $this->request->getId();
93
+        return $profilePath . '/profile-' . (new DateTime)->format('Y-m-d_His_v') . '-' . $requestId . '.json';
94
+    }
95 95
 }
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +1145 added lines, -1145 removed lines patch added patch discarded remove patch
@@ -39,1151 +39,1151 @@
 block discarded – undo
39 39
  * OC_autoload!
40 40
  */
41 41
 class OC {
42
-	/**
43
-	 * Associative array for autoloading. classname => filename
44
-	 */
45
-	public static array $CLASSPATH = [];
46
-	/**
47
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
48
-	 */
49
-	public static string $SERVERROOT = '';
50
-	/**
51
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
52
-	 */
53
-	private static string $SUBURI = '';
54
-	/**
55
-	 * the Nextcloud root path for http requests (e.g. /nextcloud)
56
-	 */
57
-	public static string $WEBROOT = '';
58
-	/**
59
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
60
-	 * web path in 'url'
61
-	 */
62
-	public static array $APPSROOTS = [];
63
-
64
-	public static string $configDir;
65
-
66
-	/**
67
-	 * requested app
68
-	 */
69
-	public static string $REQUESTEDAPP = '';
70
-
71
-	/**
72
-	 * check if Nextcloud runs in cli mode
73
-	 */
74
-	public static bool $CLI = false;
75
-
76
-	public static \OC\Autoloader $loader;
77
-
78
-	public static \Composer\Autoload\ClassLoader $composerAutoloader;
79
-
80
-	public static \OC\Server $server;
81
-
82
-	private static \OC\Config $config;
83
-
84
-	/**
85
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
86
-	 *                           the app path list is empty or contains an invalid path
87
-	 */
88
-	public static function initPaths(): void {
89
-		if (defined('PHPUNIT_CONFIG_DIR')) {
90
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
91
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
92
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
93
-		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
94
-			self::$configDir = rtrim($dir, '/') . '/';
95
-		} else {
96
-			self::$configDir = OC::$SERVERROOT . '/config/';
97
-		}
98
-		self::$config = new \OC\Config(self::$configDir);
99
-
100
-		OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT)));
101
-		/**
102
-		 * FIXME: The following lines are required because we can't yet instantiate
103
-		 *        Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist.
104
-		 */
105
-		$params = [
106
-			'server' => [
107
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null,
108
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null,
109
-			],
110
-		];
111
-		if (isset($_SERVER['REMOTE_ADDR'])) {
112
-			$params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
113
-		}
114
-		$fakeRequest = new \OC\AppFramework\Http\Request(
115
-			$params,
116
-			new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
117
-			new \OC\AllConfig(new \OC\SystemConfig(self::$config))
118
-		);
119
-		$scriptName = $fakeRequest->getScriptName();
120
-		if (substr($scriptName, -1) == '/') {
121
-			$scriptName .= 'index.php';
122
-			//make sure suburi follows the same rules as scriptName
123
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
124
-				if (substr(OC::$SUBURI, -1) != '/') {
125
-					OC::$SUBURI = OC::$SUBURI . '/';
126
-				}
127
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
128
-			}
129
-		}
130
-
131
-		if (OC::$CLI) {
132
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
133
-		} else {
134
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
135
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
136
-
137
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
138
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
139
-				}
140
-			} else {
141
-				// The scriptName is not ending with OC::$SUBURI
142
-				// This most likely means that we are calling from CLI.
143
-				// However some cron jobs still need to generate
144
-				// a web URL, so we use overwritewebroot as a fallback.
145
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
146
-			}
147
-
148
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
149
-			// slash which is required by URL generation.
150
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
151
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
152
-				header('Location: ' . \OC::$WEBROOT . '/');
153
-				exit();
154
-			}
155
-		}
156
-
157
-		// search the apps folder
158
-		$config_paths = self::$config->getValue('apps_paths', []);
159
-		if (!empty($config_paths)) {
160
-			foreach ($config_paths as $paths) {
161
-				if (isset($paths['url']) && isset($paths['path'])) {
162
-					$paths['url'] = rtrim($paths['url'], '/');
163
-					$paths['path'] = rtrim($paths['path'], '/');
164
-					OC::$APPSROOTS[] = $paths;
165
-				}
166
-			}
167
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
168
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
169
-		}
170
-
171
-		if (empty(OC::$APPSROOTS)) {
172
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
173
-				. '. You can also configure the location in the config.php file.');
174
-		}
175
-		$paths = [];
176
-		foreach (OC::$APPSROOTS as $path) {
177
-			$paths[] = $path['path'];
178
-			if (!is_dir($path['path'])) {
179
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
180
-					. ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
181
-			}
182
-		}
183
-
184
-		// set the right include path
185
-		set_include_path(
186
-			implode(PATH_SEPARATOR, $paths)
187
-		);
188
-	}
189
-
190
-	public static function checkConfig(): void {
191
-		$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
192
-
193
-		// Create config if it does not already exist
194
-		$configFilePath = self::$configDir . '/config.php';
195
-		if (!file_exists($configFilePath)) {
196
-			@touch($configFilePath);
197
-		}
198
-
199
-		// Check if config is writable
200
-		$configFileWritable = is_writable($configFilePath);
201
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
202
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
203
-			$urlGenerator = Server::get(IURLGenerator::class);
204
-
205
-			if (self::$CLI) {
206
-				echo $l->t('Cannot write into "config" directory!') . "\n";
207
-				echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n";
208
-				echo "\n";
209
-				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";
210
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n";
211
-				exit;
212
-			} else {
213
-				Server::get(ITemplateManager::class)->printErrorPage(
214
-					$l->t('Cannot write into "config" directory!'),
215
-					$l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
216
-					. $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
217
-					. $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
218
-					503
219
-				);
220
-			}
221
-		}
222
-	}
223
-
224
-	public static function checkInstalled(\OC\SystemConfig $systemConfig): void {
225
-		if (defined('OC_CONSOLE')) {
226
-			return;
227
-		}
228
-		// Redirect to installer if not installed
229
-		if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
230
-			if (OC::$CLI) {
231
-				throw new Exception('Not installed');
232
-			} else {
233
-				$url = OC::$WEBROOT . '/index.php';
234
-				header('Location: ' . $url);
235
-			}
236
-			exit();
237
-		}
238
-	}
239
-
240
-	public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void {
241
-		// Allow ajax update script to execute without being stopped
242
-		if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
243
-			// send http status 503
244
-			http_response_code(503);
245
-			header('X-Nextcloud-Maintenance-Mode: 1');
246
-			header('Retry-After: 120');
247
-
248
-			// render error page
249
-			$template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest');
250
-			\OCP\Util::addScript('core', 'maintenance');
251
-			\OCP\Util::addStyle('core', 'guest');
252
-			$template->printPage();
253
-			die();
254
-		}
255
-	}
256
-
257
-	/**
258
-	 * Prints the upgrade page
259
-	 */
260
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
261
-		$cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', '');
262
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
263
-		$tooBig = false;
264
-		if (!$disableWebUpdater) {
265
-			$apps = Server::get(\OCP\App\IAppManager::class);
266
-			if ($apps->isEnabledForAnyone('user_ldap')) {
267
-				$qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
268
-
269
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
270
-					->from('ldap_user_mapping')
271
-					->executeQuery();
272
-				$row = $result->fetch();
273
-				$result->closeCursor();
274
-
275
-				$tooBig = ($row['user_count'] > 50);
276
-			}
277
-			if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) {
278
-				$qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
279
-
280
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
281
-					->from('user_saml_users')
282
-					->executeQuery();
283
-				$row = $result->fetch();
284
-				$result->closeCursor();
285
-
286
-				$tooBig = ($row['user_count'] > 50);
287
-			}
288
-			if (!$tooBig) {
289
-				// count users
290
-				$totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51);
291
-				$tooBig = ($totalUsers > 50);
292
-			}
293
-		}
294
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
295
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
296
-
297
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
298
-			// send http status 503
299
-			http_response_code(503);
300
-			header('Retry-After: 120');
301
-
302
-			$serverVersion = \OCP\Server::get(\OCP\ServerVersion::class);
303
-
304
-			// render error page
305
-			$template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest');
306
-			$template->assign('productName', 'nextcloud'); // for now
307
-			$template->assign('version', $serverVersion->getVersionString());
308
-			$template->assign('tooBig', $tooBig);
309
-			$template->assign('cliUpgradeLink', $cliUpgradeLink);
310
-
311
-			$template->printPage();
312
-			die();
313
-		}
314
-
315
-		// check whether this is a core update or apps update
316
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
317
-		$currentVersion = implode('.', \OCP\Util::getVersion());
318
-
319
-		// if not a core upgrade, then it's apps upgrade
320
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
321
-
322
-		$oldTheme = $systemConfig->getValue('theme');
323
-		$systemConfig->setValue('theme', '');
324
-		\OCP\Util::addScript('core', 'common');
325
-		\OCP\Util::addScript('core', 'main');
326
-		\OCP\Util::addTranslations('core');
327
-		\OCP\Util::addScript('core', 'update');
328
-
329
-		/** @var \OC\App\AppManager $appManager */
330
-		$appManager = Server::get(\OCP\App\IAppManager::class);
331
-
332
-		$tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest');
333
-		$tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString());
334
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
335
-
336
-		// get third party apps
337
-		$ocVersion = \OCP\Util::getVersion();
338
-		$ocVersion = implode('.', $ocVersion);
339
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
340
-		$incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []);
341
-		$incompatibleShippedApps = [];
342
-		$incompatibleDisabledApps = [];
343
-		foreach ($incompatibleApps as $appInfo) {
344
-			if ($appManager->isShipped($appInfo['id'])) {
345
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
346
-			}
347
-			if (!in_array($appInfo['id'], $incompatibleOverwrites)) {
348
-				$incompatibleDisabledApps[] = $appInfo;
349
-			}
350
-		}
351
-
352
-		if (!empty($incompatibleShippedApps)) {
353
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('core');
354
-			$hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]);
355
-			throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint);
356
-		}
357
-
358
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
359
-		$tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps);
360
-		try {
361
-			$defaults = new \OC_Defaults();
362
-			$tmpl->assign('productName', $defaults->getName());
363
-		} catch (Throwable $error) {
364
-			$tmpl->assign('productName', 'Nextcloud');
365
-		}
366
-		$tmpl->assign('oldTheme', $oldTheme);
367
-		$tmpl->printPage();
368
-	}
369
-
370
-	public static function initSession(): void {
371
-		$request = Server::get(IRequest::class);
372
-
373
-		// TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies
374
-		// TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments
375
-		// TODO: for further information.
376
-		// $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0;
377
-		// if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) {
378
-		// setcookie('cookie_test', 'test', time() + 3600);
379
-		// // Do not initialize the session if a request is authenticated directly
380
-		// // unless there is a session cookie already sent along
381
-		// return;
382
-		// }
383
-
384
-		if ($request->getServerProtocol() === 'https') {
385
-			ini_set('session.cookie_secure', 'true');
386
-		}
387
-
388
-		// prevents javascript from accessing php session cookies
389
-		ini_set('session.cookie_httponly', 'true');
390
-
391
-		// Do not initialize sessions for 'status.php' requests
392
-		// Monitoring endpoints can quickly flood session handlers
393
-		// and 'status.php' doesn't require sessions anyway
394
-		if (str_ends_with($request->getScriptName(), '/status.php')) {
395
-			return;
396
-		}
397
-
398
-		// set the cookie path to the Nextcloud directory
399
-		$cookie_path = OC::$WEBROOT ? : '/';
400
-		ini_set('session.cookie_path', $cookie_path);
401
-
402
-		// Let the session name be changed in the initSession Hook
403
-		$sessionName = OC_Util::getInstanceId();
404
-
405
-		try {
406
-			$logger = null;
407
-			if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) {
408
-				$logger = logger('core');
409
-			}
410
-
411
-			// set the session name to the instance id - which is unique
412
-			$session = new \OC\Session\Internal(
413
-				$sessionName,
414
-				$logger,
415
-			);
416
-
417
-			$cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class);
418
-			$session = $cryptoWrapper->wrapSession($session);
419
-			self::$server->setSession($session);
420
-
421
-			// if session can't be started break with http 500 error
422
-		} catch (Exception $e) {
423
-			Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
424
-			//show the user a detailed error page
425
-			Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500);
426
-			die();
427
-		}
428
-
429
-		//try to set the session lifetime
430
-		$sessionLifeTime = self::getSessionLifeTime();
431
-
432
-		// session timeout
433
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
434
-			if (isset($_COOKIE[session_name()])) {
435
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
436
-			}
437
-			Server::get(IUserSession::class)->logout();
438
-		}
439
-
440
-		if (!self::hasSessionRelaxedExpiry()) {
441
-			$session->set('LAST_ACTIVITY', time());
442
-		}
443
-		$session->close();
444
-	}
445
-
446
-	private static function getSessionLifeTime(): int {
447
-		return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24);
448
-	}
449
-
450
-	/**
451
-	 * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
452
-	 */
453
-	public static function hasSessionRelaxedExpiry(): bool {
454
-		return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false);
455
-	}
456
-
457
-	/**
458
-	 * Try to set some values to the required Nextcloud default
459
-	 */
460
-	public static function setRequiredIniValues(): void {
461
-		// Don't display errors and log them
462
-		@ini_set('display_errors', '0');
463
-		@ini_set('log_errors', '1');
464
-
465
-		// Try to configure php to enable big file uploads.
466
-		// This doesn't work always depending on the webserver and php configuration.
467
-		// Let's try to overwrite some defaults if they are smaller than 1 hour
468
-
469
-		if (intval(@ini_get('max_execution_time') ?: 0) < 3600) {
470
-			@ini_set('max_execution_time', strval(3600));
471
-		}
472
-
473
-		if (intval(@ini_get('max_input_time') ?: 0) < 3600) {
474
-			@ini_set('max_input_time', strval(3600));
475
-		}
476
-
477
-		// Try to set the maximum execution time to the largest time limit we have
478
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
479
-			@set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
480
-		}
481
-
482
-		@ini_set('default_charset', 'UTF-8');
483
-		@ini_set('gd.jpeg_ignore_warning', '1');
484
-	}
485
-
486
-	/**
487
-	 * Send the same site cookies
488
-	 */
489
-	private static function sendSameSiteCookies(): void {
490
-		$cookieParams = session_get_cookie_params();
491
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
492
-		$policies = [
493
-			'lax',
494
-			'strict',
495
-		];
496
-
497
-		// Append __Host to the cookie if it meets the requirements
498
-		$cookiePrefix = '';
499
-		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
500
-			$cookiePrefix = '__Host-';
501
-		}
502
-
503
-		foreach ($policies as $policy) {
504
-			header(
505
-				sprintf(
506
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
507
-					$cookiePrefix,
508
-					$policy,
509
-					$cookieParams['path'],
510
-					$policy
511
-				),
512
-				false
513
-			);
514
-		}
515
-	}
516
-
517
-	/**
518
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
519
-	 * be set in every request if cookies are sent to add a second level of
520
-	 * defense against CSRF.
521
-	 *
522
-	 * If the cookie is not sent this will set the cookie and reload the page.
523
-	 * We use an additional cookie since we want to protect logout CSRF and
524
-	 * also we can't directly interfere with PHP's session mechanism.
525
-	 */
526
-	private static function performSameSiteCookieProtection(IConfig $config): void {
527
-		$request = Server::get(IRequest::class);
528
-
529
-		// Some user agents are notorious and don't really properly follow HTTP
530
-		// specifications. For those, have an automated opt-out. Since the protection
531
-		// for remote.php is applied in base.php as starting point we need to opt out
532
-		// here.
533
-		$incompatibleUserAgents = $config->getSystemValue('csrf.optout');
534
-
535
-		// Fallback, if csrf.optout is unset
536
-		if (!is_array($incompatibleUserAgents)) {
537
-			$incompatibleUserAgents = [
538
-				// OS X Finder
539
-				'/^WebDAVFS/',
540
-				// Windows webdav drive
541
-				'/^Microsoft-WebDAV-MiniRedir/',
542
-			];
543
-		}
544
-
545
-		if ($request->isUserAgent($incompatibleUserAgents)) {
546
-			return;
547
-		}
548
-
549
-		if (count($_COOKIE) > 0) {
550
-			$requestUri = $request->getScriptName();
551
-			$processingScript = explode('/', $requestUri);
552
-			$processingScript = $processingScript[count($processingScript) - 1];
553
-
554
-			// index.php routes are handled in the middleware
555
-			// and cron.php does not need any authentication at all
556
-			if ($processingScript === 'index.php'
557
-				|| $processingScript === 'cron.php') {
558
-				return;
559
-			}
560
-
561
-			// All other endpoints require the lax and the strict cookie
562
-			if (!$request->passesStrictCookieCheck()) {
563
-				logger('core')->warning('Request does not pass strict cookie check');
564
-				self::sendSameSiteCookies();
565
-				// Debug mode gets access to the resources without strict cookie
566
-				// due to the fact that the SabreDAV browser also lives there.
567
-				if (!$config->getSystemValueBool('debug', false)) {
568
-					http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED);
569
-					header('Content-Type: application/json');
570
-					echo json_encode(['error' => 'Strict Cookie has not been found in request']);
571
-					exit();
572
-				}
573
-			}
574
-		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
575
-			self::sendSameSiteCookies();
576
-		}
577
-	}
578
-
579
-	public static function init(): void {
580
-		// First handle PHP configuration and copy auth headers to the expected
581
-		// $_SERVER variable before doing anything Server object related
582
-		self::setRequiredIniValues();
583
-		self::handleAuthHeaders();
584
-
585
-		// prevent any XML processing from loading external entities
586
-		libxml_set_external_entity_loader(static function () {
587
-			return null;
588
-		});
589
-
590
-		// Set default timezone before the Server object is booted
591
-		if (!date_default_timezone_set('UTC')) {
592
-			throw new \RuntimeException('Could not set timezone to UTC');
593
-		}
594
-
595
-		// calculate the root directories
596
-		OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4));
597
-
598
-		// register autoloader
599
-		$loaderStart = microtime(true);
600
-		require_once __DIR__ . '/autoloader.php';
601
-		self::$loader = new \OC\Autoloader([
602
-			OC::$SERVERROOT . '/lib/private/legacy',
603
-		]);
604
-		if (defined('PHPUNIT_RUN')) {
605
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
606
-		}
607
-		spl_autoload_register([self::$loader, 'load']);
608
-		$loaderEnd = microtime(true);
609
-
610
-		self::$CLI = (php_sapi_name() == 'cli');
611
-
612
-		// Add default composer PSR-4 autoloader, ensure apcu to be disabled
613
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
614
-		self::$composerAutoloader->setApcuPrefix(null);
615
-
616
-
617
-		try {
618
-			self::initPaths();
619
-			// setup 3rdparty autoloader
620
-			$vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php';
621
-			if (!file_exists($vendorAutoLoad)) {
622
-				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".');
623
-			}
624
-			require_once $vendorAutoLoad;
625
-		} catch (\RuntimeException $e) {
626
-			if (!self::$CLI) {
627
-				http_response_code(503);
628
-			}
629
-			// we can't use the template error page here, because this needs the
630
-			// DI container which isn't available yet
631
-			print($e->getMessage());
632
-			exit();
633
-		}
634
-
635
-		// setup the basic server
636
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
637
-		self::$server->boot();
638
-
639
-		try {
640
-			$profiler = new BuiltInProfiler(
641
-				Server::get(IConfig::class),
642
-				Server::get(IRequest::class),
643
-			);
644
-			$profiler->start();
645
-		} catch (\Throwable $e) {
646
-			logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']);
647
-		}
648
-
649
-		if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) {
650
-			\OC\Core\Listener\BeforeMessageLoggedEventListener::setup();
651
-		}
652
-
653
-		$eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
654
-		$eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
655
-		$eventLogger->start('boot', 'Initialize');
656
-
657
-		// Override php.ini and log everything if we're troubleshooting
658
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
659
-			error_reporting(E_ALL);
660
-		}
661
-
662
-		$systemConfig = Server::get(\OC\SystemConfig::class);
663
-		self::registerAutoloaderCache($systemConfig);
664
-
665
-		// initialize intl fallback if necessary
666
-		OC_Util::isSetLocaleWorking();
667
-
668
-		$config = Server::get(IConfig::class);
669
-		if (!defined('PHPUNIT_RUN')) {
670
-			$errorHandler = new OC\Log\ErrorHandler(
671
-				\OCP\Server::get(\Psr\Log\LoggerInterface::class),
672
-			);
673
-			$exceptionHandler = [$errorHandler, 'onException'];
674
-			if ($config->getSystemValueBool('debug', false)) {
675
-				set_error_handler([$errorHandler, 'onAll'], E_ALL);
676
-				if (\OC::$CLI) {
677
-					$exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage'];
678
-				}
679
-			} else {
680
-				set_error_handler([$errorHandler, 'onError']);
681
-			}
682
-			register_shutdown_function([$errorHandler, 'onShutdown']);
683
-			set_exception_handler($exceptionHandler);
684
-		}
685
-
686
-		/** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
687
-		$bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
688
-		$bootstrapCoordinator->runInitialRegistration();
689
-
690
-		$eventLogger->start('init_session', 'Initialize session');
691
-
692
-		// Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users
693
-		// see https://github.com/nextcloud/server/pull/2619
694
-		if (!function_exists('simplexml_load_file')) {
695
-			throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.');
696
-		}
697
-
698
-		$appManager = Server::get(\OCP\App\IAppManager::class);
699
-		if ($systemConfig->getValue('installed', false)) {
700
-			$appManager->loadApps(['session']);
701
-		}
702
-		if (!self::$CLI) {
703
-			self::initSession();
704
-		}
705
-		$eventLogger->end('init_session');
706
-		self::checkConfig();
707
-		self::checkInstalled($systemConfig);
708
-
709
-		OC_Response::addSecurityHeaders();
710
-
711
-		self::performSameSiteCookieProtection($config);
712
-
713
-		if (!defined('OC_CONSOLE')) {
714
-			$errors = OC_Util::checkServer($systemConfig);
715
-			if (count($errors) > 0) {
716
-				if (!self::$CLI) {
717
-					http_response_code(503);
718
-					Util::addStyle('guest');
719
-					try {
720
-						Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]);
721
-						exit;
722
-					} catch (\Exception $e) {
723
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
724
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
725
-					}
726
-				}
727
-
728
-				// Convert l10n string into regular string for usage in database
729
-				$staticErrors = [];
730
-				foreach ($errors as $error) {
731
-					echo $error['error'] . "\n";
732
-					echo $error['hint'] . "\n\n";
733
-					$staticErrors[] = [
734
-						'error' => (string)$error['error'],
735
-						'hint' => (string)$error['hint'],
736
-					];
737
-				}
738
-
739
-				try {
740
-					$config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
741
-				} catch (\Exception $e) {
742
-					echo('Writing to database failed');
743
-				}
744
-				exit(1);
745
-			} elseif (self::$CLI && $config->getSystemValueBool('installed', false)) {
746
-				$config->deleteAppValue('core', 'cronErrors');
747
-			}
748
-		}
749
-
750
-		// User and Groups
751
-		if (!$systemConfig->getValue('installed', false)) {
752
-			self::$server->getSession()->set('user_id', '');
753
-		}
754
-
755
-		Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database());
756
-		Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
757
-
758
-		// Subscribe to the hook
759
-		\OCP\Util::connectHook(
760
-			'\OCA\Files_Sharing\API\Server2Server',
761
-			'preLoginNameUsedAsUserName',
762
-			'\OC\User\Database',
763
-			'preLoginNameUsedAsUserName'
764
-		);
765
-
766
-		//setup extra user backends
767
-		if (!\OCP\Util::needUpgrade()) {
768
-			OC_User::setupBackends();
769
-		} else {
770
-			// Run upgrades in incognito mode
771
-			OC_User::setIncognitoMode(true);
772
-		}
773
-
774
-		self::registerCleanupHooks($systemConfig);
775
-		self::registerShareHooks($systemConfig);
776
-		self::registerEncryptionWrapperAndHooks();
777
-		self::registerAccountHooks();
778
-		self::registerResourceCollectionHooks();
779
-		self::registerFileReferenceEventListener();
780
-		self::registerRenderReferenceEventListener();
781
-		self::registerAppRestrictionsHooks();
782
-
783
-		// Make sure that the application class is not loaded before the database is setup
784
-		if ($systemConfig->getValue('installed', false)) {
785
-			$appManager->loadApp('settings');
786
-			/* Build core application to make sure that listeners are registered */
787
-			Server::get(\OC\Core\Application::class);
788
-		}
789
-
790
-		//make sure temporary files are cleaned up
791
-		$tmpManager = Server::get(\OCP\ITempManager::class);
792
-		register_shutdown_function([$tmpManager, 'clean']);
793
-		$lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
794
-		register_shutdown_function([$lockProvider, 'releaseAll']);
795
-
796
-		// Check whether the sample configuration has been copied
797
-		if ($systemConfig->getValue('copied_sample_config', false)) {
798
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
799
-			Server::get(ITemplateManager::class)->printErrorPage(
800
-				$l->t('Sample configuration detected'),
801
-				$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'),
802
-				503
803
-			);
804
-			return;
805
-		}
806
-
807
-		$request = Server::get(IRequest::class);
808
-		$host = $request->getInsecureServerHost();
809
-		/**
810
-		 * if the host passed in headers isn't trusted
811
-		 * FIXME: Should not be in here at all :see_no_evil:
812
-		 */
813
-		if (!OC::$CLI
814
-			&& !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
815
-			&& $config->getSystemValueBool('installed', false)
816
-		) {
817
-			// Allow access to CSS resources
818
-			$isScssRequest = false;
819
-			if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
820
-				$isScssRequest = true;
821
-			}
822
-
823
-			if (substr($request->getRequestUri(), -11) === '/status.php') {
824
-				http_response_code(400);
825
-				header('Content-Type: application/json');
826
-				echo '{"error": "Trusted domain error.", "code": 15}';
827
-				exit();
828
-			}
829
-
830
-			if (!$isScssRequest) {
831
-				http_response_code(400);
832
-				Server::get(LoggerInterface::class)->info(
833
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
834
-					[
835
-						'app' => 'core',
836
-						'remoteAddress' => $request->getRemoteAddress(),
837
-						'host' => $host,
838
-					]
839
-				);
840
-
841
-				$tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest');
842
-				$tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
843
-				$tmpl->printPage();
844
-
845
-				exit();
846
-			}
847
-		}
848
-		$eventLogger->end('boot');
849
-		$eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
850
-		$eventLogger->start('runtime', 'Runtime');
851
-		$eventLogger->start('request', 'Full request after boot');
852
-		register_shutdown_function(function () use ($eventLogger) {
853
-			$eventLogger->end('request');
854
-		});
855
-
856
-		register_shutdown_function(function () {
857
-			$memoryPeak = memory_get_peak_usage();
858
-			$logLevel = match (true) {
859
-				$memoryPeak > 500_000_000 => ILogger::FATAL,
860
-				$memoryPeak > 400_000_000 => ILogger::ERROR,
861
-				$memoryPeak > 300_000_000 => ILogger::WARN,
862
-				default => null,
863
-			};
864
-			if ($logLevel !== null) {
865
-				$message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak);
866
-				$logger = Server::get(LoggerInterface::class);
867
-				$logger->log($logLevel, $message, ['app' => 'core']);
868
-			}
869
-		});
870
-	}
871
-
872
-	/**
873
-	 * register hooks for the cleanup of cache and bruteforce protection
874
-	 */
875
-	public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
876
-		//don't try to do this before we are properly setup
877
-		if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
878
-			// NOTE: This will be replaced to use OCP
879
-			$userSession = Server::get(\OC\User\Session::class);
880
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
881
-				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
882
-					// reset brute force delay for this IP address and username
883
-					$uid = $userSession->getUser()->getUID();
884
-					$request = Server::get(IRequest::class);
885
-					$throttler = Server::get(IThrottler::class);
886
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
887
-				}
888
-
889
-				try {
890
-					$cache = new \OC\Cache\File();
891
-					$cache->gc();
892
-				} catch (\OC\ServerNotAvailableException $e) {
893
-					// not a GC exception, pass it on
894
-					throw $e;
895
-				} catch (\OC\ForbiddenException $e) {
896
-					// filesystem blocked for this request, ignore
897
-				} catch (\Exception $e) {
898
-					// a GC exception should not prevent users from using OC,
899
-					// so log the exception
900
-					Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
901
-						'app' => 'core',
902
-						'exception' => $e,
903
-					]);
904
-				}
905
-			});
906
-		}
907
-	}
908
-
909
-	private static function registerEncryptionWrapperAndHooks(): void {
910
-		$manager = Server::get(\OCP\Encryption\IManager::class);
911
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
912
-
913
-		$enabled = $manager->isEnabled();
914
-		if ($enabled) {
915
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
916
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
917
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
918
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
919
-		}
920
-	}
921
-
922
-	private static function registerAccountHooks(): void {
923
-		/** @var IEventDispatcher $dispatcher */
924
-		$dispatcher = Server::get(IEventDispatcher::class);
925
-		$dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
926
-	}
927
-
928
-	private static function registerAppRestrictionsHooks(): void {
929
-		/** @var \OC\Group\Manager $groupManager */
930
-		$groupManager = Server::get(\OCP\IGroupManager::class);
931
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
932
-			$appManager = Server::get(\OCP\App\IAppManager::class);
933
-			$apps = $appManager->getEnabledAppsForGroup($group);
934
-			foreach ($apps as $appId) {
935
-				$restrictions = $appManager->getAppRestriction($appId);
936
-				if (empty($restrictions)) {
937
-					continue;
938
-				}
939
-				$key = array_search($group->getGID(), $restrictions);
940
-				unset($restrictions[$key]);
941
-				$restrictions = array_values($restrictions);
942
-				if (empty($restrictions)) {
943
-					$appManager->disableApp($appId);
944
-				} else {
945
-					$appManager->enableAppForGroups($appId, $restrictions);
946
-				}
947
-			}
948
-		});
949
-	}
950
-
951
-	private static function registerResourceCollectionHooks(): void {
952
-		\OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class));
953
-	}
954
-
955
-	private static function registerFileReferenceEventListener(): void {
956
-		\OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
957
-	}
958
-
959
-	private static function registerRenderReferenceEventListener() {
960
-		\OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
961
-	}
962
-
963
-	/**
964
-	 * register hooks for sharing
965
-	 */
966
-	public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
967
-		if ($systemConfig->getValue('installed')) {
968
-
969
-			$dispatcher = Server::get(IEventDispatcher::class);
970
-			$dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class);
971
-			$dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class);
972
-			$dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class);
973
-		}
974
-	}
975
-
976
-	protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
977
-		// The class loader takes an optional low-latency cache, which MUST be
978
-		// namespaced. The instanceid is used for namespacing, but might be
979
-		// unavailable at this point. Furthermore, it might not be possible to
980
-		// generate an instanceid via \OC_Util::getInstanceId() because the
981
-		// config file may not be writable. As such, we only register a class
982
-		// loader cache if instanceid is available without trying to create one.
983
-		$instanceId = $systemConfig->getValue('instanceid', null);
984
-		if ($instanceId) {
985
-			try {
986
-				$memcacheFactory = Server::get(\OCP\ICacheFactory::class);
987
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
988
-			} catch (\Exception $ex) {
989
-			}
990
-		}
991
-	}
992
-
993
-	/**
994
-	 * Handle the request
995
-	 */
996
-	public static function handleRequest(): void {
997
-		Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
998
-		$systemConfig = Server::get(\OC\SystemConfig::class);
999
-
1000
-		// Check if Nextcloud is installed or in maintenance (update) mode
1001
-		if (!$systemConfig->getValue('installed', false)) {
1002
-			\OC::$server->getSession()->clear();
1003
-			$controller = Server::get(\OC\Core\Controller\SetupController::class);
1004
-			$controller->run($_POST);
1005
-			exit();
1006
-		}
1007
-
1008
-		$request = Server::get(IRequest::class);
1009
-		$requestPath = $request->getRawPathInfo();
1010
-		if ($requestPath === '/heartbeat') {
1011
-			return;
1012
-		}
1013
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
1014
-			self::checkMaintenanceMode($systemConfig);
1015
-
1016
-			if (\OCP\Util::needUpgrade()) {
1017
-				if (function_exists('opcache_reset')) {
1018
-					opcache_reset();
1019
-				}
1020
-				if (!((bool)$systemConfig->getValue('maintenance', false))) {
1021
-					self::printUpgradePage($systemConfig);
1022
-					exit();
1023
-				}
1024
-			}
1025
-		}
1026
-
1027
-		$appManager = Server::get(\OCP\App\IAppManager::class);
1028
-
1029
-		// Always load authentication apps
1030
-		$appManager->loadApps(['authentication']);
1031
-		$appManager->loadApps(['extended_authentication']);
1032
-
1033
-		// Load minimum set of apps
1034
-		if (!\OCP\Util::needUpgrade()
1035
-			&& !((bool)$systemConfig->getValue('maintenance', false))) {
1036
-			// For logged-in users: Load everything
1037
-			if (Server::get(IUserSession::class)->isLoggedIn()) {
1038
-				$appManager->loadApps();
1039
-			} else {
1040
-				// For guests: Load only filesystem and logging
1041
-				$appManager->loadApps(['filesystem', 'logging']);
1042
-
1043
-				// Don't try to login when a client is trying to get a OAuth token.
1044
-				// OAuth needs to support basic auth too, so the login is not valid
1045
-				// inside Nextcloud and the Login exception would ruin it.
1046
-				if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1047
-					self::handleLogin($request);
1048
-				}
1049
-			}
1050
-		}
1051
-
1052
-		if (!self::$CLI) {
1053
-			try {
1054
-				if (!\OCP\Util::needUpgrade()) {
1055
-					$appManager->loadApps(['filesystem', 'logging']);
1056
-					$appManager->loadApps();
1057
-				}
1058
-				Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1059
-				return;
1060
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1061
-				//header('HTTP/1.0 404 Not Found');
1062
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1063
-				http_response_code(405);
1064
-				return;
1065
-			}
1066
-		}
1067
-
1068
-		// Handle WebDAV
1069
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1070
-			// not allowed any more to prevent people
1071
-			// mounting this root directly.
1072
-			// Users need to mount remote.php/webdav instead.
1073
-			http_response_code(405);
1074
-			return;
1075
-		}
1076
-
1077
-		// Handle requests for JSON or XML
1078
-		$acceptHeader = $request->getHeader('Accept');
1079
-		if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1080
-			http_response_code(404);
1081
-			return;
1082
-		}
1083
-
1084
-		// Handle resources that can't be found
1085
-		// This prevents browsers from redirecting to the default page and then
1086
-		// attempting to parse HTML as CSS and similar.
1087
-		$destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1088
-		if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1089
-			http_response_code(404);
1090
-			return;
1091
-		}
1092
-
1093
-		// Redirect to the default app or login only as an entry point
1094
-		if ($requestPath === '') {
1095
-			// Someone is logged in
1096
-			if (Server::get(IUserSession::class)->isLoggedIn()) {
1097
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1098
-			} else {
1099
-				// Not handled and not logged in
1100
-				header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1101
-			}
1102
-			return;
1103
-		}
1104
-
1105
-		try {
1106
-			Server::get(\OC\Route\Router::class)->match('/error/404');
1107
-		} catch (\Exception $e) {
1108
-			if (!$e instanceof MethodNotAllowedException) {
1109
-				logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1110
-			}
1111
-			$l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
1112
-			Server::get(ITemplateManager::class)->printErrorPage(
1113
-				'404',
1114
-				$l->t('The page could not be found on the server.'),
1115
-				404
1116
-			);
1117
-		}
1118
-	}
1119
-
1120
-	/**
1121
-	 * Check login: apache auth, auth token, basic auth
1122
-	 */
1123
-	public static function handleLogin(OCP\IRequest $request): bool {
1124
-		if ($request->getHeader('X-Nextcloud-Federation')) {
1125
-			return false;
1126
-		}
1127
-		$userSession = Server::get(\OC\User\Session::class);
1128
-		if (OC_User::handleApacheAuth()) {
1129
-			return true;
1130
-		}
1131
-		if (self::tryAppAPILogin($request)) {
1132
-			return true;
1133
-		}
1134
-		if ($userSession->tryTokenLogin($request)) {
1135
-			return true;
1136
-		}
1137
-		if (isset($_COOKIE['nc_username'])
1138
-			&& isset($_COOKIE['nc_token'])
1139
-			&& isset($_COOKIE['nc_session_id'])
1140
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1141
-			return true;
1142
-		}
1143
-		if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) {
1144
-			return true;
1145
-		}
1146
-		return false;
1147
-	}
1148
-
1149
-	protected static function handleAuthHeaders(): void {
1150
-		//copy http auth headers for apache+php-fcgid work around
1151
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1152
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1153
-		}
1154
-
1155
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1156
-		$vars = [
1157
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1158
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1159
-		];
1160
-		foreach ($vars as $var) {
1161
-			if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1162
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1163
-				if (count($credentials) === 2) {
1164
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1165
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1166
-					break;
1167
-				}
1168
-			}
1169
-		}
1170
-	}
1171
-
1172
-	protected static function tryAppAPILogin(OCP\IRequest $request): bool {
1173
-		if (!$request->getHeader('AUTHORIZATION-APP-API')) {
1174
-			return false;
1175
-		}
1176
-		$appManager = Server::get(OCP\App\IAppManager::class);
1177
-		if (!$appManager->isEnabledForAnyone('app_api')) {
1178
-			return false;
1179
-		}
1180
-		try {
1181
-			$appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class);
1182
-			return $appAPIService->validateExAppRequestToNC($request);
1183
-		} catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) {
1184
-			return false;
1185
-		}
1186
-	}
42
+    /**
43
+     * Associative array for autoloading. classname => filename
44
+     */
45
+    public static array $CLASSPATH = [];
46
+    /**
47
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
48
+     */
49
+    public static string $SERVERROOT = '';
50
+    /**
51
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
52
+     */
53
+    private static string $SUBURI = '';
54
+    /**
55
+     * the Nextcloud root path for http requests (e.g. /nextcloud)
56
+     */
57
+    public static string $WEBROOT = '';
58
+    /**
59
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
60
+     * web path in 'url'
61
+     */
62
+    public static array $APPSROOTS = [];
63
+
64
+    public static string $configDir;
65
+
66
+    /**
67
+     * requested app
68
+     */
69
+    public static string $REQUESTEDAPP = '';
70
+
71
+    /**
72
+     * check if Nextcloud runs in cli mode
73
+     */
74
+    public static bool $CLI = false;
75
+
76
+    public static \OC\Autoloader $loader;
77
+
78
+    public static \Composer\Autoload\ClassLoader $composerAutoloader;
79
+
80
+    public static \OC\Server $server;
81
+
82
+    private static \OC\Config $config;
83
+
84
+    /**
85
+     * @throws \RuntimeException when the 3rdparty directory is missing or
86
+     *                           the app path list is empty or contains an invalid path
87
+     */
88
+    public static function initPaths(): void {
89
+        if (defined('PHPUNIT_CONFIG_DIR')) {
90
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
91
+        } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
92
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
93
+        } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
94
+            self::$configDir = rtrim($dir, '/') . '/';
95
+        } else {
96
+            self::$configDir = OC::$SERVERROOT . '/config/';
97
+        }
98
+        self::$config = new \OC\Config(self::$configDir);
99
+
100
+        OC::$SUBURI = str_replace('\\', '/', substr(realpath($_SERVER['SCRIPT_FILENAME'] ?? ''), strlen(OC::$SERVERROOT)));
101
+        /**
102
+         * FIXME: The following lines are required because we can't yet instantiate
103
+         *        Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist.
104
+         */
105
+        $params = [
106
+            'server' => [
107
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null,
108
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null,
109
+            ],
110
+        ];
111
+        if (isset($_SERVER['REMOTE_ADDR'])) {
112
+            $params['server']['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
113
+        }
114
+        $fakeRequest = new \OC\AppFramework\Http\Request(
115
+            $params,
116
+            new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
117
+            new \OC\AllConfig(new \OC\SystemConfig(self::$config))
118
+        );
119
+        $scriptName = $fakeRequest->getScriptName();
120
+        if (substr($scriptName, -1) == '/') {
121
+            $scriptName .= 'index.php';
122
+            //make sure suburi follows the same rules as scriptName
123
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
124
+                if (substr(OC::$SUBURI, -1) != '/') {
125
+                    OC::$SUBURI = OC::$SUBURI . '/';
126
+                }
127
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
128
+            }
129
+        }
130
+
131
+        if (OC::$CLI) {
132
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
133
+        } else {
134
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
135
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
136
+
137
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
138
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
139
+                }
140
+            } else {
141
+                // The scriptName is not ending with OC::$SUBURI
142
+                // This most likely means that we are calling from CLI.
143
+                // However some cron jobs still need to generate
144
+                // a web URL, so we use overwritewebroot as a fallback.
145
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
146
+            }
147
+
148
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
149
+            // slash which is required by URL generation.
150
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
151
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
152
+                header('Location: ' . \OC::$WEBROOT . '/');
153
+                exit();
154
+            }
155
+        }
156
+
157
+        // search the apps folder
158
+        $config_paths = self::$config->getValue('apps_paths', []);
159
+        if (!empty($config_paths)) {
160
+            foreach ($config_paths as $paths) {
161
+                if (isset($paths['url']) && isset($paths['path'])) {
162
+                    $paths['url'] = rtrim($paths['url'], '/');
163
+                    $paths['path'] = rtrim($paths['path'], '/');
164
+                    OC::$APPSROOTS[] = $paths;
165
+                }
166
+            }
167
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
168
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
169
+        }
170
+
171
+        if (empty(OC::$APPSROOTS)) {
172
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
173
+                . '. You can also configure the location in the config.php file.');
174
+        }
175
+        $paths = [];
176
+        foreach (OC::$APPSROOTS as $path) {
177
+            $paths[] = $path['path'];
178
+            if (!is_dir($path['path'])) {
179
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
180
+                    . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
181
+            }
182
+        }
183
+
184
+        // set the right include path
185
+        set_include_path(
186
+            implode(PATH_SEPARATOR, $paths)
187
+        );
188
+    }
189
+
190
+    public static function checkConfig(): void {
191
+        $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
192
+
193
+        // Create config if it does not already exist
194
+        $configFilePath = self::$configDir . '/config.php';
195
+        if (!file_exists($configFilePath)) {
196
+            @touch($configFilePath);
197
+        }
198
+
199
+        // Check if config is writable
200
+        $configFileWritable = is_writable($configFilePath);
201
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
202
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
203
+            $urlGenerator = Server::get(IURLGenerator::class);
204
+
205
+            if (self::$CLI) {
206
+                echo $l->t('Cannot write into "config" directory!') . "\n";
207
+                echo $l->t('This can usually be fixed by giving the web server write access to the config directory.') . "\n";
208
+                echo "\n";
209
+                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";
210
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]) . "\n";
211
+                exit;
212
+            } else {
213
+                Server::get(ITemplateManager::class)->printErrorPage(
214
+                    $l->t('Cannot write into "config" directory!'),
215
+                    $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
216
+                    . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
217
+                    . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
218
+                    503
219
+                );
220
+            }
221
+        }
222
+    }
223
+
224
+    public static function checkInstalled(\OC\SystemConfig $systemConfig): void {
225
+        if (defined('OC_CONSOLE')) {
226
+            return;
227
+        }
228
+        // Redirect to installer if not installed
229
+        if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
230
+            if (OC::$CLI) {
231
+                throw new Exception('Not installed');
232
+            } else {
233
+                $url = OC::$WEBROOT . '/index.php';
234
+                header('Location: ' . $url);
235
+            }
236
+            exit();
237
+        }
238
+    }
239
+
240
+    public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void {
241
+        // Allow ajax update script to execute without being stopped
242
+        if (((bool)$systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
243
+            // send http status 503
244
+            http_response_code(503);
245
+            header('X-Nextcloud-Maintenance-Mode: 1');
246
+            header('Retry-After: 120');
247
+
248
+            // render error page
249
+            $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.user', 'guest');
250
+            \OCP\Util::addScript('core', 'maintenance');
251
+            \OCP\Util::addStyle('core', 'guest');
252
+            $template->printPage();
253
+            die();
254
+        }
255
+    }
256
+
257
+    /**
258
+     * Prints the upgrade page
259
+     */
260
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
261
+        $cliUpgradeLink = $systemConfig->getValue('upgrade.cli-upgrade-link', '');
262
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
263
+        $tooBig = false;
264
+        if (!$disableWebUpdater) {
265
+            $apps = Server::get(\OCP\App\IAppManager::class);
266
+            if ($apps->isEnabledForAnyone('user_ldap')) {
267
+                $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
268
+
269
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
270
+                    ->from('ldap_user_mapping')
271
+                    ->executeQuery();
272
+                $row = $result->fetch();
273
+                $result->closeCursor();
274
+
275
+                $tooBig = ($row['user_count'] > 50);
276
+            }
277
+            if (!$tooBig && $apps->isEnabledForAnyone('user_saml')) {
278
+                $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder();
279
+
280
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
281
+                    ->from('user_saml_users')
282
+                    ->executeQuery();
283
+                $row = $result->fetch();
284
+                $result->closeCursor();
285
+
286
+                $tooBig = ($row['user_count'] > 50);
287
+            }
288
+            if (!$tooBig) {
289
+                // count users
290
+                $totalUsers = Server::get(\OCP\IUserManager::class)->countUsersTotal(51);
291
+                $tooBig = ($totalUsers > 50);
292
+            }
293
+        }
294
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
295
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
296
+
297
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
298
+            // send http status 503
299
+            http_response_code(503);
300
+            header('Retry-After: 120');
301
+
302
+            $serverVersion = \OCP\Server::get(\OCP\ServerVersion::class);
303
+
304
+            // render error page
305
+            $template = Server::get(ITemplateManager::class)->getTemplate('', 'update.use-cli', 'guest');
306
+            $template->assign('productName', 'nextcloud'); // for now
307
+            $template->assign('version', $serverVersion->getVersionString());
308
+            $template->assign('tooBig', $tooBig);
309
+            $template->assign('cliUpgradeLink', $cliUpgradeLink);
310
+
311
+            $template->printPage();
312
+            die();
313
+        }
314
+
315
+        // check whether this is a core update or apps update
316
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
317
+        $currentVersion = implode('.', \OCP\Util::getVersion());
318
+
319
+        // if not a core upgrade, then it's apps upgrade
320
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
321
+
322
+        $oldTheme = $systemConfig->getValue('theme');
323
+        $systemConfig->setValue('theme', '');
324
+        \OCP\Util::addScript('core', 'common');
325
+        \OCP\Util::addScript('core', 'main');
326
+        \OCP\Util::addTranslations('core');
327
+        \OCP\Util::addScript('core', 'update');
328
+
329
+        /** @var \OC\App\AppManager $appManager */
330
+        $appManager = Server::get(\OCP\App\IAppManager::class);
331
+
332
+        $tmpl = Server::get(ITemplateManager::class)->getTemplate('', 'update.admin', 'guest');
333
+        $tmpl->assign('version', \OCP\Server::get(\OCP\ServerVersion::class)->getVersionString());
334
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
335
+
336
+        // get third party apps
337
+        $ocVersion = \OCP\Util::getVersion();
338
+        $ocVersion = implode('.', $ocVersion);
339
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
340
+        $incompatibleOverwrites = $systemConfig->getValue('app_install_overwrite', []);
341
+        $incompatibleShippedApps = [];
342
+        $incompatibleDisabledApps = [];
343
+        foreach ($incompatibleApps as $appInfo) {
344
+            if ($appManager->isShipped($appInfo['id'])) {
345
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
346
+            }
347
+            if (!in_array($appInfo['id'], $incompatibleOverwrites)) {
348
+                $incompatibleDisabledApps[] = $appInfo;
349
+            }
350
+        }
351
+
352
+        if (!empty($incompatibleShippedApps)) {
353
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('core');
354
+            $hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]);
355
+            throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint);
356
+        }
357
+
358
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
359
+        $tmpl->assign('incompatibleAppsList', $incompatibleDisabledApps);
360
+        try {
361
+            $defaults = new \OC_Defaults();
362
+            $tmpl->assign('productName', $defaults->getName());
363
+        } catch (Throwable $error) {
364
+            $tmpl->assign('productName', 'Nextcloud');
365
+        }
366
+        $tmpl->assign('oldTheme', $oldTheme);
367
+        $tmpl->printPage();
368
+    }
369
+
370
+    public static function initSession(): void {
371
+        $request = Server::get(IRequest::class);
372
+
373
+        // TODO: Temporary disabled again to solve issues with CalDAV/CardDAV clients like DAVx5 that use cookies
374
+        // TODO: See https://github.com/nextcloud/server/issues/37277#issuecomment-1476366147 and the other comments
375
+        // TODO: for further information.
376
+        // $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0;
377
+        // if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) {
378
+        // setcookie('cookie_test', 'test', time() + 3600);
379
+        // // Do not initialize the session if a request is authenticated directly
380
+        // // unless there is a session cookie already sent along
381
+        // return;
382
+        // }
383
+
384
+        if ($request->getServerProtocol() === 'https') {
385
+            ini_set('session.cookie_secure', 'true');
386
+        }
387
+
388
+        // prevents javascript from accessing php session cookies
389
+        ini_set('session.cookie_httponly', 'true');
390
+
391
+        // Do not initialize sessions for 'status.php' requests
392
+        // Monitoring endpoints can quickly flood session handlers
393
+        // and 'status.php' doesn't require sessions anyway
394
+        if (str_ends_with($request->getScriptName(), '/status.php')) {
395
+            return;
396
+        }
397
+
398
+        // set the cookie path to the Nextcloud directory
399
+        $cookie_path = OC::$WEBROOT ? : '/';
400
+        ini_set('session.cookie_path', $cookie_path);
401
+
402
+        // Let the session name be changed in the initSession Hook
403
+        $sessionName = OC_Util::getInstanceId();
404
+
405
+        try {
406
+            $logger = null;
407
+            if (Server::get(\OC\SystemConfig::class)->getValue('installed', false)) {
408
+                $logger = logger('core');
409
+            }
410
+
411
+            // set the session name to the instance id - which is unique
412
+            $session = new \OC\Session\Internal(
413
+                $sessionName,
414
+                $logger,
415
+            );
416
+
417
+            $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class);
418
+            $session = $cryptoWrapper->wrapSession($session);
419
+            self::$server->setSession($session);
420
+
421
+            // if session can't be started break with http 500 error
422
+        } catch (Exception $e) {
423
+            Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]);
424
+            //show the user a detailed error page
425
+            Server::get(ITemplateManager::class)->printExceptionErrorPage($e, 500);
426
+            die();
427
+        }
428
+
429
+        //try to set the session lifetime
430
+        $sessionLifeTime = self::getSessionLifeTime();
431
+
432
+        // session timeout
433
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
434
+            if (isset($_COOKIE[session_name()])) {
435
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
436
+            }
437
+            Server::get(IUserSession::class)->logout();
438
+        }
439
+
440
+        if (!self::hasSessionRelaxedExpiry()) {
441
+            $session->set('LAST_ACTIVITY', time());
442
+        }
443
+        $session->close();
444
+    }
445
+
446
+    private static function getSessionLifeTime(): int {
447
+        return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24);
448
+    }
449
+
450
+    /**
451
+     * @return bool true if the session expiry should only be done by gc instead of an explicit timeout
452
+     */
453
+    public static function hasSessionRelaxedExpiry(): bool {
454
+        return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false);
455
+    }
456
+
457
+    /**
458
+     * Try to set some values to the required Nextcloud default
459
+     */
460
+    public static function setRequiredIniValues(): void {
461
+        // Don't display errors and log them
462
+        @ini_set('display_errors', '0');
463
+        @ini_set('log_errors', '1');
464
+
465
+        // Try to configure php to enable big file uploads.
466
+        // This doesn't work always depending on the webserver and php configuration.
467
+        // Let's try to overwrite some defaults if they are smaller than 1 hour
468
+
469
+        if (intval(@ini_get('max_execution_time') ?: 0) < 3600) {
470
+            @ini_set('max_execution_time', strval(3600));
471
+        }
472
+
473
+        if (intval(@ini_get('max_input_time') ?: 0) < 3600) {
474
+            @ini_set('max_input_time', strval(3600));
475
+        }
476
+
477
+        // Try to set the maximum execution time to the largest time limit we have
478
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
479
+            @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
480
+        }
481
+
482
+        @ini_set('default_charset', 'UTF-8');
483
+        @ini_set('gd.jpeg_ignore_warning', '1');
484
+    }
485
+
486
+    /**
487
+     * Send the same site cookies
488
+     */
489
+    private static function sendSameSiteCookies(): void {
490
+        $cookieParams = session_get_cookie_params();
491
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
492
+        $policies = [
493
+            'lax',
494
+            'strict',
495
+        ];
496
+
497
+        // Append __Host to the cookie if it meets the requirements
498
+        $cookiePrefix = '';
499
+        if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
500
+            $cookiePrefix = '__Host-';
501
+        }
502
+
503
+        foreach ($policies as $policy) {
504
+            header(
505
+                sprintf(
506
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
507
+                    $cookiePrefix,
508
+                    $policy,
509
+                    $cookieParams['path'],
510
+                    $policy
511
+                ),
512
+                false
513
+            );
514
+        }
515
+    }
516
+
517
+    /**
518
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
519
+     * be set in every request if cookies are sent to add a second level of
520
+     * defense against CSRF.
521
+     *
522
+     * If the cookie is not sent this will set the cookie and reload the page.
523
+     * We use an additional cookie since we want to protect logout CSRF and
524
+     * also we can't directly interfere with PHP's session mechanism.
525
+     */
526
+    private static function performSameSiteCookieProtection(IConfig $config): void {
527
+        $request = Server::get(IRequest::class);
528
+
529
+        // Some user agents are notorious and don't really properly follow HTTP
530
+        // specifications. For those, have an automated opt-out. Since the protection
531
+        // for remote.php is applied in base.php as starting point we need to opt out
532
+        // here.
533
+        $incompatibleUserAgents = $config->getSystemValue('csrf.optout');
534
+
535
+        // Fallback, if csrf.optout is unset
536
+        if (!is_array($incompatibleUserAgents)) {
537
+            $incompatibleUserAgents = [
538
+                // OS X Finder
539
+                '/^WebDAVFS/',
540
+                // Windows webdav drive
541
+                '/^Microsoft-WebDAV-MiniRedir/',
542
+            ];
543
+        }
544
+
545
+        if ($request->isUserAgent($incompatibleUserAgents)) {
546
+            return;
547
+        }
548
+
549
+        if (count($_COOKIE) > 0) {
550
+            $requestUri = $request->getScriptName();
551
+            $processingScript = explode('/', $requestUri);
552
+            $processingScript = $processingScript[count($processingScript) - 1];
553
+
554
+            // index.php routes are handled in the middleware
555
+            // and cron.php does not need any authentication at all
556
+            if ($processingScript === 'index.php'
557
+                || $processingScript === 'cron.php') {
558
+                return;
559
+            }
560
+
561
+            // All other endpoints require the lax and the strict cookie
562
+            if (!$request->passesStrictCookieCheck()) {
563
+                logger('core')->warning('Request does not pass strict cookie check');
564
+                self::sendSameSiteCookies();
565
+                // Debug mode gets access to the resources without strict cookie
566
+                // due to the fact that the SabreDAV browser also lives there.
567
+                if (!$config->getSystemValueBool('debug', false)) {
568
+                    http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED);
569
+                    header('Content-Type: application/json');
570
+                    echo json_encode(['error' => 'Strict Cookie has not been found in request']);
571
+                    exit();
572
+                }
573
+            }
574
+        } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
575
+            self::sendSameSiteCookies();
576
+        }
577
+    }
578
+
579
+    public static function init(): void {
580
+        // First handle PHP configuration and copy auth headers to the expected
581
+        // $_SERVER variable before doing anything Server object related
582
+        self::setRequiredIniValues();
583
+        self::handleAuthHeaders();
584
+
585
+        // prevent any XML processing from loading external entities
586
+        libxml_set_external_entity_loader(static function () {
587
+            return null;
588
+        });
589
+
590
+        // Set default timezone before the Server object is booted
591
+        if (!date_default_timezone_set('UTC')) {
592
+            throw new \RuntimeException('Could not set timezone to UTC');
593
+        }
594
+
595
+        // calculate the root directories
596
+        OC::$SERVERROOT = str_replace('\\', '/', substr(__DIR__, 0, -4));
597
+
598
+        // register autoloader
599
+        $loaderStart = microtime(true);
600
+        require_once __DIR__ . '/autoloader.php';
601
+        self::$loader = new \OC\Autoloader([
602
+            OC::$SERVERROOT . '/lib/private/legacy',
603
+        ]);
604
+        if (defined('PHPUNIT_RUN')) {
605
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
606
+        }
607
+        spl_autoload_register([self::$loader, 'load']);
608
+        $loaderEnd = microtime(true);
609
+
610
+        self::$CLI = (php_sapi_name() == 'cli');
611
+
612
+        // Add default composer PSR-4 autoloader, ensure apcu to be disabled
613
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
614
+        self::$composerAutoloader->setApcuPrefix(null);
615
+
616
+
617
+        try {
618
+            self::initPaths();
619
+            // setup 3rdparty autoloader
620
+            $vendorAutoLoad = OC::$SERVERROOT . '/3rdparty/autoload.php';
621
+            if (!file_exists($vendorAutoLoad)) {
622
+                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".');
623
+            }
624
+            require_once $vendorAutoLoad;
625
+        } catch (\RuntimeException $e) {
626
+            if (!self::$CLI) {
627
+                http_response_code(503);
628
+            }
629
+            // we can't use the template error page here, because this needs the
630
+            // DI container which isn't available yet
631
+            print($e->getMessage());
632
+            exit();
633
+        }
634
+
635
+        // setup the basic server
636
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
637
+        self::$server->boot();
638
+
639
+        try {
640
+            $profiler = new BuiltInProfiler(
641
+                Server::get(IConfig::class),
642
+                Server::get(IRequest::class),
643
+            );
644
+            $profiler->start();
645
+        } catch (\Throwable $e) {
646
+            logger('core')->error('Failed to start profiler: ' . $e->getMessage(), ['app' => 'base']);
647
+        }
648
+
649
+        if (self::$CLI && in_array('--' . \OCP\Console\ReservedOptions::DEBUG_LOG, $_SERVER['argv'])) {
650
+            \OC\Core\Listener\BeforeMessageLoggedEventListener::setup();
651
+        }
652
+
653
+        $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
654
+        $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
655
+        $eventLogger->start('boot', 'Initialize');
656
+
657
+        // Override php.ini and log everything if we're troubleshooting
658
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
659
+            error_reporting(E_ALL);
660
+        }
661
+
662
+        $systemConfig = Server::get(\OC\SystemConfig::class);
663
+        self::registerAutoloaderCache($systemConfig);
664
+
665
+        // initialize intl fallback if necessary
666
+        OC_Util::isSetLocaleWorking();
667
+
668
+        $config = Server::get(IConfig::class);
669
+        if (!defined('PHPUNIT_RUN')) {
670
+            $errorHandler = new OC\Log\ErrorHandler(
671
+                \OCP\Server::get(\Psr\Log\LoggerInterface::class),
672
+            );
673
+            $exceptionHandler = [$errorHandler, 'onException'];
674
+            if ($config->getSystemValueBool('debug', false)) {
675
+                set_error_handler([$errorHandler, 'onAll'], E_ALL);
676
+                if (\OC::$CLI) {
677
+                    $exceptionHandler = [Server::get(ITemplateManager::class), 'printExceptionErrorPage'];
678
+                }
679
+            } else {
680
+                set_error_handler([$errorHandler, 'onError']);
681
+            }
682
+            register_shutdown_function([$errorHandler, 'onShutdown']);
683
+            set_exception_handler($exceptionHandler);
684
+        }
685
+
686
+        /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
687
+        $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
688
+        $bootstrapCoordinator->runInitialRegistration();
689
+
690
+        $eventLogger->start('init_session', 'Initialize session');
691
+
692
+        // Check for PHP SimpleXML extension earlier since we need it before our other checks and want to provide a useful hint for web users
693
+        // see https://github.com/nextcloud/server/pull/2619
694
+        if (!function_exists('simplexml_load_file')) {
695
+            throw new \OCP\HintException('The PHP SimpleXML/PHP-XML extension is not installed.', 'Install the extension or make sure it is enabled.');
696
+        }
697
+
698
+        $appManager = Server::get(\OCP\App\IAppManager::class);
699
+        if ($systemConfig->getValue('installed', false)) {
700
+            $appManager->loadApps(['session']);
701
+        }
702
+        if (!self::$CLI) {
703
+            self::initSession();
704
+        }
705
+        $eventLogger->end('init_session');
706
+        self::checkConfig();
707
+        self::checkInstalled($systemConfig);
708
+
709
+        OC_Response::addSecurityHeaders();
710
+
711
+        self::performSameSiteCookieProtection($config);
712
+
713
+        if (!defined('OC_CONSOLE')) {
714
+            $errors = OC_Util::checkServer($systemConfig);
715
+            if (count($errors) > 0) {
716
+                if (!self::$CLI) {
717
+                    http_response_code(503);
718
+                    Util::addStyle('guest');
719
+                    try {
720
+                        Server::get(ITemplateManager::class)->printGuestPage('', 'error', ['errors' => $errors]);
721
+                        exit;
722
+                    } catch (\Exception $e) {
723
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
724
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
725
+                    }
726
+                }
727
+
728
+                // Convert l10n string into regular string for usage in database
729
+                $staticErrors = [];
730
+                foreach ($errors as $error) {
731
+                    echo $error['error'] . "\n";
732
+                    echo $error['hint'] . "\n\n";
733
+                    $staticErrors[] = [
734
+                        'error' => (string)$error['error'],
735
+                        'hint' => (string)$error['hint'],
736
+                    ];
737
+                }
738
+
739
+                try {
740
+                    $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
741
+                } catch (\Exception $e) {
742
+                    echo('Writing to database failed');
743
+                }
744
+                exit(1);
745
+            } elseif (self::$CLI && $config->getSystemValueBool('installed', false)) {
746
+                $config->deleteAppValue('core', 'cronErrors');
747
+            }
748
+        }
749
+
750
+        // User and Groups
751
+        if (!$systemConfig->getValue('installed', false)) {
752
+            self::$server->getSession()->set('user_id', '');
753
+        }
754
+
755
+        Server::get(\OCP\IUserManager::class)->registerBackend(new \OC\User\Database());
756
+        Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
757
+
758
+        // Subscribe to the hook
759
+        \OCP\Util::connectHook(
760
+            '\OCA\Files_Sharing\API\Server2Server',
761
+            'preLoginNameUsedAsUserName',
762
+            '\OC\User\Database',
763
+            'preLoginNameUsedAsUserName'
764
+        );
765
+
766
+        //setup extra user backends
767
+        if (!\OCP\Util::needUpgrade()) {
768
+            OC_User::setupBackends();
769
+        } else {
770
+            // Run upgrades in incognito mode
771
+            OC_User::setIncognitoMode(true);
772
+        }
773
+
774
+        self::registerCleanupHooks($systemConfig);
775
+        self::registerShareHooks($systemConfig);
776
+        self::registerEncryptionWrapperAndHooks();
777
+        self::registerAccountHooks();
778
+        self::registerResourceCollectionHooks();
779
+        self::registerFileReferenceEventListener();
780
+        self::registerRenderReferenceEventListener();
781
+        self::registerAppRestrictionsHooks();
782
+
783
+        // Make sure that the application class is not loaded before the database is setup
784
+        if ($systemConfig->getValue('installed', false)) {
785
+            $appManager->loadApp('settings');
786
+            /* Build core application to make sure that listeners are registered */
787
+            Server::get(\OC\Core\Application::class);
788
+        }
789
+
790
+        //make sure temporary files are cleaned up
791
+        $tmpManager = Server::get(\OCP\ITempManager::class);
792
+        register_shutdown_function([$tmpManager, 'clean']);
793
+        $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
794
+        register_shutdown_function([$lockProvider, 'releaseAll']);
795
+
796
+        // Check whether the sample configuration has been copied
797
+        if ($systemConfig->getValue('copied_sample_config', false)) {
798
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
799
+            Server::get(ITemplateManager::class)->printErrorPage(
800
+                $l->t('Sample configuration detected'),
801
+                $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'),
802
+                503
803
+            );
804
+            return;
805
+        }
806
+
807
+        $request = Server::get(IRequest::class);
808
+        $host = $request->getInsecureServerHost();
809
+        /**
810
+         * if the host passed in headers isn't trusted
811
+         * FIXME: Should not be in here at all :see_no_evil:
812
+         */
813
+        if (!OC::$CLI
814
+            && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
815
+            && $config->getSystemValueBool('installed', false)
816
+        ) {
817
+            // Allow access to CSS resources
818
+            $isScssRequest = false;
819
+            if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
820
+                $isScssRequest = true;
821
+            }
822
+
823
+            if (substr($request->getRequestUri(), -11) === '/status.php') {
824
+                http_response_code(400);
825
+                header('Content-Type: application/json');
826
+                echo '{"error": "Trusted domain error.", "code": 15}';
827
+                exit();
828
+            }
829
+
830
+            if (!$isScssRequest) {
831
+                http_response_code(400);
832
+                Server::get(LoggerInterface::class)->info(
833
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
834
+                    [
835
+                        'app' => 'core',
836
+                        'remoteAddress' => $request->getRemoteAddress(),
837
+                        'host' => $host,
838
+                    ]
839
+                );
840
+
841
+                $tmpl = Server::get(ITemplateManager::class)->getTemplate('core', 'untrustedDomain', 'guest');
842
+                $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
843
+                $tmpl->printPage();
844
+
845
+                exit();
846
+            }
847
+        }
848
+        $eventLogger->end('boot');
849
+        $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
850
+        $eventLogger->start('runtime', 'Runtime');
851
+        $eventLogger->start('request', 'Full request after boot');
852
+        register_shutdown_function(function () use ($eventLogger) {
853
+            $eventLogger->end('request');
854
+        });
855
+
856
+        register_shutdown_function(function () {
857
+            $memoryPeak = memory_get_peak_usage();
858
+            $logLevel = match (true) {
859
+                $memoryPeak > 500_000_000 => ILogger::FATAL,
860
+                $memoryPeak > 400_000_000 => ILogger::ERROR,
861
+                $memoryPeak > 300_000_000 => ILogger::WARN,
862
+                default => null,
863
+            };
864
+            if ($logLevel !== null) {
865
+                $message = 'Request used more than 300 MB of RAM: ' . Util::humanFileSize($memoryPeak);
866
+                $logger = Server::get(LoggerInterface::class);
867
+                $logger->log($logLevel, $message, ['app' => 'core']);
868
+            }
869
+        });
870
+    }
871
+
872
+    /**
873
+     * register hooks for the cleanup of cache and bruteforce protection
874
+     */
875
+    public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
876
+        //don't try to do this before we are properly setup
877
+        if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
878
+            // NOTE: This will be replaced to use OCP
879
+            $userSession = Server::get(\OC\User\Session::class);
880
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
881
+                if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
882
+                    // reset brute force delay for this IP address and username
883
+                    $uid = $userSession->getUser()->getUID();
884
+                    $request = Server::get(IRequest::class);
885
+                    $throttler = Server::get(IThrottler::class);
886
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
887
+                }
888
+
889
+                try {
890
+                    $cache = new \OC\Cache\File();
891
+                    $cache->gc();
892
+                } catch (\OC\ServerNotAvailableException $e) {
893
+                    // not a GC exception, pass it on
894
+                    throw $e;
895
+                } catch (\OC\ForbiddenException $e) {
896
+                    // filesystem blocked for this request, ignore
897
+                } catch (\Exception $e) {
898
+                    // a GC exception should not prevent users from using OC,
899
+                    // so log the exception
900
+                    Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
901
+                        'app' => 'core',
902
+                        'exception' => $e,
903
+                    ]);
904
+                }
905
+            });
906
+        }
907
+    }
908
+
909
+    private static function registerEncryptionWrapperAndHooks(): void {
910
+        $manager = Server::get(\OCP\Encryption\IManager::class);
911
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
912
+
913
+        $enabled = $manager->isEnabled();
914
+        if ($enabled) {
915
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
916
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
917
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
918
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
919
+        }
920
+    }
921
+
922
+    private static function registerAccountHooks(): void {
923
+        /** @var IEventDispatcher $dispatcher */
924
+        $dispatcher = Server::get(IEventDispatcher::class);
925
+        $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
926
+    }
927
+
928
+    private static function registerAppRestrictionsHooks(): void {
929
+        /** @var \OC\Group\Manager $groupManager */
930
+        $groupManager = Server::get(\OCP\IGroupManager::class);
931
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
932
+            $appManager = Server::get(\OCP\App\IAppManager::class);
933
+            $apps = $appManager->getEnabledAppsForGroup($group);
934
+            foreach ($apps as $appId) {
935
+                $restrictions = $appManager->getAppRestriction($appId);
936
+                if (empty($restrictions)) {
937
+                    continue;
938
+                }
939
+                $key = array_search($group->getGID(), $restrictions);
940
+                unset($restrictions[$key]);
941
+                $restrictions = array_values($restrictions);
942
+                if (empty($restrictions)) {
943
+                    $appManager->disableApp($appId);
944
+                } else {
945
+                    $appManager->enableAppForGroups($appId, $restrictions);
946
+                }
947
+            }
948
+        });
949
+    }
950
+
951
+    private static function registerResourceCollectionHooks(): void {
952
+        \OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class));
953
+    }
954
+
955
+    private static function registerFileReferenceEventListener(): void {
956
+        \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
957
+    }
958
+
959
+    private static function registerRenderReferenceEventListener() {
960
+        \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
961
+    }
962
+
963
+    /**
964
+     * register hooks for sharing
965
+     */
966
+    public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
967
+        if ($systemConfig->getValue('installed')) {
968
+
969
+            $dispatcher = Server::get(IEventDispatcher::class);
970
+            $dispatcher->addServiceListener(UserRemovedEvent::class, UserRemovedListener::class);
971
+            $dispatcher->addServiceListener(GroupDeletedEvent::class, GroupDeletedListener::class);
972
+            $dispatcher->addServiceListener(UserDeletedEvent::class, UserDeletedListener::class);
973
+        }
974
+    }
975
+
976
+    protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
977
+        // The class loader takes an optional low-latency cache, which MUST be
978
+        // namespaced. The instanceid is used for namespacing, but might be
979
+        // unavailable at this point. Furthermore, it might not be possible to
980
+        // generate an instanceid via \OC_Util::getInstanceId() because the
981
+        // config file may not be writable. As such, we only register a class
982
+        // loader cache if instanceid is available without trying to create one.
983
+        $instanceId = $systemConfig->getValue('instanceid', null);
984
+        if ($instanceId) {
985
+            try {
986
+                $memcacheFactory = Server::get(\OCP\ICacheFactory::class);
987
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
988
+            } catch (\Exception $ex) {
989
+            }
990
+        }
991
+    }
992
+
993
+    /**
994
+     * Handle the request
995
+     */
996
+    public static function handleRequest(): void {
997
+        Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
998
+        $systemConfig = Server::get(\OC\SystemConfig::class);
999
+
1000
+        // Check if Nextcloud is installed or in maintenance (update) mode
1001
+        if (!$systemConfig->getValue('installed', false)) {
1002
+            \OC::$server->getSession()->clear();
1003
+            $controller = Server::get(\OC\Core\Controller\SetupController::class);
1004
+            $controller->run($_POST);
1005
+            exit();
1006
+        }
1007
+
1008
+        $request = Server::get(IRequest::class);
1009
+        $requestPath = $request->getRawPathInfo();
1010
+        if ($requestPath === '/heartbeat') {
1011
+            return;
1012
+        }
1013
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
1014
+            self::checkMaintenanceMode($systemConfig);
1015
+
1016
+            if (\OCP\Util::needUpgrade()) {
1017
+                if (function_exists('opcache_reset')) {
1018
+                    opcache_reset();
1019
+                }
1020
+                if (!((bool)$systemConfig->getValue('maintenance', false))) {
1021
+                    self::printUpgradePage($systemConfig);
1022
+                    exit();
1023
+                }
1024
+            }
1025
+        }
1026
+
1027
+        $appManager = Server::get(\OCP\App\IAppManager::class);
1028
+
1029
+        // Always load authentication apps
1030
+        $appManager->loadApps(['authentication']);
1031
+        $appManager->loadApps(['extended_authentication']);
1032
+
1033
+        // Load minimum set of apps
1034
+        if (!\OCP\Util::needUpgrade()
1035
+            && !((bool)$systemConfig->getValue('maintenance', false))) {
1036
+            // For logged-in users: Load everything
1037
+            if (Server::get(IUserSession::class)->isLoggedIn()) {
1038
+                $appManager->loadApps();
1039
+            } else {
1040
+                // For guests: Load only filesystem and logging
1041
+                $appManager->loadApps(['filesystem', 'logging']);
1042
+
1043
+                // Don't try to login when a client is trying to get a OAuth token.
1044
+                // OAuth needs to support basic auth too, so the login is not valid
1045
+                // inside Nextcloud and the Login exception would ruin it.
1046
+                if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
1047
+                    self::handleLogin($request);
1048
+                }
1049
+            }
1050
+        }
1051
+
1052
+        if (!self::$CLI) {
1053
+            try {
1054
+                if (!\OCP\Util::needUpgrade()) {
1055
+                    $appManager->loadApps(['filesystem', 'logging']);
1056
+                    $appManager->loadApps();
1057
+                }
1058
+                Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
1059
+                return;
1060
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1061
+                //header('HTTP/1.0 404 Not Found');
1062
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1063
+                http_response_code(405);
1064
+                return;
1065
+            }
1066
+        }
1067
+
1068
+        // Handle WebDAV
1069
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1070
+            // not allowed any more to prevent people
1071
+            // mounting this root directly.
1072
+            // Users need to mount remote.php/webdav instead.
1073
+            http_response_code(405);
1074
+            return;
1075
+        }
1076
+
1077
+        // Handle requests for JSON or XML
1078
+        $acceptHeader = $request->getHeader('Accept');
1079
+        if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
1080
+            http_response_code(404);
1081
+            return;
1082
+        }
1083
+
1084
+        // Handle resources that can't be found
1085
+        // This prevents browsers from redirecting to the default page and then
1086
+        // attempting to parse HTML as CSS and similar.
1087
+        $destinationHeader = $request->getHeader('Sec-Fetch-Dest');
1088
+        if (in_array($destinationHeader, ['font', 'script', 'style'])) {
1089
+            http_response_code(404);
1090
+            return;
1091
+        }
1092
+
1093
+        // Redirect to the default app or login only as an entry point
1094
+        if ($requestPath === '') {
1095
+            // Someone is logged in
1096
+            if (Server::get(IUserSession::class)->isLoggedIn()) {
1097
+                header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
1098
+            } else {
1099
+                // Not handled and not logged in
1100
+                header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
1101
+            }
1102
+            return;
1103
+        }
1104
+
1105
+        try {
1106
+            Server::get(\OC\Route\Router::class)->match('/error/404');
1107
+        } catch (\Exception $e) {
1108
+            if (!$e instanceof MethodNotAllowedException) {
1109
+                logger('core')->emergency($e->getMessage(), ['exception' => $e]);
1110
+            }
1111
+            $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
1112
+            Server::get(ITemplateManager::class)->printErrorPage(
1113
+                '404',
1114
+                $l->t('The page could not be found on the server.'),
1115
+                404
1116
+            );
1117
+        }
1118
+    }
1119
+
1120
+    /**
1121
+     * Check login: apache auth, auth token, basic auth
1122
+     */
1123
+    public static function handleLogin(OCP\IRequest $request): bool {
1124
+        if ($request->getHeader('X-Nextcloud-Federation')) {
1125
+            return false;
1126
+        }
1127
+        $userSession = Server::get(\OC\User\Session::class);
1128
+        if (OC_User::handleApacheAuth()) {
1129
+            return true;
1130
+        }
1131
+        if (self::tryAppAPILogin($request)) {
1132
+            return true;
1133
+        }
1134
+        if ($userSession->tryTokenLogin($request)) {
1135
+            return true;
1136
+        }
1137
+        if (isset($_COOKIE['nc_username'])
1138
+            && isset($_COOKIE['nc_token'])
1139
+            && isset($_COOKIE['nc_session_id'])
1140
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1141
+            return true;
1142
+        }
1143
+        if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) {
1144
+            return true;
1145
+        }
1146
+        return false;
1147
+    }
1148
+
1149
+    protected static function handleAuthHeaders(): void {
1150
+        //copy http auth headers for apache+php-fcgid work around
1151
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1152
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1153
+        }
1154
+
1155
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1156
+        $vars = [
1157
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1158
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1159
+        ];
1160
+        foreach ($vars as $var) {
1161
+            if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1162
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1163
+                if (count($credentials) === 2) {
1164
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1165
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1166
+                    break;
1167
+                }
1168
+            }
1169
+        }
1170
+    }
1171
+
1172
+    protected static function tryAppAPILogin(OCP\IRequest $request): bool {
1173
+        if (!$request->getHeader('AUTHORIZATION-APP-API')) {
1174
+            return false;
1175
+        }
1176
+        $appManager = Server::get(OCP\App\IAppManager::class);
1177
+        if (!$appManager->isEnabledForAnyone('app_api')) {
1178
+            return false;
1179
+        }
1180
+        try {
1181
+            $appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class);
1182
+            return $appAPIService->validateExAppRequestToNC($request);
1183
+        } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) {
1184
+            return false;
1185
+        }
1186
+    }
1187 1187
 }
1188 1188
 
1189 1189
 OC::init();
Please login to merge, or discard this patch.
build/stubs/excimer.php 1 patch
Indentation   +232 added lines, -232 removed lines patch added patch discarded remove patch
@@ -12,108 +12,108 @@  discard block
 block discarded – undo
12 12
  * Collects a stack trace every time a timer event fires.
13 13
  */
14 14
 class ExcimerProfiler {
15
-	/**
16
-	 * Set the period.
17
-	 *
18
-	 * This will take effect the next time start() is called.
19
-	 *
20
-	 * If this method is not called, the default period of 0.1 seconds
21
-	 * will be used.
22
-	 *
23
-	 * @param float $period The period in seconds
24
-	 */
25
-	public function setPeriod($period) {
26
-	}
15
+    /**
16
+     * Set the period.
17
+     *
18
+     * This will take effect the next time start() is called.
19
+     *
20
+     * If this method is not called, the default period of 0.1 seconds
21
+     * will be used.
22
+     *
23
+     * @param float $period The period in seconds
24
+     */
25
+    public function setPeriod($period) {
26
+    }
27 27
 
28
-	/**
29
-	 * Set the event type. May be either EXCIMER_REAL, for real (wall-clock)
30
-	 * time, or EXCIMER_CPU, for CPU time. The default is EXCIMER_REAL.
31
-	 *
32
-	 * This will take effect the next time start() is called.
33
-	 *
34
-	 * @param int $eventType
35
-	 */
36
-	public function setEventType($eventType) {
37
-	}
28
+    /**
29
+     * Set the event type. May be either EXCIMER_REAL, for real (wall-clock)
30
+     * time, or EXCIMER_CPU, for CPU time. The default is EXCIMER_REAL.
31
+     *
32
+     * This will take effect the next time start() is called.
33
+     *
34
+     * @param int $eventType
35
+     */
36
+    public function setEventType($eventType) {
37
+    }
38 38
 
39
-	/**
40
-	 * Set the maximum depth of stack trace collection. If this depth is
41
-	 * exceeded, the traversal up the stack will be terminated, so the function
42
-	 * will appear to have no caller.
43
-	 *
44
-	 * By default, there is no limit. If this is called with a depth of zero,
45
-	 * the limit is disabled.
46
-	 *
47
-	 * This will take effect immediately.
48
-	 *
49
-	 * @param int $maxDepth
50
-	 */
51
-	public function setMaxDepth($maxDepth) {
52
-	}
39
+    /**
40
+     * Set the maximum depth of stack trace collection. If this depth is
41
+     * exceeded, the traversal up the stack will be terminated, so the function
42
+     * will appear to have no caller.
43
+     *
44
+     * By default, there is no limit. If this is called with a depth of zero,
45
+     * the limit is disabled.
46
+     *
47
+     * This will take effect immediately.
48
+     *
49
+     * @param int $maxDepth
50
+     */
51
+    public function setMaxDepth($maxDepth) {
52
+    }
53 53
 
54
-	/**
55
-	 * Set a callback which will be called once the specified number of samples
56
-	 * has been collected.
57
-	 *
58
-	 * When the ExcimerProfiler object is destroyed, the callback will also
59
-	 * be called, unless no samples have been collected.
60
-	 *
61
-	 * The callback will be called with a single argument: the ExcimerLog
62
-	 * object containing the samples. Before the callback is called, a new
63
-	 * ExcimerLog object will be created and registered with the
64
-	 * ExcimerProfiler. So ExcimerProfiler::getLog() should not be used from
65
-	 * the callback, since it will not return the samples.
66
-	 *
67
-	 * @param callable $callback
68
-	 * @param int $maxSamples
69
-	 */
70
-	public function setFlushCallback($callback, $maxSamples) {
71
-	}
54
+    /**
55
+     * Set a callback which will be called once the specified number of samples
56
+     * has been collected.
57
+     *
58
+     * When the ExcimerProfiler object is destroyed, the callback will also
59
+     * be called, unless no samples have been collected.
60
+     *
61
+     * The callback will be called with a single argument: the ExcimerLog
62
+     * object containing the samples. Before the callback is called, a new
63
+     * ExcimerLog object will be created and registered with the
64
+     * ExcimerProfiler. So ExcimerProfiler::getLog() should not be used from
65
+     * the callback, since it will not return the samples.
66
+     *
67
+     * @param callable $callback
68
+     * @param int $maxSamples
69
+     */
70
+    public function setFlushCallback($callback, $maxSamples) {
71
+    }
72 72
 
73
-	/**
74
-	 * Clear the flush callback. No callback will be called regardless of
75
-	 * how many samples are collected.
76
-	 */
77
-	public function clearFlushCallback() {
78
-	}
73
+    /**
74
+     * Clear the flush callback. No callback will be called regardless of
75
+     * how many samples are collected.
76
+     */
77
+    public function clearFlushCallback() {
78
+    }
79 79
 
80
-	/**
81
-	 * Start the profiler. If the profiler was already running, it will be
82
-	 * stopped and restarted with new options.
83
-	 */
84
-	public function start() {
85
-	}
80
+    /**
81
+     * Start the profiler. If the profiler was already running, it will be
82
+     * stopped and restarted with new options.
83
+     */
84
+    public function start() {
85
+    }
86 86
 
87
-	/**
88
-	 * Stop the profiler.
89
-	 */
90
-	public function stop() {
91
-	}
87
+    /**
88
+     * Stop the profiler.
89
+     */
90
+    public function stop() {
91
+    }
92 92
 
93
-	/**
94
-	 * Get the current ExcimerLog object.
95
-	 *
96
-	 * Note that if the profiler is running, the object thus returned may be
97
-	 * modified by a timer event at any time, potentially invalidating your
98
-	 * analysis. Instead, the profiler should be stopped first, or flush()
99
-	 * should be used.
100
-	 *
101
-	 * @return ExcimerLog
102
-	 */
103
-	public function getLog() {
104
-	}
93
+    /**
94
+     * Get the current ExcimerLog object.
95
+     *
96
+     * Note that if the profiler is running, the object thus returned may be
97
+     * modified by a timer event at any time, potentially invalidating your
98
+     * analysis. Instead, the profiler should be stopped first, or flush()
99
+     * should be used.
100
+     *
101
+     * @return ExcimerLog
102
+     */
103
+    public function getLog() {
104
+    }
105 105
 
106
-	/**
107
-	 * Create and register a new ExcimerLog object, and return the old
108
-	 * ExcimerLog object.
109
-	 *
110
-	 * This will return all accumulated events to this point, and reset the
111
-	 * log with a new log of zero length.
112
-	 *
113
-	 * @return ExcimerLog
114
-	 */
115
-	public function flush() {
116
-	}
106
+    /**
107
+     * Create and register a new ExcimerLog object, and return the old
108
+     * ExcimerLog object.
109
+     *
110
+     * This will return all accumulated events to this point, and reset the
111
+     * log with a new log of zero length.
112
+     *
113
+     * @return ExcimerLog
114
+     */
115
+    public function flush() {
116
+    }
117 117
 }
118 118
 
119 119
 /**
@@ -127,156 +127,156 @@  discard block
 block discarded – undo
127 127
  *   }
128 128
  */
129 129
 class ExcimerLog implements ArrayAccess, Iterator {
130
-	/**
131
-	 * ExcimerLog is not constructible by user code. Objects of this type
132
-	 * are available via:
133
-	 *   - ExcimerProfiler::getLog()
134
-	 *   - ExcimerProfiler::flush()
135
-	 *   - The callback to ExcimerProfiler::setFlushCallback()
136
-	 */
137
-	final private function __construct() {
138
-	}
130
+    /**
131
+     * ExcimerLog is not constructible by user code. Objects of this type
132
+     * are available via:
133
+     *   - ExcimerProfiler::getLog()
134
+     *   - ExcimerProfiler::flush()
135
+     *   - The callback to ExcimerProfiler::setFlushCallback()
136
+     */
137
+    final private function __construct() {
138
+    }
139 139
 
140
-	/**
141
-	 * Aggregate the stack traces and convert them to a line-based format
142
-	 * understood by Brendan Gregg's FlameGraph utility. Each stack trace is
143
-	 * represented as a series of function names, separated by semicolons.
144
-	 * After this identifier, there is a single space character, then a number
145
-	 * giving the number of times the stack appeared. Then there is a line
146
-	 * break. This is repeated for each unique stack trace.
147
-	 *
148
-	 * @return string
149
-	 */
150
-	public function formatCollapsed() {
151
-	}
140
+    /**
141
+     * Aggregate the stack traces and convert them to a line-based format
142
+     * understood by Brendan Gregg's FlameGraph utility. Each stack trace is
143
+     * represented as a series of function names, separated by semicolons.
144
+     * After this identifier, there is a single space character, then a number
145
+     * giving the number of times the stack appeared. Then there is a line
146
+     * break. This is repeated for each unique stack trace.
147
+     *
148
+     * @return string
149
+     */
150
+    public function formatCollapsed() {
151
+    }
152 152
 
153
-	/**
154
-	 * Produce an array with an element for every function which appears in
155
-	 * the log. The key is a human-readable unique identifier for the function,
156
-	 * method or closure. The value is an associative array with the following
157
-	 * elements:
158
-	 *
159
-	 *   - self: The number of events in which the function itself was running,
160
-	 *     no other userspace function was being called. This includes time
161
-	 *     spent in internal functions that this function called.
162
-	 *   - inclusive: The number of events in which this function appeared
163
-	 *     somewhere in the stack.
164
-	 *
165
-	 * And optionally the following elements, if they are relevant:
166
-	 *
167
-	 *   - file: The filename in which the function appears
168
-	 *   - line: The exact line number at which the first relevant event
169
-	 *     occurred.
170
-	 *   - class: The class name in which the method is defined
171
-	 *   - function: The name of the function or method
172
-	 *   - closure_line: The line number at which the closure was defined
173
-	 *
174
-	 * The event counts in the "self" and "inclusive" fields are adjusted for
175
-	 * overruns. They represent an estimate of the number of profiling periods
176
-	 * in which those functions were present.
177
-	 *
178
-	 * @return array
179
-	 */
180
-	public function aggregateByFunction() {
181
-	}
153
+    /**
154
+     * Produce an array with an element for every function which appears in
155
+     * the log. The key is a human-readable unique identifier for the function,
156
+     * method or closure. The value is an associative array with the following
157
+     * elements:
158
+     *
159
+     *   - self: The number of events in which the function itself was running,
160
+     *     no other userspace function was being called. This includes time
161
+     *     spent in internal functions that this function called.
162
+     *   - inclusive: The number of events in which this function appeared
163
+     *     somewhere in the stack.
164
+     *
165
+     * And optionally the following elements, if they are relevant:
166
+     *
167
+     *   - file: The filename in which the function appears
168
+     *   - line: The exact line number at which the first relevant event
169
+     *     occurred.
170
+     *   - class: The class name in which the method is defined
171
+     *   - function: The name of the function or method
172
+     *   - closure_line: The line number at which the closure was defined
173
+     *
174
+     * The event counts in the "self" and "inclusive" fields are adjusted for
175
+     * overruns. They represent an estimate of the number of profiling periods
176
+     * in which those functions were present.
177
+     *
178
+     * @return array
179
+     */
180
+    public function aggregateByFunction() {
181
+    }
182 182
 
183
-	/**
184
-	 * Get an array which can be JSON encoded for import into speedscope
185
-	 *
186
-	 * @return array
187
-	 */
188
-	public function getSpeedscopeData() {
189
-	}
183
+    /**
184
+     * Get an array which can be JSON encoded for import into speedscope
185
+     *
186
+     * @return array
187
+     */
188
+    public function getSpeedscopeData() {
189
+    }
190 190
 
191
-	/**
192
-	 * Get the total number of profiling periods represented by this log.
193
-	 *
194
-	 * @return int
195
-	 */
196
-	public function getEventCount() {
197
-	}
191
+    /**
192
+     * Get the total number of profiling periods represented by this log.
193
+     *
194
+     * @return int
195
+     */
196
+    public function getEventCount() {
197
+    }
198 198
 
199
-	/**
200
-	 * Get the current ExcimerLogEntry object. Part of the Iterator interface.
201
-	 *
202
-	 * @return ExcimerLogEntry|null
203
-	 */
204
-	public function current() {
205
-	}
199
+    /**
200
+     * Get the current ExcimerLogEntry object. Part of the Iterator interface.
201
+     *
202
+     * @return ExcimerLogEntry|null
203
+     */
204
+    public function current() {
205
+    }
206 206
 
207
-	/**
208
-	 * Get the current integer key or null. Part of the Iterator interface.
209
-	 *
210
-	 * @return int|null
211
-	 */
212
-	public function key() {
213
-	}
207
+    /**
208
+     * Get the current integer key or null. Part of the Iterator interface.
209
+     *
210
+     * @return int|null
211
+     */
212
+    public function key() {
213
+    }
214 214
 
215
-	/**
216
-	 * Advance to the next log entry. Part of the Iterator interface.
217
-	 */
218
-	public function next() {
219
-	}
215
+    /**
216
+     * Advance to the next log entry. Part of the Iterator interface.
217
+     */
218
+    public function next() {
219
+    }
220 220
 
221
-	/**
222
-	 * Rewind back to the first log entry. Part of the Iterator interface.
223
-	 */
224
-	public function rewind() {
225
-	}
221
+    /**
222
+     * Rewind back to the first log entry. Part of the Iterator interface.
223
+     */
224
+    public function rewind() {
225
+    }
226 226
 
227
-	/**
228
-	 * Check if the current position is valid. Part of the Iterator interface.
229
-	 *
230
-	 * @return bool
231
-	 */
232
-	public function valid() {
233
-	}
227
+    /**
228
+     * Check if the current position is valid. Part of the Iterator interface.
229
+     *
230
+     * @return bool
231
+     */
232
+    public function valid() {
233
+    }
234 234
 
235
-	/**
236
-	 * Get the number of log entries contained in this log. This is always less
237
-	 * than or equal to the number returned by getEventCount(), which includes
238
-	 * overruns.
239
-	 *
240
-	 * @return int
241
-	 */
242
-	public function count() {
243
-	}
235
+    /**
236
+     * Get the number of log entries contained in this log. This is always less
237
+     * than or equal to the number returned by getEventCount(), which includes
238
+     * overruns.
239
+     *
240
+     * @return int
241
+     */
242
+    public function count() {
243
+    }
244 244
 
245
-	/**
246
-	 * Determine whether a log entry exists at the specified array offset.
247
-	 * Part of the ArrayAccess interface.
248
-	 *
249
-	 * @param int $offset
250
-	 * @return bool
251
-	 */
252
-	public function offsetExists($offset) {
253
-	}
245
+    /**
246
+     * Determine whether a log entry exists at the specified array offset.
247
+     * Part of the ArrayAccess interface.
248
+     *
249
+     * @param int $offset
250
+     * @return bool
251
+     */
252
+    public function offsetExists($offset) {
253
+    }
254 254
 
255
-	/**
256
-	 * Get the ExcimerLogEntry object at the specified array offset.
257
-	 *
258
-	 * @param int $offset
259
-	 * @return ExcimerLogEntry|null
260
-	 */
261
-	public function offsetGet($offset) {
262
-	}
255
+    /**
256
+     * Get the ExcimerLogEntry object at the specified array offset.
257
+     *
258
+     * @param int $offset
259
+     * @return ExcimerLogEntry|null
260
+     */
261
+    public function offsetGet($offset) {
262
+    }
263 263
 
264
-	/**
265
-	 * This function is included for compliance with the ArrayAccess interface.
266
-	 * It raises a warning and does nothing.
267
-	 *
268
-	 * @param int $offset
269
-	 * @param mixed $value
270
-	 */
271
-	public function offsetSet($offset, $value) {
272
-	}
264
+    /**
265
+     * This function is included for compliance with the ArrayAccess interface.
266
+     * It raises a warning and does nothing.
267
+     *
268
+     * @param int $offset
269
+     * @param mixed $value
270
+     */
271
+    public function offsetSet($offset, $value) {
272
+    }
273 273
 
274
-	/**
275
-	 * This function is included for compliance with the ArrayAccess interface.
276
-	 * It raises a warning and does nothing.
277
-	 *
278
-	 * @param int $offset
279
-	 */
280
-	public function offsetUnset($offset) {
281
-	}
274
+    /**
275
+     * This function is included for compliance with the ArrayAccess interface.
276
+     * It raises a warning and does nothing.
277
+     *
278
+     * @param int $offset
279
+     */
280
+    public function offsetUnset($offset) {
281
+    }
282 282
 }
Please login to merge, or discard this patch.