Passed
Push — master ( 408ed7...54726d )
by Morris
14:32 queued 12s
created
lib/private/User/User.php 2 patches
Indentation   +436 added lines, -436 removed lines patch added patch discarded remove patch
@@ -55,440 +55,440 @@
 block discarded – undo
55 55
 use Symfony\Component\EventDispatcher\GenericEvent;
56 56
 
57 57
 class User implements IUser {
58
-	/** @var string */
59
-	private $uid;
60
-
61
-	/** @var string */
62
-	private $displayName;
63
-
64
-	/** @var UserInterface|null */
65
-	private $backend;
66
-	/** @var EventDispatcherInterface */
67
-	private $legacyDispatcher;
68
-
69
-	/** @var IEventDispatcher */
70
-	private $dispatcher;
71
-
72
-	/** @var bool */
73
-	private $enabled;
74
-
75
-	/** @var Emitter|Manager */
76
-	private $emitter;
77
-
78
-	/** @var string */
79
-	private $home;
80
-
81
-	/** @var int */
82
-	private $lastLogin;
83
-
84
-	/** @var \OCP\IConfig */
85
-	private $config;
86
-
87
-	/** @var IAvatarManager */
88
-	private $avatarManager;
89
-
90
-	/** @var IURLGenerator */
91
-	private $urlGenerator;
92
-
93
-	public function __construct(string $uid, ?UserInterface $backend, EventDispatcherInterface $dispatcher, $emitter = null, IConfig $config = null, $urlGenerator = null) {
94
-		$this->uid = $uid;
95
-		$this->backend = $backend;
96
-		$this->legacyDispatcher = $dispatcher;
97
-		$this->emitter = $emitter;
98
-		if (is_null($config)) {
99
-			$config = \OC::$server->getConfig();
100
-		}
101
-		$this->config = $config;
102
-		$this->urlGenerator = $urlGenerator;
103
-		$enabled = $this->config->getUserValue($uid, 'core', 'enabled', 'true');
104
-		$this->enabled = ($enabled === 'true');
105
-		$this->lastLogin = $this->config->getUserValue($uid, 'login', 'lastLogin', 0);
106
-		if (is_null($this->urlGenerator)) {
107
-			$this->urlGenerator = \OC::$server->getURLGenerator();
108
-		}
109
-		// TODO: inject
110
-		$this->dispatcher = \OC::$server->query(IEventDispatcher::class);
111
-	}
112
-
113
-	/**
114
-	 * get the user id
115
-	 *
116
-	 * @return string
117
-	 */
118
-	public function getUID() {
119
-		return $this->uid;
120
-	}
121
-
122
-	/**
123
-	 * get the display name for the user, if no specific display name is set it will fallback to the user id
124
-	 *
125
-	 * @return string
126
-	 */
127
-	public function getDisplayName() {
128
-		if (!isset($this->displayName)) {
129
-			$displayName = '';
130
-			if ($this->backend && $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) {
131
-				// get display name and strip whitespace from the beginning and end of it
132
-				$backendDisplayName = $this->backend->getDisplayName($this->uid);
133
-				if (is_string($backendDisplayName)) {
134
-					$displayName = trim($backendDisplayName);
135
-				}
136
-			}
137
-
138
-			if (!empty($displayName)) {
139
-				$this->displayName = $displayName;
140
-			} else {
141
-				$this->displayName = $this->uid;
142
-			}
143
-		}
144
-		return $this->displayName;
145
-	}
146
-
147
-	/**
148
-	 * set the displayname for the user
149
-	 *
150
-	 * @param string $displayName
151
-	 * @return bool
152
-	 */
153
-	public function setDisplayName($displayName) {
154
-		$displayName = trim($displayName);
155
-		$oldDisplayName = $this->getDisplayName();
156
-		if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName) && $displayName !== $oldDisplayName) {
157
-			$result = $this->backend->setDisplayName($this->uid, $displayName);
158
-			if ($result) {
159
-				$this->displayName = $displayName;
160
-				$this->triggerChange('displayName', $displayName, $oldDisplayName);
161
-			}
162
-			return $result !== false;
163
-		}
164
-		return false;
165
-	}
166
-
167
-	/**
168
-	 * set the email address of the user
169
-	 *
170
-	 * @param string|null $mailAddress
171
-	 * @return void
172
-	 * @since 9.0.0
173
-	 */
174
-	public function setEMailAddress($mailAddress) {
175
-		$oldMailAddress = $this->getEMailAddress();
176
-		if ($oldMailAddress !== $mailAddress) {
177
-			if ($mailAddress === '') {
178
-				$this->config->deleteUserValue($this->uid, 'settings', 'email');
179
-			} else {
180
-				$this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
181
-			}
182
-			$this->triggerChange('eMailAddress', $mailAddress, $oldMailAddress);
183
-		}
184
-	}
185
-
186
-	/**
187
-	 * returns the timestamp of the user's last login or 0 if the user did never
188
-	 * login
189
-	 *
190
-	 * @return int
191
-	 */
192
-	public function getLastLogin() {
193
-		return $this->lastLogin;
194
-	}
195
-
196
-	/**
197
-	 * updates the timestamp of the most recent login of this user
198
-	 */
199
-	public function updateLastLoginTimestamp() {
200
-		$firstTimeLogin = ($this->lastLogin === 0);
201
-		$this->lastLogin = time();
202
-		$this->config->setUserValue(
203
-			$this->uid, 'login', 'lastLogin', $this->lastLogin);
204
-
205
-		return $firstTimeLogin;
206
-	}
207
-
208
-	/**
209
-	 * Delete the user
210
-	 *
211
-	 * @return bool
212
-	 */
213
-	public function delete() {
214
-		$this->legacyDispatcher->dispatch(IUser::class . '::preDelete', new GenericEvent($this));
215
-		if ($this->emitter) {
216
-			$this->emitter->emit('\OC\User', 'preDelete', [$this]);
217
-		}
218
-		// get the home now because it won't return it after user deletion
219
-		$homePath = $this->getHome();
220
-		$result = $this->backend->deleteUser($this->uid);
221
-		if ($result) {
222
-
223
-			// FIXME: Feels like an hack - suggestions?
224
-
225
-			$groupManager = \OC::$server->getGroupManager();
226
-			// We have to delete the user from all groups
227
-			foreach ($groupManager->getUserGroupIds($this) as $groupId) {
228
-				$group = $groupManager->get($groupId);
229
-				if ($group) {
230
-					$this->dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $this));
231
-					$group->removeUser($this);
232
-					$this->dispatcher->dispatchTyped(new UserRemovedEvent($group, $this));
233
-				}
234
-			}
235
-			// Delete the user's keys in preferences
236
-			\OC::$server->getConfig()->deleteAllUserValues($this->uid);
237
-
238
-			// Delete user files in /data/
239
-			if ($homePath !== false) {
240
-				// FIXME: this operates directly on FS, should use View instead...
241
-				// also this is not testable/mockable...
242
-				\OC_Helper::rmdirr($homePath);
243
-			}
244
-
245
-			// Delete the users entry in the storage table
246
-			Storage::remove('home::' . $this->uid);
247
-
248
-			\OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
249
-			\OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
250
-
251
-			/** @var IAvatarManager $avatarManager */
252
-			$avatarManager = \OC::$server->query(AvatarManager::class);
253
-			$avatarManager->deleteUserAvatar($this->uid);
254
-
255
-			$notification = \OC::$server->getNotificationManager()->createNotification();
256
-			$notification->setUser($this->uid);
257
-			\OC::$server->getNotificationManager()->markProcessed($notification);
258
-
259
-			/** @var AccountManager $accountManager */
260
-			$accountManager = \OC::$server->query(AccountManager::class);
261
-			$accountManager->deleteUser($this);
262
-
263
-			$this->legacyDispatcher->dispatch(IUser::class . '::postDelete', new GenericEvent($this));
264
-			if ($this->emitter) {
265
-				$this->emitter->emit('\OC\User', 'postDelete', [$this]);
266
-			}
267
-		}
268
-		return !($result === false);
269
-	}
270
-
271
-	/**
272
-	 * Set the password of the user
273
-	 *
274
-	 * @param string $password
275
-	 * @param string $recoveryPassword for the encryption app to reset encryption keys
276
-	 * @return bool
277
-	 */
278
-	public function setPassword($password, $recoveryPassword = null) {
279
-		$this->legacyDispatcher->dispatch(IUser::class . '::preSetPassword', new GenericEvent($this, [
280
-			'password' => $password,
281
-			'recoveryPassword' => $recoveryPassword,
282
-		]));
283
-		if ($this->emitter) {
284
-			$this->emitter->emit('\OC\User', 'preSetPassword', [$this, $password, $recoveryPassword]);
285
-		}
286
-		if ($this->backend->implementsActions(Backend::SET_PASSWORD)) {
287
-			$result = $this->backend->setPassword($this->uid, $password);
288
-			$this->legacyDispatcher->dispatch(IUser::class . '::postSetPassword', new GenericEvent($this, [
289
-				'password' => $password,
290
-				'recoveryPassword' => $recoveryPassword,
291
-			]));
292
-			if ($this->emitter) {
293
-				$this->emitter->emit('\OC\User', 'postSetPassword', [$this, $password, $recoveryPassword]);
294
-			}
295
-			return !($result === false);
296
-		} else {
297
-			return false;
298
-		}
299
-	}
300
-
301
-	/**
302
-	 * get the users home folder to mount
303
-	 *
304
-	 * @return string
305
-	 */
306
-	public function getHome() {
307
-		if (!$this->home) {
308
-			if ($this->backend->implementsActions(Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
309
-				$this->home = $home;
310
-			} elseif ($this->config) {
311
-				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
312
-			} else {
313
-				$this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
314
-			}
315
-		}
316
-		return $this->home;
317
-	}
318
-
319
-	/**
320
-	 * Get the name of the backend class the user is connected with
321
-	 *
322
-	 * @return string
323
-	 */
324
-	public function getBackendClassName() {
325
-		if ($this->backend instanceof IUserBackend) {
326
-			return $this->backend->getBackendName();
327
-		}
328
-		return get_class($this->backend);
329
-	}
330
-
331
-	public function getBackend() {
332
-		return $this->backend;
333
-	}
334
-
335
-	/**
336
-	 * check if the backend allows the user to change his avatar on Personal page
337
-	 *
338
-	 * @return bool
339
-	 */
340
-	public function canChangeAvatar() {
341
-		if ($this->backend->implementsActions(Backend::PROVIDE_AVATAR)) {
342
-			return $this->backend->canChangeAvatar($this->uid);
343
-		}
344
-		return true;
345
-	}
346
-
347
-	/**
348
-	 * check if the backend supports changing passwords
349
-	 *
350
-	 * @return bool
351
-	 */
352
-	public function canChangePassword() {
353
-		return $this->backend->implementsActions(Backend::SET_PASSWORD);
354
-	}
355
-
356
-	/**
357
-	 * check if the backend supports changing display names
358
-	 *
359
-	 * @return bool
360
-	 */
361
-	public function canChangeDisplayName() {
362
-		if ($this->config->getSystemValue('allow_user_to_change_display_name') === false) {
363
-			return false;
364
-		}
365
-		return $this->backend->implementsActions(Backend::SET_DISPLAYNAME);
366
-	}
367
-
368
-	/**
369
-	 * check if the user is enabled
370
-	 *
371
-	 * @return bool
372
-	 */
373
-	public function isEnabled() {
374
-		return $this->enabled;
375
-	}
376
-
377
-	/**
378
-	 * set the enabled status for the user
379
-	 *
380
-	 * @param bool $enabled
381
-	 */
382
-	public function setEnabled(bool $enabled = true) {
383
-		$oldStatus = $this->isEnabled();
384
-		$this->enabled = $enabled;
385
-		if ($oldStatus !== $this->enabled) {
386
-			// TODO: First change the value, then trigger the event as done for all other properties.
387
-			$this->triggerChange('enabled', $enabled, $oldStatus);
388
-			$this->config->setUserValue($this->uid, 'core', 'enabled', $enabled ? 'true' : 'false');
389
-		}
390
-	}
391
-
392
-	/**
393
-	 * get the users email address
394
-	 *
395
-	 * @return string|null
396
-	 * @since 9.0.0
397
-	 */
398
-	public function getEMailAddress() {
399
-		return $this->config->getUserValue($this->uid, 'settings', 'email', null);
400
-	}
401
-
402
-	/**
403
-	 * get the users' quota
404
-	 *
405
-	 * @return string
406
-	 * @since 9.0.0
407
-	 */
408
-	public function getQuota() {
409
-		$quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
410
-		if ($quota === 'default') {
411
-			$quota = $this->config->getAppValue('files', 'default_quota', 'none');
412
-		}
413
-		return $quota;
414
-	}
415
-
416
-	/**
417
-	 * set the users' quota
418
-	 *
419
-	 * @param string $quota
420
-	 * @return void
421
-	 * @since 9.0.0
422
-	 */
423
-	public function setQuota($quota) {
424
-		$oldQuota = $this->config->getUserValue($this->uid, 'files', 'quota', '');
425
-		if ($quota !== 'none' and $quota !== 'default') {
426
-			$quota = OC_Helper::computerFileSize($quota);
427
-			$quota = OC_Helper::humanFileSize($quota);
428
-		}
429
-		if ($quota !== $oldQuota) {
430
-			$this->config->setUserValue($this->uid, 'files', 'quota', $quota);
431
-			$this->triggerChange('quota', $quota, $oldQuota);
432
-		}
433
-	}
434
-
435
-	/**
436
-	 * get the avatar image if it exists
437
-	 *
438
-	 * @param int $size
439
-	 * @return IImage|null
440
-	 * @since 9.0.0
441
-	 */
442
-	public function getAvatarImage($size) {
443
-		// delay the initialization
444
-		if (is_null($this->avatarManager)) {
445
-			$this->avatarManager = \OC::$server->getAvatarManager();
446
-		}
447
-
448
-		$avatar = $this->avatarManager->getAvatar($this->uid);
449
-		$image = $avatar->get(-1);
450
-		if ($image) {
451
-			return $image;
452
-		}
453
-
454
-		return null;
455
-	}
456
-
457
-	/**
458
-	 * get the federation cloud id
459
-	 *
460
-	 * @return string
461
-	 * @since 9.0.0
462
-	 */
463
-	public function getCloudId() {
464
-		$uid = $this->getUID();
465
-		$server = $this->urlGenerator->getAbsoluteURL('/');
466
-		$server =  rtrim($this->removeProtocolFromUrl($server), '/');
467
-		return \OC::$server->getCloudIdManager()->getCloudId($uid, $server)->getId();
468
-	}
469
-
470
-	/**
471
-	 * @param string $url
472
-	 * @return string
473
-	 */
474
-	private function removeProtocolFromUrl($url) {
475
-		if (strpos($url, 'https://') === 0) {
476
-			return substr($url, strlen('https://'));
477
-		} elseif (strpos($url, 'http://') === 0) {
478
-			return substr($url, strlen('http://'));
479
-		}
480
-
481
-		return $url;
482
-	}
483
-
484
-	public function triggerChange($feature, $value = null, $oldValue = null) {
485
-		$this->legacyDispatcher->dispatch(IUser::class . '::changeUser', new GenericEvent($this, [
486
-			'feature' => $feature,
487
-			'value' => $value,
488
-			'oldValue' => $oldValue,
489
-		]));
490
-		if ($this->emitter) {
491
-			$this->emitter->emit('\OC\User', 'changeUser', [$this, $feature, $value, $oldValue]);
492
-		}
493
-	}
58
+    /** @var string */
59
+    private $uid;
60
+
61
+    /** @var string */
62
+    private $displayName;
63
+
64
+    /** @var UserInterface|null */
65
+    private $backend;
66
+    /** @var EventDispatcherInterface */
67
+    private $legacyDispatcher;
68
+
69
+    /** @var IEventDispatcher */
70
+    private $dispatcher;
71
+
72
+    /** @var bool */
73
+    private $enabled;
74
+
75
+    /** @var Emitter|Manager */
76
+    private $emitter;
77
+
78
+    /** @var string */
79
+    private $home;
80
+
81
+    /** @var int */
82
+    private $lastLogin;
83
+
84
+    /** @var \OCP\IConfig */
85
+    private $config;
86
+
87
+    /** @var IAvatarManager */
88
+    private $avatarManager;
89
+
90
+    /** @var IURLGenerator */
91
+    private $urlGenerator;
92
+
93
+    public function __construct(string $uid, ?UserInterface $backend, EventDispatcherInterface $dispatcher, $emitter = null, IConfig $config = null, $urlGenerator = null) {
94
+        $this->uid = $uid;
95
+        $this->backend = $backend;
96
+        $this->legacyDispatcher = $dispatcher;
97
+        $this->emitter = $emitter;
98
+        if (is_null($config)) {
99
+            $config = \OC::$server->getConfig();
100
+        }
101
+        $this->config = $config;
102
+        $this->urlGenerator = $urlGenerator;
103
+        $enabled = $this->config->getUserValue($uid, 'core', 'enabled', 'true');
104
+        $this->enabled = ($enabled === 'true');
105
+        $this->lastLogin = $this->config->getUserValue($uid, 'login', 'lastLogin', 0);
106
+        if (is_null($this->urlGenerator)) {
107
+            $this->urlGenerator = \OC::$server->getURLGenerator();
108
+        }
109
+        // TODO: inject
110
+        $this->dispatcher = \OC::$server->query(IEventDispatcher::class);
111
+    }
112
+
113
+    /**
114
+     * get the user id
115
+     *
116
+     * @return string
117
+     */
118
+    public function getUID() {
119
+        return $this->uid;
120
+    }
121
+
122
+    /**
123
+     * get the display name for the user, if no specific display name is set it will fallback to the user id
124
+     *
125
+     * @return string
126
+     */
127
+    public function getDisplayName() {
128
+        if (!isset($this->displayName)) {
129
+            $displayName = '';
130
+            if ($this->backend && $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) {
131
+                // get display name and strip whitespace from the beginning and end of it
132
+                $backendDisplayName = $this->backend->getDisplayName($this->uid);
133
+                if (is_string($backendDisplayName)) {
134
+                    $displayName = trim($backendDisplayName);
135
+                }
136
+            }
137
+
138
+            if (!empty($displayName)) {
139
+                $this->displayName = $displayName;
140
+            } else {
141
+                $this->displayName = $this->uid;
142
+            }
143
+        }
144
+        return $this->displayName;
145
+    }
146
+
147
+    /**
148
+     * set the displayname for the user
149
+     *
150
+     * @param string $displayName
151
+     * @return bool
152
+     */
153
+    public function setDisplayName($displayName) {
154
+        $displayName = trim($displayName);
155
+        $oldDisplayName = $this->getDisplayName();
156
+        if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName) && $displayName !== $oldDisplayName) {
157
+            $result = $this->backend->setDisplayName($this->uid, $displayName);
158
+            if ($result) {
159
+                $this->displayName = $displayName;
160
+                $this->triggerChange('displayName', $displayName, $oldDisplayName);
161
+            }
162
+            return $result !== false;
163
+        }
164
+        return false;
165
+    }
166
+
167
+    /**
168
+     * set the email address of the user
169
+     *
170
+     * @param string|null $mailAddress
171
+     * @return void
172
+     * @since 9.0.0
173
+     */
174
+    public function setEMailAddress($mailAddress) {
175
+        $oldMailAddress = $this->getEMailAddress();
176
+        if ($oldMailAddress !== $mailAddress) {
177
+            if ($mailAddress === '') {
178
+                $this->config->deleteUserValue($this->uid, 'settings', 'email');
179
+            } else {
180
+                $this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
181
+            }
182
+            $this->triggerChange('eMailAddress', $mailAddress, $oldMailAddress);
183
+        }
184
+    }
185
+
186
+    /**
187
+     * returns the timestamp of the user's last login or 0 if the user did never
188
+     * login
189
+     *
190
+     * @return int
191
+     */
192
+    public function getLastLogin() {
193
+        return $this->lastLogin;
194
+    }
195
+
196
+    /**
197
+     * updates the timestamp of the most recent login of this user
198
+     */
199
+    public function updateLastLoginTimestamp() {
200
+        $firstTimeLogin = ($this->lastLogin === 0);
201
+        $this->lastLogin = time();
202
+        $this->config->setUserValue(
203
+            $this->uid, 'login', 'lastLogin', $this->lastLogin);
204
+
205
+        return $firstTimeLogin;
206
+    }
207
+
208
+    /**
209
+     * Delete the user
210
+     *
211
+     * @return bool
212
+     */
213
+    public function delete() {
214
+        $this->legacyDispatcher->dispatch(IUser::class . '::preDelete', new GenericEvent($this));
215
+        if ($this->emitter) {
216
+            $this->emitter->emit('\OC\User', 'preDelete', [$this]);
217
+        }
218
+        // get the home now because it won't return it after user deletion
219
+        $homePath = $this->getHome();
220
+        $result = $this->backend->deleteUser($this->uid);
221
+        if ($result) {
222
+
223
+            // FIXME: Feels like an hack - suggestions?
224
+
225
+            $groupManager = \OC::$server->getGroupManager();
226
+            // We have to delete the user from all groups
227
+            foreach ($groupManager->getUserGroupIds($this) as $groupId) {
228
+                $group = $groupManager->get($groupId);
229
+                if ($group) {
230
+                    $this->dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $this));
231
+                    $group->removeUser($this);
232
+                    $this->dispatcher->dispatchTyped(new UserRemovedEvent($group, $this));
233
+                }
234
+            }
235
+            // Delete the user's keys in preferences
236
+            \OC::$server->getConfig()->deleteAllUserValues($this->uid);
237
+
238
+            // Delete user files in /data/
239
+            if ($homePath !== false) {
240
+                // FIXME: this operates directly on FS, should use View instead...
241
+                // also this is not testable/mockable...
242
+                \OC_Helper::rmdirr($homePath);
243
+            }
244
+
245
+            // Delete the users entry in the storage table
246
+            Storage::remove('home::' . $this->uid);
247
+
248
+            \OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
249
+            \OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
250
+
251
+            /** @var IAvatarManager $avatarManager */
252
+            $avatarManager = \OC::$server->query(AvatarManager::class);
253
+            $avatarManager->deleteUserAvatar($this->uid);
254
+
255
+            $notification = \OC::$server->getNotificationManager()->createNotification();
256
+            $notification->setUser($this->uid);
257
+            \OC::$server->getNotificationManager()->markProcessed($notification);
258
+
259
+            /** @var AccountManager $accountManager */
260
+            $accountManager = \OC::$server->query(AccountManager::class);
261
+            $accountManager->deleteUser($this);
262
+
263
+            $this->legacyDispatcher->dispatch(IUser::class . '::postDelete', new GenericEvent($this));
264
+            if ($this->emitter) {
265
+                $this->emitter->emit('\OC\User', 'postDelete', [$this]);
266
+            }
267
+        }
268
+        return !($result === false);
269
+    }
270
+
271
+    /**
272
+     * Set the password of the user
273
+     *
274
+     * @param string $password
275
+     * @param string $recoveryPassword for the encryption app to reset encryption keys
276
+     * @return bool
277
+     */
278
+    public function setPassword($password, $recoveryPassword = null) {
279
+        $this->legacyDispatcher->dispatch(IUser::class . '::preSetPassword', new GenericEvent($this, [
280
+            'password' => $password,
281
+            'recoveryPassword' => $recoveryPassword,
282
+        ]));
283
+        if ($this->emitter) {
284
+            $this->emitter->emit('\OC\User', 'preSetPassword', [$this, $password, $recoveryPassword]);
285
+        }
286
+        if ($this->backend->implementsActions(Backend::SET_PASSWORD)) {
287
+            $result = $this->backend->setPassword($this->uid, $password);
288
+            $this->legacyDispatcher->dispatch(IUser::class . '::postSetPassword', new GenericEvent($this, [
289
+                'password' => $password,
290
+                'recoveryPassword' => $recoveryPassword,
291
+            ]));
292
+            if ($this->emitter) {
293
+                $this->emitter->emit('\OC\User', 'postSetPassword', [$this, $password, $recoveryPassword]);
294
+            }
295
+            return !($result === false);
296
+        } else {
297
+            return false;
298
+        }
299
+    }
300
+
301
+    /**
302
+     * get the users home folder to mount
303
+     *
304
+     * @return string
305
+     */
306
+    public function getHome() {
307
+        if (!$this->home) {
308
+            if ($this->backend->implementsActions(Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
309
+                $this->home = $home;
310
+            } elseif ($this->config) {
311
+                $this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
312
+            } else {
313
+                $this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
314
+            }
315
+        }
316
+        return $this->home;
317
+    }
318
+
319
+    /**
320
+     * Get the name of the backend class the user is connected with
321
+     *
322
+     * @return string
323
+     */
324
+    public function getBackendClassName() {
325
+        if ($this->backend instanceof IUserBackend) {
326
+            return $this->backend->getBackendName();
327
+        }
328
+        return get_class($this->backend);
329
+    }
330
+
331
+    public function getBackend() {
332
+        return $this->backend;
333
+    }
334
+
335
+    /**
336
+     * check if the backend allows the user to change his avatar on Personal page
337
+     *
338
+     * @return bool
339
+     */
340
+    public function canChangeAvatar() {
341
+        if ($this->backend->implementsActions(Backend::PROVIDE_AVATAR)) {
342
+            return $this->backend->canChangeAvatar($this->uid);
343
+        }
344
+        return true;
345
+    }
346
+
347
+    /**
348
+     * check if the backend supports changing passwords
349
+     *
350
+     * @return bool
351
+     */
352
+    public function canChangePassword() {
353
+        return $this->backend->implementsActions(Backend::SET_PASSWORD);
354
+    }
355
+
356
+    /**
357
+     * check if the backend supports changing display names
358
+     *
359
+     * @return bool
360
+     */
361
+    public function canChangeDisplayName() {
362
+        if ($this->config->getSystemValue('allow_user_to_change_display_name') === false) {
363
+            return false;
364
+        }
365
+        return $this->backend->implementsActions(Backend::SET_DISPLAYNAME);
366
+    }
367
+
368
+    /**
369
+     * check if the user is enabled
370
+     *
371
+     * @return bool
372
+     */
373
+    public function isEnabled() {
374
+        return $this->enabled;
375
+    }
376
+
377
+    /**
378
+     * set the enabled status for the user
379
+     *
380
+     * @param bool $enabled
381
+     */
382
+    public function setEnabled(bool $enabled = true) {
383
+        $oldStatus = $this->isEnabled();
384
+        $this->enabled = $enabled;
385
+        if ($oldStatus !== $this->enabled) {
386
+            // TODO: First change the value, then trigger the event as done for all other properties.
387
+            $this->triggerChange('enabled', $enabled, $oldStatus);
388
+            $this->config->setUserValue($this->uid, 'core', 'enabled', $enabled ? 'true' : 'false');
389
+        }
390
+    }
391
+
392
+    /**
393
+     * get the users email address
394
+     *
395
+     * @return string|null
396
+     * @since 9.0.0
397
+     */
398
+    public function getEMailAddress() {
399
+        return $this->config->getUserValue($this->uid, 'settings', 'email', null);
400
+    }
401
+
402
+    /**
403
+     * get the users' quota
404
+     *
405
+     * @return string
406
+     * @since 9.0.0
407
+     */
408
+    public function getQuota() {
409
+        $quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
410
+        if ($quota === 'default') {
411
+            $quota = $this->config->getAppValue('files', 'default_quota', 'none');
412
+        }
413
+        return $quota;
414
+    }
415
+
416
+    /**
417
+     * set the users' quota
418
+     *
419
+     * @param string $quota
420
+     * @return void
421
+     * @since 9.0.0
422
+     */
423
+    public function setQuota($quota) {
424
+        $oldQuota = $this->config->getUserValue($this->uid, 'files', 'quota', '');
425
+        if ($quota !== 'none' and $quota !== 'default') {
426
+            $quota = OC_Helper::computerFileSize($quota);
427
+            $quota = OC_Helper::humanFileSize($quota);
428
+        }
429
+        if ($quota !== $oldQuota) {
430
+            $this->config->setUserValue($this->uid, 'files', 'quota', $quota);
431
+            $this->triggerChange('quota', $quota, $oldQuota);
432
+        }
433
+    }
434
+
435
+    /**
436
+     * get the avatar image if it exists
437
+     *
438
+     * @param int $size
439
+     * @return IImage|null
440
+     * @since 9.0.0
441
+     */
442
+    public function getAvatarImage($size) {
443
+        // delay the initialization
444
+        if (is_null($this->avatarManager)) {
445
+            $this->avatarManager = \OC::$server->getAvatarManager();
446
+        }
447
+
448
+        $avatar = $this->avatarManager->getAvatar($this->uid);
449
+        $image = $avatar->get(-1);
450
+        if ($image) {
451
+            return $image;
452
+        }
453
+
454
+        return null;
455
+    }
456
+
457
+    /**
458
+     * get the federation cloud id
459
+     *
460
+     * @return string
461
+     * @since 9.0.0
462
+     */
463
+    public function getCloudId() {
464
+        $uid = $this->getUID();
465
+        $server = $this->urlGenerator->getAbsoluteURL('/');
466
+        $server =  rtrim($this->removeProtocolFromUrl($server), '/');
467
+        return \OC::$server->getCloudIdManager()->getCloudId($uid, $server)->getId();
468
+    }
469
+
470
+    /**
471
+     * @param string $url
472
+     * @return string
473
+     */
474
+    private function removeProtocolFromUrl($url) {
475
+        if (strpos($url, 'https://') === 0) {
476
+            return substr($url, strlen('https://'));
477
+        } elseif (strpos($url, 'http://') === 0) {
478
+            return substr($url, strlen('http://'));
479
+        }
480
+
481
+        return $url;
482
+    }
483
+
484
+    public function triggerChange($feature, $value = null, $oldValue = null) {
485
+        $this->legacyDispatcher->dispatch(IUser::class . '::changeUser', new GenericEvent($this, [
486
+            'feature' => $feature,
487
+            'value' => $value,
488
+            'oldValue' => $oldValue,
489
+        ]));
490
+        if ($this->emitter) {
491
+            $this->emitter->emit('\OC\User', 'changeUser', [$this, $feature, $value, $oldValue]);
492
+        }
493
+    }
494 494
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
 	 * @return bool
212 212
 	 */
213 213
 	public function delete() {
214
-		$this->legacyDispatcher->dispatch(IUser::class . '::preDelete', new GenericEvent($this));
214
+		$this->legacyDispatcher->dispatch(IUser::class.'::preDelete', new GenericEvent($this));
215 215
 		if ($this->emitter) {
216 216
 			$this->emitter->emit('\OC\User', 'preDelete', [$this]);
217 217
 		}
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
 			}
244 244
 
245 245
 			// Delete the users entry in the storage table
246
-			Storage::remove('home::' . $this->uid);
246
+			Storage::remove('home::'.$this->uid);
247 247
 
248 248
 			\OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
249 249
 			\OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
 			$accountManager = \OC::$server->query(AccountManager::class);
261 261
 			$accountManager->deleteUser($this);
262 262
 
263
-			$this->legacyDispatcher->dispatch(IUser::class . '::postDelete', new GenericEvent($this));
263
+			$this->legacyDispatcher->dispatch(IUser::class.'::postDelete', new GenericEvent($this));
264 264
 			if ($this->emitter) {
265 265
 				$this->emitter->emit('\OC\User', 'postDelete', [$this]);
266 266
 			}
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
 	 * @return bool
277 277
 	 */
278 278
 	public function setPassword($password, $recoveryPassword = null) {
279
-		$this->legacyDispatcher->dispatch(IUser::class . '::preSetPassword', new GenericEvent($this, [
279
+		$this->legacyDispatcher->dispatch(IUser::class.'::preSetPassword', new GenericEvent($this, [
280 280
 			'password' => $password,
281 281
 			'recoveryPassword' => $recoveryPassword,
282 282
 		]));
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 		}
286 286
 		if ($this->backend->implementsActions(Backend::SET_PASSWORD)) {
287 287
 			$result = $this->backend->setPassword($this->uid, $password);
288
-			$this->legacyDispatcher->dispatch(IUser::class . '::postSetPassword', new GenericEvent($this, [
288
+			$this->legacyDispatcher->dispatch(IUser::class.'::postSetPassword', new GenericEvent($this, [
289 289
 				'password' => $password,
290 290
 				'recoveryPassword' => $recoveryPassword,
291 291
 			]));
@@ -308,9 +308,9 @@  discard block
 block discarded – undo
308 308
 			if ($this->backend->implementsActions(Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
309 309
 				$this->home = $home;
310 310
 			} elseif ($this->config) {
311
-				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
311
+				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/'.$this->uid;
312 312
 			} else {
313
-				$this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
313
+				$this->home = \OC::$SERVERROOT.'/data/'.$this->uid;
314 314
 			}
315 315
 		}
316 316
 		return $this->home;
@@ -463,7 +463,7 @@  discard block
 block discarded – undo
463 463
 	public function getCloudId() {
464 464
 		$uid = $this->getUID();
465 465
 		$server = $this->urlGenerator->getAbsoluteURL('/');
466
-		$server =  rtrim($this->removeProtocolFromUrl($server), '/');
466
+		$server = rtrim($this->removeProtocolFromUrl($server), '/');
467 467
 		return \OC::$server->getCloudIdManager()->getCloudId($uid, $server)->getId();
468 468
 	}
469 469
 
@@ -482,7 +482,7 @@  discard block
 block discarded – undo
482 482
 	}
483 483
 
484 484
 	public function triggerChange($feature, $value = null, $oldValue = null) {
485
-		$this->legacyDispatcher->dispatch(IUser::class . '::changeUser', new GenericEvent($this, [
485
+		$this->legacyDispatcher->dispatch(IUser::class.'::changeUser', new GenericEvent($this, [
486 486
 			'feature' => $feature,
487 487
 			'value' => $value,
488 488
 			'oldValue' => $oldValue,
Please login to merge, or discard this patch.
lib/private/Share20/Hooks.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -23,11 +23,11 @@
 block discarded – undo
23 23
 namespace OC\Share20;
24 24
 
25 25
 class Hooks {
26
-	public static function post_deleteUser($arguments) {
27
-		\OC::$server->getShareManager()->userDeleted($arguments['uid']);
28
-	}
26
+    public static function post_deleteUser($arguments) {
27
+        \OC::$server->getShareManager()->userDeleted($arguments['uid']);
28
+    }
29 29
 
30
-	public static function post_deleteGroup($arguments) {
31
-		\OC::$server->getShareManager()->groupDeleted($arguments['gid']);
32
-	}
30
+    public static function post_deleteGroup($arguments) {
31
+        \OC::$server->getShareManager()->groupDeleted($arguments['gid']);
32
+    }
33 33
 }
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +1010 added lines, -1010 removed lines patch added patch discarded remove patch
@@ -77,1016 +77,1016 @@
 block discarded – undo
77 77
  * OC_autoload!
78 78
  */
79 79
 class OC {
80
-	/**
81
-	 * Associative array for autoloading. classname => filename
82
-	 */
83
-	public static $CLASSPATH = [];
84
-	/**
85
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
86
-	 */
87
-	public static $SERVERROOT = '';
88
-	/**
89
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
90
-	 */
91
-	private static $SUBURI = '';
92
-	/**
93
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
94
-	 */
95
-	public static $WEBROOT = '';
96
-	/**
97
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
98
-	 * web path in 'url'
99
-	 */
100
-	public static $APPSROOTS = [];
101
-
102
-	/**
103
-	 * @var string
104
-	 */
105
-	public static $configDir;
106
-
107
-	/**
108
-	 * requested app
109
-	 */
110
-	public static $REQUESTEDAPP = '';
111
-
112
-	/**
113
-	 * check if Nextcloud runs in cli mode
114
-	 */
115
-	public static $CLI = false;
116
-
117
-	/**
118
-	 * @var \OC\Autoloader $loader
119
-	 */
120
-	public static $loader = null;
121
-
122
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
123
-	public static $composerAutoloader = null;
124
-
125
-	/**
126
-	 * @var \OC\Server
127
-	 */
128
-	public static $server = null;
129
-
130
-	/**
131
-	 * @var \OC\Config
132
-	 */
133
-	private static $config = null;
134
-
135
-	/**
136
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
137
-	 * the app path list is empty or contains an invalid path
138
-	 */
139
-	public static function initPaths() {
140
-		if (defined('PHPUNIT_CONFIG_DIR')) {
141
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
142
-		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
143
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
144
-		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
145
-			self::$configDir = rtrim($dir, '/') . '/';
146
-		} else {
147
-			self::$configDir = OC::$SERVERROOT . '/config/';
148
-		}
149
-		self::$config = new \OC\Config(self::$configDir);
150
-
151
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
152
-		/**
153
-		 * FIXME: The following lines are required because we can't yet instantiate
154
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
155
-		 */
156
-		$params = [
157
-			'server' => [
158
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
159
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
160
-			],
161
-		];
162
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
163
-		$scriptName = $fakeRequest->getScriptName();
164
-		if (substr($scriptName, -1) == '/') {
165
-			$scriptName .= 'index.php';
166
-			//make sure suburi follows the same rules as scriptName
167
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
168
-				if (substr(OC::$SUBURI, -1) != '/') {
169
-					OC::$SUBURI = OC::$SUBURI . '/';
170
-				}
171
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
172
-			}
173
-		}
174
-
175
-
176
-		if (OC::$CLI) {
177
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
178
-		} else {
179
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
180
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
181
-
182
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
183
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
184
-				}
185
-			} else {
186
-				// The scriptName is not ending with OC::$SUBURI
187
-				// This most likely means that we are calling from CLI.
188
-				// However some cron jobs still need to generate
189
-				// a web URL, so we use overwritewebroot as a fallback.
190
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
191
-			}
192
-
193
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
194
-			// slash which is required by URL generation.
195
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
196
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
197
-				header('Location: '.\OC::$WEBROOT.'/');
198
-				exit();
199
-			}
200
-		}
201
-
202
-		// search the apps folder
203
-		$config_paths = self::$config->getValue('apps_paths', []);
204
-		if (!empty($config_paths)) {
205
-			foreach ($config_paths as $paths) {
206
-				if (isset($paths['url']) && isset($paths['path'])) {
207
-					$paths['url'] = rtrim($paths['url'], '/');
208
-					$paths['path'] = rtrim($paths['path'], '/');
209
-					OC::$APPSROOTS[] = $paths;
210
-				}
211
-			}
212
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
213
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
214
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
215
-			OC::$APPSROOTS[] = [
216
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
217
-				'url' => '/apps',
218
-				'writable' => true
219
-			];
220
-		}
221
-
222
-		if (empty(OC::$APPSROOTS)) {
223
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
224
-				. ' or the folder above. You can also configure the location in the config.php file.');
225
-		}
226
-		$paths = [];
227
-		foreach (OC::$APPSROOTS as $path) {
228
-			$paths[] = $path['path'];
229
-			if (!is_dir($path['path'])) {
230
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
231
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
232
-					. ' config.php file.', $path['path']));
233
-			}
234
-		}
235
-
236
-		// set the right include path
237
-		set_include_path(
238
-			implode(PATH_SEPARATOR, $paths)
239
-		);
240
-	}
241
-
242
-	public static function checkConfig() {
243
-		$l = \OC::$server->getL10N('lib');
244
-
245
-		// Create config if it does not already exist
246
-		$configFilePath = self::$configDir .'/config.php';
247
-		if (!file_exists($configFilePath)) {
248
-			@touch($configFilePath);
249
-		}
250
-
251
-		// Check if config is writable
252
-		$configFileWritable = is_writable($configFilePath);
253
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
254
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
255
-			$urlGenerator = \OC::$server->getURLGenerator();
256
-
257
-			if (self::$CLI) {
258
-				echo $l->t('Cannot write into "config" directory!')."\n";
259
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
260
-				echo "\n";
261
-				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
262
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
263
-				exit;
264
-			} else {
265
-				OC_Template::printErrorPage(
266
-					$l->t('Cannot write into "config" directory!'),
267
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
268
-					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
269
-					[ $urlGenerator->linkToDocs('admin-config') ]),
270
-					503
271
-				);
272
-			}
273
-		}
274
-	}
275
-
276
-	public static function checkInstalled() {
277
-		if (defined('OC_CONSOLE')) {
278
-			return;
279
-		}
280
-		// Redirect to installer if not installed
281
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
282
-			if (OC::$CLI) {
283
-				throw new Exception('Not installed');
284
-			} else {
285
-				$url = OC::$WEBROOT . '/index.php';
286
-				header('Location: ' . $url);
287
-			}
288
-			exit();
289
-		}
290
-	}
291
-
292
-	public static function checkMaintenanceMode() {
293
-		// Allow ajax update script to execute without being stopped
294
-		if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
295
-			// send http status 503
296
-			http_response_code(503);
297
-			header('Retry-After: 120');
298
-
299
-			// render error page
300
-			$template = new OC_Template('', 'update.user', 'guest');
301
-			OC_Util::addScript('dist/maintenance');
302
-			OC_Util::addStyle('core', 'guest');
303
-			$template->printPage();
304
-			die();
305
-		}
306
-	}
307
-
308
-	/**
309
-	 * Prints the upgrade page
310
-	 *
311
-	 * @param \OC\SystemConfig $systemConfig
312
-	 */
313
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
314
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
315
-		$tooBig = false;
316
-		if (!$disableWebUpdater) {
317
-			$apps = \OC::$server->getAppManager();
318
-			if ($apps->isInstalled('user_ldap')) {
319
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
320
-
321
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
322
-					->from('ldap_user_mapping')
323
-					->execute();
324
-				$row = $result->fetch();
325
-				$result->closeCursor();
326
-
327
-				$tooBig = ($row['user_count'] > 50);
328
-			}
329
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
330
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
331
-
332
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
333
-					->from('user_saml_users')
334
-					->execute();
335
-				$row = $result->fetch();
336
-				$result->closeCursor();
337
-
338
-				$tooBig = ($row['user_count'] > 50);
339
-			}
340
-			if (!$tooBig) {
341
-				// count users
342
-				$stats = \OC::$server->getUserManager()->countUsers();
343
-				$totalUsers = array_sum($stats);
344
-				$tooBig = ($totalUsers > 50);
345
-			}
346
-		}
347
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
348
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
349
-
350
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
351
-			// send http status 503
352
-			http_response_code(503);
353
-			header('Retry-After: 120');
354
-
355
-			// render error page
356
-			$template = new OC_Template('', 'update.use-cli', 'guest');
357
-			$template->assign('productName', 'nextcloud'); // for now
358
-			$template->assign('version', OC_Util::getVersionString());
359
-			$template->assign('tooBig', $tooBig);
360
-
361
-			$template->printPage();
362
-			die();
363
-		}
364
-
365
-		// check whether this is a core update or apps update
366
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
367
-		$currentVersion = implode('.', \OCP\Util::getVersion());
368
-
369
-		// if not a core upgrade, then it's apps upgrade
370
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
371
-
372
-		$oldTheme = $systemConfig->getValue('theme');
373
-		$systemConfig->setValue('theme', '');
374
-		OC_Util::addScript('config'); // needed for web root
375
-		OC_Util::addScript('update');
376
-
377
-		/** @var \OC\App\AppManager $appManager */
378
-		$appManager = \OC::$server->getAppManager();
379
-
380
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
381
-		$tmpl->assign('version', OC_Util::getVersionString());
382
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
383
-
384
-		// get third party apps
385
-		$ocVersion = \OCP\Util::getVersion();
386
-		$ocVersion = implode('.', $ocVersion);
387
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
388
-		$incompatibleShippedApps = [];
389
-		foreach ($incompatibleApps as $appInfo) {
390
-			if ($appManager->isShipped($appInfo['id'])) {
391
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
392
-			}
393
-		}
394
-
395
-		if (!empty($incompatibleShippedApps)) {
396
-			$l = \OC::$server->getL10N('core');
397
-			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
398
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
399
-		}
400
-
401
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
402
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
403
-		$tmpl->assign('productName', 'Nextcloud'); // for now
404
-		$tmpl->assign('oldTheme', $oldTheme);
405
-		$tmpl->printPage();
406
-	}
407
-
408
-	public static function initSession() {
409
-		if (self::$server->getRequest()->getServerProtocol() === 'https') {
410
-			ini_set('session.cookie_secure', true);
411
-		}
412
-
413
-		// prevents javascript from accessing php session cookies
414
-		ini_set('session.cookie_httponly', 'true');
415
-
416
-		// set the cookie path to the Nextcloud directory
417
-		$cookie_path = OC::$WEBROOT ? : '/';
418
-		ini_set('session.cookie_path', $cookie_path);
419
-
420
-		// Let the session name be changed in the initSession Hook
421
-		$sessionName = OC_Util::getInstanceId();
422
-
423
-		try {
424
-			// set the session name to the instance id - which is unique
425
-			$session = new \OC\Session\Internal($sessionName);
426
-
427
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
428
-			$session = $cryptoWrapper->wrapSession($session);
429
-			self::$server->setSession($session);
430
-
431
-			// if session can't be started break with http 500 error
432
-		} catch (Exception $e) {
433
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
434
-			//show the user a detailed error page
435
-			OC_Template::printExceptionErrorPage($e, 500);
436
-			die();
437
-		}
438
-
439
-		$sessionLifeTime = self::getSessionLifeTime();
440
-
441
-		// session timeout
442
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
443
-			if (isset($_COOKIE[session_name()])) {
444
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
445
-			}
446
-			\OC::$server->getUserSession()->logout();
447
-		}
448
-
449
-		$session->set('LAST_ACTIVITY', time());
450
-	}
451
-
452
-	/**
453
-	 * @return string
454
-	 */
455
-	private static function getSessionLifeTime() {
456
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
457
-	}
458
-
459
-	/**
460
-	 * Try to set some values to the required Nextcloud default
461
-	 */
462
-	public static function setRequiredIniValues() {
463
-		@ini_set('default_charset', 'UTF-8');
464
-		@ini_set('gd.jpeg_ignore_warning', '1');
465
-	}
466
-
467
-	/**
468
-	 * Send the same site cookies
469
-	 */
470
-	private static function sendSameSiteCookies() {
471
-		$cookieParams = session_get_cookie_params();
472
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
473
-		$policies = [
474
-			'lax',
475
-			'strict',
476
-		];
477
-
478
-		// Append __Host to the cookie if it meets the requirements
479
-		$cookiePrefix = '';
480
-		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
481
-			$cookiePrefix = '__Host-';
482
-		}
483
-
484
-		foreach ($policies as $policy) {
485
-			header(
486
-				sprintf(
487
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
488
-					$cookiePrefix,
489
-					$policy,
490
-					$cookieParams['path'],
491
-					$policy
492
-				),
493
-				false
494
-			);
495
-		}
496
-	}
497
-
498
-	/**
499
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
500
-	 * be set in every request if cookies are sent to add a second level of
501
-	 * defense against CSRF.
502
-	 *
503
-	 * If the cookie is not sent this will set the cookie and reload the page.
504
-	 * We use an additional cookie since we want to protect logout CSRF and
505
-	 * also we can't directly interfere with PHP's session mechanism.
506
-	 */
507
-	private static function performSameSiteCookieProtection() {
508
-		$request = \OC::$server->getRequest();
509
-
510
-		// Some user agents are notorious and don't really properly follow HTTP
511
-		// specifications. For those, have an automated opt-out. Since the protection
512
-		// for remote.php is applied in base.php as starting point we need to opt out
513
-		// here.
514
-		$incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
515
-
516
-		// Fallback, if csrf.optout is unset
517
-		if (!is_array($incompatibleUserAgents)) {
518
-			$incompatibleUserAgents = [
519
-				// OS X Finder
520
-				'/^WebDAVFS/',
521
-				// Windows webdav drive
522
-				'/^Microsoft-WebDAV-MiniRedir/',
523
-			];
524
-		}
525
-
526
-		if ($request->isUserAgent($incompatibleUserAgents)) {
527
-			return;
528
-		}
529
-
530
-		if (count($_COOKIE) > 0) {
531
-			$requestUri = $request->getScriptName();
532
-			$processingScript = explode('/', $requestUri);
533
-			$processingScript = $processingScript[count($processingScript)-1];
534
-
535
-			// index.php routes are handled in the middleware
536
-			if ($processingScript === 'index.php') {
537
-				return;
538
-			}
539
-
540
-			// All other endpoints require the lax and the strict cookie
541
-			if (!$request->passesStrictCookieCheck()) {
542
-				self::sendSameSiteCookies();
543
-				// Debug mode gets access to the resources without strict cookie
544
-				// due to the fact that the SabreDAV browser also lives there.
545
-				if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
546
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
547
-					exit();
548
-				}
549
-			}
550
-		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
551
-			self::sendSameSiteCookies();
552
-		}
553
-	}
554
-
555
-	public static function init() {
556
-		// calculate the root directories
557
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
558
-
559
-		// register autoloader
560
-		$loaderStart = microtime(true);
561
-		require_once __DIR__ . '/autoloader.php';
562
-		self::$loader = new \OC\Autoloader([
563
-			OC::$SERVERROOT . '/lib/private/legacy',
564
-		]);
565
-		if (defined('PHPUNIT_RUN')) {
566
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
567
-		}
568
-		spl_autoload_register([self::$loader, 'load']);
569
-		$loaderEnd = microtime(true);
570
-
571
-		self::$CLI = (php_sapi_name() == 'cli');
572
-
573
-		// Add default composer PSR-4 autoloader
574
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
575
-
576
-		try {
577
-			self::initPaths();
578
-			// setup 3rdparty autoloader
579
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
580
-			if (!file_exists($vendorAutoLoad)) {
581
-				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".');
582
-			}
583
-			require_once $vendorAutoLoad;
584
-		} catch (\RuntimeException $e) {
585
-			if (!self::$CLI) {
586
-				http_response_code(503);
587
-			}
588
-			// we can't use the template error page here, because this needs the
589
-			// DI container which isn't available yet
590
-			print($e->getMessage());
591
-			exit();
592
-		}
593
-
594
-		// setup the basic server
595
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
596
-		self::$server->boot();
597
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
598
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
599
-
600
-		// Override php.ini and log everything if we're troubleshooting
601
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
602
-			error_reporting(E_ALL);
603
-		}
604
-
605
-		// Don't display errors and log them
606
-		@ini_set('display_errors', '0');
607
-		@ini_set('log_errors', '1');
608
-
609
-		if (!date_default_timezone_set('UTC')) {
610
-			throw new \RuntimeException('Could not set timezone to UTC');
611
-		}
612
-
613
-		//try to configure php to enable big file uploads.
614
-		//this doesn´t work always depending on the webserver and php configuration.
615
-		//Let´s try to overwrite some defaults anyway
616
-
617
-		//try to set the maximum execution time to 60min
618
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
619
-			@set_time_limit(3600);
620
-		}
621
-		@ini_set('max_execution_time', '3600');
622
-		@ini_set('max_input_time', '3600');
623
-
624
-		//try to set the maximum filesize to 10G
625
-		@ini_set('upload_max_filesize', '10G');
626
-		@ini_set('post_max_size', '10G');
627
-		@ini_set('file_uploads', '50');
628
-
629
-		self::setRequiredIniValues();
630
-		self::handleAuthHeaders();
631
-		self::registerAutoloaderCache();
632
-
633
-		// initialize intl fallback is necessary
634
-		\Patchwork\Utf8\Bootup::initIntl();
635
-		OC_Util::isSetLocaleWorking();
636
-
637
-		if (!defined('PHPUNIT_RUN')) {
638
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
639
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
640
-			OC\Log\ErrorHandler::register($debug);
641
-		}
642
-
643
-		/** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
644
-		$bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
645
-		$bootstrapCoordinator->runRegistration();
646
-
647
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
648
-		OC_App::loadApps(['session']);
649
-		if (!self::$CLI) {
650
-			self::initSession();
651
-		}
652
-		\OC::$server->getEventLogger()->end('init_session');
653
-		self::checkConfig();
654
-		self::checkInstalled();
655
-
656
-		OC_Response::addSecurityHeaders();
657
-
658
-		self::performSameSiteCookieProtection();
659
-
660
-		if (!defined('OC_CONSOLE')) {
661
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
662
-			if (count($errors) > 0) {
663
-				if (!self::$CLI) {
664
-					http_response_code(503);
665
-					OC_Util::addStyle('guest');
666
-					try {
667
-						OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
668
-						exit;
669
-					} catch (\Exception $e) {
670
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
671
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
672
-					}
673
-				}
674
-
675
-				// Convert l10n string into regular string for usage in database
676
-				$staticErrors = [];
677
-				foreach ($errors as $error) {
678
-					echo $error['error'] . "\n";
679
-					echo $error['hint'] . "\n\n";
680
-					$staticErrors[] = [
681
-						'error' => (string)$error['error'],
682
-						'hint' => (string)$error['hint'],
683
-					];
684
-				}
685
-
686
-				try {
687
-					\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
688
-				} catch (\Exception $e) {
689
-					echo('Writing to database failed');
690
-				}
691
-				exit(1);
692
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
693
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
694
-			}
695
-		}
696
-		//try to set the session lifetime
697
-		$sessionLifeTime = self::getSessionLifeTime();
698
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
699
-
700
-		$systemConfig = \OC::$server->getSystemConfig();
701
-
702
-		// User and Groups
703
-		if (!$systemConfig->getValue("installed", false)) {
704
-			self::$server->getSession()->set('user_id', '');
705
-		}
706
-
707
-		OC_User::useBackend(new \OC\User\Database());
708
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
709
-
710
-		// Subscribe to the hook
711
-		\OCP\Util::connectHook(
712
-			'\OCA\Files_Sharing\API\Server2Server',
713
-			'preLoginNameUsedAsUserName',
714
-			'\OC\User\Database',
715
-			'preLoginNameUsedAsUserName'
716
-		);
717
-
718
-		//setup extra user backends
719
-		if (!\OCP\Util::needUpgrade()) {
720
-			OC_User::setupBackends();
721
-		} else {
722
-			// Run upgrades in incognito mode
723
-			OC_User::setIncognitoMode(true);
724
-		}
725
-
726
-		self::registerCleanupHooks();
727
-		self::registerFilesystemHooks();
728
-		self::registerShareHooks();
729
-		self::registerEncryptionWrapper();
730
-		self::registerEncryptionHooks();
731
-		self::registerAccountHooks();
732
-		self::registerResourceCollectionHooks();
733
-		self::registerAppRestrictionsHooks();
734
-
735
-		// Make sure that the application class is not loaded before the database is setup
736
-		if ($systemConfig->getValue("installed", false)) {
737
-			OC_App::loadApp('settings');
738
-		}
739
-
740
-		//make sure temporary files are cleaned up
741
-		$tmpManager = \OC::$server->getTempManager();
742
-		register_shutdown_function([$tmpManager, 'clean']);
743
-		$lockProvider = \OC::$server->getLockingProvider();
744
-		register_shutdown_function([$lockProvider, 'releaseAll']);
745
-
746
-		// Check whether the sample configuration has been copied
747
-		if ($systemConfig->getValue('copied_sample_config', false)) {
748
-			$l = \OC::$server->getL10N('lib');
749
-			OC_Template::printErrorPage(
750
-				$l->t('Sample configuration detected'),
751
-				$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'),
752
-				503
753
-			);
754
-			return;
755
-		}
756
-
757
-		$request = \OC::$server->getRequest();
758
-		$host = $request->getInsecureServerHost();
759
-		/**
760
-		 * if the host passed in headers isn't trusted
761
-		 * FIXME: Should not be in here at all :see_no_evil:
762
-		 */
763
-		if (!OC::$CLI
764
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
765
-			&& self::$server->getConfig()->getSystemValue('installed', false)
766
-		) {
767
-			// Allow access to CSS resources
768
-			$isScssRequest = false;
769
-			if (strpos($request->getPathInfo(), '/css/') === 0) {
770
-				$isScssRequest = true;
771
-			}
772
-
773
-			if (substr($request->getRequestUri(), -11) === '/status.php') {
774
-				http_response_code(400);
775
-				header('Content-Type: application/json');
776
-				echo '{"error": "Trusted domain error.", "code": 15}';
777
-				exit();
778
-			}
779
-
780
-			if (!$isScssRequest) {
781
-				http_response_code(400);
782
-
783
-				\OC::$server->getLogger()->info(
784
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
785
-					[
786
-						'app' => 'core',
787
-						'remoteAddress' => $request->getRemoteAddress(),
788
-						'host' => $host,
789
-					]
790
-				);
791
-
792
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
793
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
794
-				$tmpl->printPage();
795
-
796
-				exit();
797
-			}
798
-		}
799
-		\OC::$server->getEventLogger()->end('boot');
800
-	}
801
-
802
-	/**
803
-	 * register hooks for the cleanup of cache and bruteforce protection
804
-	 */
805
-	public static function registerCleanupHooks() {
806
-		//don't try to do this before we are properly setup
807
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
808
-
809
-			// NOTE: This will be replaced to use OCP
810
-			$userSession = self::$server->getUserSession();
811
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
812
-				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
813
-					// reset brute force delay for this IP address and username
814
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
815
-					$request = \OC::$server->getRequest();
816
-					$throttler = \OC::$server->getBruteForceThrottler();
817
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
818
-				}
819
-
820
-				try {
821
-					$cache = new \OC\Cache\File();
822
-					$cache->gc();
823
-				} catch (\OC\ServerNotAvailableException $e) {
824
-					// not a GC exception, pass it on
825
-					throw $e;
826
-				} catch (\OC\ForbiddenException $e) {
827
-					// filesystem blocked for this request, ignore
828
-				} catch (\Exception $e) {
829
-					// a GC exception should not prevent users from using OC,
830
-					// so log the exception
831
-					\OC::$server->getLogger()->logException($e, [
832
-						'message' => 'Exception when running cache gc.',
833
-						'level' => ILogger::WARN,
834
-						'app' => 'core',
835
-					]);
836
-				}
837
-			});
838
-		}
839
-	}
840
-
841
-	private static function registerEncryptionWrapper() {
842
-		$manager = self::$server->getEncryptionManager();
843
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
844
-	}
845
-
846
-	private static function registerEncryptionHooks() {
847
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
848
-		if ($enabled) {
849
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
850
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
851
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
852
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
853
-		}
854
-	}
855
-
856
-	private static function registerAccountHooks() {
857
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
858
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
859
-	}
860
-
861
-	private static function registerAppRestrictionsHooks() {
862
-		$groupManager = self::$server->query(\OCP\IGroupManager::class);
863
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
864
-			$appManager = self::$server->getAppManager();
865
-			$apps = $appManager->getEnabledAppsForGroup($group);
866
-			foreach ($apps as $appId) {
867
-				$restrictions = $appManager->getAppRestriction($appId);
868
-				if (empty($restrictions)) {
869
-					continue;
870
-				}
871
-				$key = array_search($group->getGID(), $restrictions);
872
-				unset($restrictions[$key]);
873
-				$restrictions = array_values($restrictions);
874
-				if (empty($restrictions)) {
875
-					$appManager->disableApp($appId);
876
-				} else {
877
-					$appManager->enableAppForGroups($appId, $restrictions);
878
-				}
879
-			}
880
-		});
881
-	}
882
-
883
-	private static function registerResourceCollectionHooks() {
884
-		\OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
885
-	}
886
-
887
-	/**
888
-	 * register hooks for the filesystem
889
-	 */
890
-	public static function registerFilesystemHooks() {
891
-		// Check for blacklisted files
892
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
893
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
894
-	}
895
-
896
-	/**
897
-	 * register hooks for sharing
898
-	 */
899
-	public static function registerShareHooks() {
900
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
901
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
902
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
903
-
904
-			/** @var IEventDispatcher $dispatcher */
905
-			$dispatcher = \OC::$server->get(IEventDispatcher::class);
906
-			$dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
907
-		}
908
-	}
909
-
910
-	protected static function registerAutoloaderCache() {
911
-		// The class loader takes an optional low-latency cache, which MUST be
912
-		// namespaced. The instanceid is used for namespacing, but might be
913
-		// unavailable at this point. Furthermore, it might not be possible to
914
-		// generate an instanceid via \OC_Util::getInstanceId() because the
915
-		// config file may not be writable. As such, we only register a class
916
-		// loader cache if instanceid is available without trying to create one.
917
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
918
-		if ($instanceId) {
919
-			try {
920
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
921
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
922
-			} catch (\Exception $ex) {
923
-			}
924
-		}
925
-	}
926
-
927
-	/**
928
-	 * Handle the request
929
-	 */
930
-	public static function handleRequest() {
931
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
932
-		$systemConfig = \OC::$server->getSystemConfig();
933
-
934
-		// Check if Nextcloud is installed or in maintenance (update) mode
935
-		if (!$systemConfig->getValue('installed', false)) {
936
-			\OC::$server->getSession()->clear();
937
-			$setupHelper = new OC\Setup(
938
-				$systemConfig,
939
-				\OC::$server->getIniWrapper(),
940
-				\OC::$server->getL10N('lib'),
941
-				\OC::$server->query(\OCP\Defaults::class),
942
-				\OC::$server->getLogger(),
943
-				\OC::$server->getSecureRandom(),
944
-				\OC::$server->query(\OC\Installer::class)
945
-			);
946
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
947
-			$controller->run($_POST);
948
-			exit();
949
-		}
950
-
951
-		$request = \OC::$server->getRequest();
952
-		$requestPath = $request->getRawPathInfo();
953
-		if ($requestPath === '/heartbeat') {
954
-			return;
955
-		}
956
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
957
-			self::checkMaintenanceMode();
958
-
959
-			if (\OCP\Util::needUpgrade()) {
960
-				if (function_exists('opcache_reset')) {
961
-					opcache_reset();
962
-				}
963
-				if (!((bool) $systemConfig->getValue('maintenance', false))) {
964
-					self::printUpgradePage($systemConfig);
965
-					exit();
966
-				}
967
-			}
968
-		}
969
-
970
-		// emergency app disabling
971
-		if ($requestPath === '/disableapp'
972
-			&& $request->getMethod() === 'POST'
973
-			&& ((array)$request->getParam('appid')) !== ''
974
-		) {
975
-			\OC_JSON::callCheck();
976
-			\OC_JSON::checkAdminUser();
977
-			$appIds = (array)$request->getParam('appid');
978
-			foreach ($appIds as $appId) {
979
-				$appId = \OC_App::cleanAppId($appId);
980
-				\OC::$server->getAppManager()->disableApp($appId);
981
-			}
982
-			\OC_JSON::success();
983
-			exit();
984
-		}
985
-
986
-		// Always load authentication apps
987
-		OC_App::loadApps(['authentication']);
988
-
989
-		// Load minimum set of apps
990
-		if (!\OCP\Util::needUpgrade()
991
-			&& !((bool) $systemConfig->getValue('maintenance', false))) {
992
-			// For logged-in users: Load everything
993
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
994
-				OC_App::loadApps();
995
-			} else {
996
-				// For guests: Load only filesystem and logging
997
-				OC_App::loadApps(['filesystem', 'logging']);
998
-				self::handleLogin($request);
999
-			}
1000
-		}
1001
-
1002
-		if (!self::$CLI) {
1003
-			try {
1004
-				if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1005
-					OC_App::loadApps(['filesystem', 'logging']);
1006
-					OC_App::loadApps();
1007
-				}
1008
-				OC_Util::setupFS();
1009
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1010
-				return;
1011
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1012
-				//header('HTTP/1.0 404 Not Found');
1013
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1014
-				http_response_code(405);
1015
-				return;
1016
-			}
1017
-		}
1018
-
1019
-		// Handle WebDAV
1020
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1021
-			// not allowed any more to prevent people
1022
-			// mounting this root directly.
1023
-			// Users need to mount remote.php/webdav instead.
1024
-			http_response_code(405);
1025
-			return;
1026
-		}
1027
-
1028
-		// Someone is logged in
1029
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1030
-			OC_App::loadApps();
1031
-			OC_User::setupBackends();
1032
-			OC_Util::setupFS();
1033
-			// FIXME
1034
-			// Redirect to default application
1035
-			OC_Util::redirectToDefaultPage();
1036
-		} else {
1037
-			// Not handled and not logged in
1038
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1039
-		}
1040
-	}
1041
-
1042
-	/**
1043
-	 * Check login: apache auth, auth token, basic auth
1044
-	 *
1045
-	 * @param OCP\IRequest $request
1046
-	 * @return boolean
1047
-	 */
1048
-	public static function handleLogin(OCP\IRequest $request) {
1049
-		$userSession = self::$server->getUserSession();
1050
-		if (OC_User::handleApacheAuth()) {
1051
-			return true;
1052
-		}
1053
-		if ($userSession->tryTokenLogin($request)) {
1054
-			return true;
1055
-		}
1056
-		if (isset($_COOKIE['nc_username'])
1057
-			&& isset($_COOKIE['nc_token'])
1058
-			&& isset($_COOKIE['nc_session_id'])
1059
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1060
-			return true;
1061
-		}
1062
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1063
-			return true;
1064
-		}
1065
-		return false;
1066
-	}
1067
-
1068
-	protected static function handleAuthHeaders() {
1069
-		//copy http auth headers for apache+php-fcgid work around
1070
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1071
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1072
-		}
1073
-
1074
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1075
-		$vars = [
1076
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1077
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1078
-		];
1079
-		foreach ($vars as $var) {
1080
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1081
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1082
-				if (count($credentials) === 2) {
1083
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1084
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1085
-					break;
1086
-				}
1087
-			}
1088
-		}
1089
-	}
80
+    /**
81
+     * Associative array for autoloading. classname => filename
82
+     */
83
+    public static $CLASSPATH = [];
84
+    /**
85
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
86
+     */
87
+    public static $SERVERROOT = '';
88
+    /**
89
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
90
+     */
91
+    private static $SUBURI = '';
92
+    /**
93
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
94
+     */
95
+    public static $WEBROOT = '';
96
+    /**
97
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
98
+     * web path in 'url'
99
+     */
100
+    public static $APPSROOTS = [];
101
+
102
+    /**
103
+     * @var string
104
+     */
105
+    public static $configDir;
106
+
107
+    /**
108
+     * requested app
109
+     */
110
+    public static $REQUESTEDAPP = '';
111
+
112
+    /**
113
+     * check if Nextcloud runs in cli mode
114
+     */
115
+    public static $CLI = false;
116
+
117
+    /**
118
+     * @var \OC\Autoloader $loader
119
+     */
120
+    public static $loader = null;
121
+
122
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
123
+    public static $composerAutoloader = null;
124
+
125
+    /**
126
+     * @var \OC\Server
127
+     */
128
+    public static $server = null;
129
+
130
+    /**
131
+     * @var \OC\Config
132
+     */
133
+    private static $config = null;
134
+
135
+    /**
136
+     * @throws \RuntimeException when the 3rdparty directory is missing or
137
+     * the app path list is empty or contains an invalid path
138
+     */
139
+    public static function initPaths() {
140
+        if (defined('PHPUNIT_CONFIG_DIR')) {
141
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
142
+        } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
143
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
144
+        } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
145
+            self::$configDir = rtrim($dir, '/') . '/';
146
+        } else {
147
+            self::$configDir = OC::$SERVERROOT . '/config/';
148
+        }
149
+        self::$config = new \OC\Config(self::$configDir);
150
+
151
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
152
+        /**
153
+         * FIXME: The following lines are required because we can't yet instantiate
154
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
155
+         */
156
+        $params = [
157
+            'server' => [
158
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
159
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
160
+            ],
161
+        ];
162
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
163
+        $scriptName = $fakeRequest->getScriptName();
164
+        if (substr($scriptName, -1) == '/') {
165
+            $scriptName .= 'index.php';
166
+            //make sure suburi follows the same rules as scriptName
167
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
168
+                if (substr(OC::$SUBURI, -1) != '/') {
169
+                    OC::$SUBURI = OC::$SUBURI . '/';
170
+                }
171
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
172
+            }
173
+        }
174
+
175
+
176
+        if (OC::$CLI) {
177
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
178
+        } else {
179
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
180
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
181
+
182
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
183
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
184
+                }
185
+            } else {
186
+                // The scriptName is not ending with OC::$SUBURI
187
+                // This most likely means that we are calling from CLI.
188
+                // However some cron jobs still need to generate
189
+                // a web URL, so we use overwritewebroot as a fallback.
190
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
191
+            }
192
+
193
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
194
+            // slash which is required by URL generation.
195
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
196
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
197
+                header('Location: '.\OC::$WEBROOT.'/');
198
+                exit();
199
+            }
200
+        }
201
+
202
+        // search the apps folder
203
+        $config_paths = self::$config->getValue('apps_paths', []);
204
+        if (!empty($config_paths)) {
205
+            foreach ($config_paths as $paths) {
206
+                if (isset($paths['url']) && isset($paths['path'])) {
207
+                    $paths['url'] = rtrim($paths['url'], '/');
208
+                    $paths['path'] = rtrim($paths['path'], '/');
209
+                    OC::$APPSROOTS[] = $paths;
210
+                }
211
+            }
212
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
213
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
214
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
215
+            OC::$APPSROOTS[] = [
216
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
217
+                'url' => '/apps',
218
+                'writable' => true
219
+            ];
220
+        }
221
+
222
+        if (empty(OC::$APPSROOTS)) {
223
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
224
+                . ' or the folder above. You can also configure the location in the config.php file.');
225
+        }
226
+        $paths = [];
227
+        foreach (OC::$APPSROOTS as $path) {
228
+            $paths[] = $path['path'];
229
+            if (!is_dir($path['path'])) {
230
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
231
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
232
+                    . ' config.php file.', $path['path']));
233
+            }
234
+        }
235
+
236
+        // set the right include path
237
+        set_include_path(
238
+            implode(PATH_SEPARATOR, $paths)
239
+        );
240
+    }
241
+
242
+    public static function checkConfig() {
243
+        $l = \OC::$server->getL10N('lib');
244
+
245
+        // Create config if it does not already exist
246
+        $configFilePath = self::$configDir .'/config.php';
247
+        if (!file_exists($configFilePath)) {
248
+            @touch($configFilePath);
249
+        }
250
+
251
+        // Check if config is writable
252
+        $configFileWritable = is_writable($configFilePath);
253
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
254
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
255
+            $urlGenerator = \OC::$server->getURLGenerator();
256
+
257
+            if (self::$CLI) {
258
+                echo $l->t('Cannot write into "config" directory!')."\n";
259
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
260
+                echo "\n";
261
+                echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
262
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
263
+                exit;
264
+            } else {
265
+                OC_Template::printErrorPage(
266
+                    $l->t('Cannot write into "config" directory!'),
267
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
268
+                    . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
269
+                    [ $urlGenerator->linkToDocs('admin-config') ]),
270
+                    503
271
+                );
272
+            }
273
+        }
274
+    }
275
+
276
+    public static function checkInstalled() {
277
+        if (defined('OC_CONSOLE')) {
278
+            return;
279
+        }
280
+        // Redirect to installer if not installed
281
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
282
+            if (OC::$CLI) {
283
+                throw new Exception('Not installed');
284
+            } else {
285
+                $url = OC::$WEBROOT . '/index.php';
286
+                header('Location: ' . $url);
287
+            }
288
+            exit();
289
+        }
290
+    }
291
+
292
+    public static function checkMaintenanceMode() {
293
+        // Allow ajax update script to execute without being stopped
294
+        if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
295
+            // send http status 503
296
+            http_response_code(503);
297
+            header('Retry-After: 120');
298
+
299
+            // render error page
300
+            $template = new OC_Template('', 'update.user', 'guest');
301
+            OC_Util::addScript('dist/maintenance');
302
+            OC_Util::addStyle('core', 'guest');
303
+            $template->printPage();
304
+            die();
305
+        }
306
+    }
307
+
308
+    /**
309
+     * Prints the upgrade page
310
+     *
311
+     * @param \OC\SystemConfig $systemConfig
312
+     */
313
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
314
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
315
+        $tooBig = false;
316
+        if (!$disableWebUpdater) {
317
+            $apps = \OC::$server->getAppManager();
318
+            if ($apps->isInstalled('user_ldap')) {
319
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
320
+
321
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
322
+                    ->from('ldap_user_mapping')
323
+                    ->execute();
324
+                $row = $result->fetch();
325
+                $result->closeCursor();
326
+
327
+                $tooBig = ($row['user_count'] > 50);
328
+            }
329
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
330
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
331
+
332
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
333
+                    ->from('user_saml_users')
334
+                    ->execute();
335
+                $row = $result->fetch();
336
+                $result->closeCursor();
337
+
338
+                $tooBig = ($row['user_count'] > 50);
339
+            }
340
+            if (!$tooBig) {
341
+                // count users
342
+                $stats = \OC::$server->getUserManager()->countUsers();
343
+                $totalUsers = array_sum($stats);
344
+                $tooBig = ($totalUsers > 50);
345
+            }
346
+        }
347
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
348
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
349
+
350
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
351
+            // send http status 503
352
+            http_response_code(503);
353
+            header('Retry-After: 120');
354
+
355
+            // render error page
356
+            $template = new OC_Template('', 'update.use-cli', 'guest');
357
+            $template->assign('productName', 'nextcloud'); // for now
358
+            $template->assign('version', OC_Util::getVersionString());
359
+            $template->assign('tooBig', $tooBig);
360
+
361
+            $template->printPage();
362
+            die();
363
+        }
364
+
365
+        // check whether this is a core update or apps update
366
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
367
+        $currentVersion = implode('.', \OCP\Util::getVersion());
368
+
369
+        // if not a core upgrade, then it's apps upgrade
370
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
371
+
372
+        $oldTheme = $systemConfig->getValue('theme');
373
+        $systemConfig->setValue('theme', '');
374
+        OC_Util::addScript('config'); // needed for web root
375
+        OC_Util::addScript('update');
376
+
377
+        /** @var \OC\App\AppManager $appManager */
378
+        $appManager = \OC::$server->getAppManager();
379
+
380
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
381
+        $tmpl->assign('version', OC_Util::getVersionString());
382
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
383
+
384
+        // get third party apps
385
+        $ocVersion = \OCP\Util::getVersion();
386
+        $ocVersion = implode('.', $ocVersion);
387
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
388
+        $incompatibleShippedApps = [];
389
+        foreach ($incompatibleApps as $appInfo) {
390
+            if ($appManager->isShipped($appInfo['id'])) {
391
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
392
+            }
393
+        }
394
+
395
+        if (!empty($incompatibleShippedApps)) {
396
+            $l = \OC::$server->getL10N('core');
397
+            $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
398
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
399
+        }
400
+
401
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
402
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
403
+        $tmpl->assign('productName', 'Nextcloud'); // for now
404
+        $tmpl->assign('oldTheme', $oldTheme);
405
+        $tmpl->printPage();
406
+    }
407
+
408
+    public static function initSession() {
409
+        if (self::$server->getRequest()->getServerProtocol() === 'https') {
410
+            ini_set('session.cookie_secure', true);
411
+        }
412
+
413
+        // prevents javascript from accessing php session cookies
414
+        ini_set('session.cookie_httponly', 'true');
415
+
416
+        // set the cookie path to the Nextcloud directory
417
+        $cookie_path = OC::$WEBROOT ? : '/';
418
+        ini_set('session.cookie_path', $cookie_path);
419
+
420
+        // Let the session name be changed in the initSession Hook
421
+        $sessionName = OC_Util::getInstanceId();
422
+
423
+        try {
424
+            // set the session name to the instance id - which is unique
425
+            $session = new \OC\Session\Internal($sessionName);
426
+
427
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
428
+            $session = $cryptoWrapper->wrapSession($session);
429
+            self::$server->setSession($session);
430
+
431
+            // if session can't be started break with http 500 error
432
+        } catch (Exception $e) {
433
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
434
+            //show the user a detailed error page
435
+            OC_Template::printExceptionErrorPage($e, 500);
436
+            die();
437
+        }
438
+
439
+        $sessionLifeTime = self::getSessionLifeTime();
440
+
441
+        // session timeout
442
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
443
+            if (isset($_COOKIE[session_name()])) {
444
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
445
+            }
446
+            \OC::$server->getUserSession()->logout();
447
+        }
448
+
449
+        $session->set('LAST_ACTIVITY', time());
450
+    }
451
+
452
+    /**
453
+     * @return string
454
+     */
455
+    private static function getSessionLifeTime() {
456
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
457
+    }
458
+
459
+    /**
460
+     * Try to set some values to the required Nextcloud default
461
+     */
462
+    public static function setRequiredIniValues() {
463
+        @ini_set('default_charset', 'UTF-8');
464
+        @ini_set('gd.jpeg_ignore_warning', '1');
465
+    }
466
+
467
+    /**
468
+     * Send the same site cookies
469
+     */
470
+    private static function sendSameSiteCookies() {
471
+        $cookieParams = session_get_cookie_params();
472
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
473
+        $policies = [
474
+            'lax',
475
+            'strict',
476
+        ];
477
+
478
+        // Append __Host to the cookie if it meets the requirements
479
+        $cookiePrefix = '';
480
+        if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
481
+            $cookiePrefix = '__Host-';
482
+        }
483
+
484
+        foreach ($policies as $policy) {
485
+            header(
486
+                sprintf(
487
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
488
+                    $cookiePrefix,
489
+                    $policy,
490
+                    $cookieParams['path'],
491
+                    $policy
492
+                ),
493
+                false
494
+            );
495
+        }
496
+    }
497
+
498
+    /**
499
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
500
+     * be set in every request if cookies are sent to add a second level of
501
+     * defense against CSRF.
502
+     *
503
+     * If the cookie is not sent this will set the cookie and reload the page.
504
+     * We use an additional cookie since we want to protect logout CSRF and
505
+     * also we can't directly interfere with PHP's session mechanism.
506
+     */
507
+    private static function performSameSiteCookieProtection() {
508
+        $request = \OC::$server->getRequest();
509
+
510
+        // Some user agents are notorious and don't really properly follow HTTP
511
+        // specifications. For those, have an automated opt-out. Since the protection
512
+        // for remote.php is applied in base.php as starting point we need to opt out
513
+        // here.
514
+        $incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
515
+
516
+        // Fallback, if csrf.optout is unset
517
+        if (!is_array($incompatibleUserAgents)) {
518
+            $incompatibleUserAgents = [
519
+                // OS X Finder
520
+                '/^WebDAVFS/',
521
+                // Windows webdav drive
522
+                '/^Microsoft-WebDAV-MiniRedir/',
523
+            ];
524
+        }
525
+
526
+        if ($request->isUserAgent($incompatibleUserAgents)) {
527
+            return;
528
+        }
529
+
530
+        if (count($_COOKIE) > 0) {
531
+            $requestUri = $request->getScriptName();
532
+            $processingScript = explode('/', $requestUri);
533
+            $processingScript = $processingScript[count($processingScript)-1];
534
+
535
+            // index.php routes are handled in the middleware
536
+            if ($processingScript === 'index.php') {
537
+                return;
538
+            }
539
+
540
+            // All other endpoints require the lax and the strict cookie
541
+            if (!$request->passesStrictCookieCheck()) {
542
+                self::sendSameSiteCookies();
543
+                // Debug mode gets access to the resources without strict cookie
544
+                // due to the fact that the SabreDAV browser also lives there.
545
+                if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
546
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
547
+                    exit();
548
+                }
549
+            }
550
+        } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
551
+            self::sendSameSiteCookies();
552
+        }
553
+    }
554
+
555
+    public static function init() {
556
+        // calculate the root directories
557
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
558
+
559
+        // register autoloader
560
+        $loaderStart = microtime(true);
561
+        require_once __DIR__ . '/autoloader.php';
562
+        self::$loader = new \OC\Autoloader([
563
+            OC::$SERVERROOT . '/lib/private/legacy',
564
+        ]);
565
+        if (defined('PHPUNIT_RUN')) {
566
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
567
+        }
568
+        spl_autoload_register([self::$loader, 'load']);
569
+        $loaderEnd = microtime(true);
570
+
571
+        self::$CLI = (php_sapi_name() == 'cli');
572
+
573
+        // Add default composer PSR-4 autoloader
574
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
575
+
576
+        try {
577
+            self::initPaths();
578
+            // setup 3rdparty autoloader
579
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
580
+            if (!file_exists($vendorAutoLoad)) {
581
+                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".');
582
+            }
583
+            require_once $vendorAutoLoad;
584
+        } catch (\RuntimeException $e) {
585
+            if (!self::$CLI) {
586
+                http_response_code(503);
587
+            }
588
+            // we can't use the template error page here, because this needs the
589
+            // DI container which isn't available yet
590
+            print($e->getMessage());
591
+            exit();
592
+        }
593
+
594
+        // setup the basic server
595
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
596
+        self::$server->boot();
597
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
598
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
599
+
600
+        // Override php.ini and log everything if we're troubleshooting
601
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
602
+            error_reporting(E_ALL);
603
+        }
604
+
605
+        // Don't display errors and log them
606
+        @ini_set('display_errors', '0');
607
+        @ini_set('log_errors', '1');
608
+
609
+        if (!date_default_timezone_set('UTC')) {
610
+            throw new \RuntimeException('Could not set timezone to UTC');
611
+        }
612
+
613
+        //try to configure php to enable big file uploads.
614
+        //this doesn´t work always depending on the webserver and php configuration.
615
+        //Let´s try to overwrite some defaults anyway
616
+
617
+        //try to set the maximum execution time to 60min
618
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
619
+            @set_time_limit(3600);
620
+        }
621
+        @ini_set('max_execution_time', '3600');
622
+        @ini_set('max_input_time', '3600');
623
+
624
+        //try to set the maximum filesize to 10G
625
+        @ini_set('upload_max_filesize', '10G');
626
+        @ini_set('post_max_size', '10G');
627
+        @ini_set('file_uploads', '50');
628
+
629
+        self::setRequiredIniValues();
630
+        self::handleAuthHeaders();
631
+        self::registerAutoloaderCache();
632
+
633
+        // initialize intl fallback is necessary
634
+        \Patchwork\Utf8\Bootup::initIntl();
635
+        OC_Util::isSetLocaleWorking();
636
+
637
+        if (!defined('PHPUNIT_RUN')) {
638
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
639
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
640
+            OC\Log\ErrorHandler::register($debug);
641
+        }
642
+
643
+        /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
644
+        $bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
645
+        $bootstrapCoordinator->runRegistration();
646
+
647
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
648
+        OC_App::loadApps(['session']);
649
+        if (!self::$CLI) {
650
+            self::initSession();
651
+        }
652
+        \OC::$server->getEventLogger()->end('init_session');
653
+        self::checkConfig();
654
+        self::checkInstalled();
655
+
656
+        OC_Response::addSecurityHeaders();
657
+
658
+        self::performSameSiteCookieProtection();
659
+
660
+        if (!defined('OC_CONSOLE')) {
661
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
662
+            if (count($errors) > 0) {
663
+                if (!self::$CLI) {
664
+                    http_response_code(503);
665
+                    OC_Util::addStyle('guest');
666
+                    try {
667
+                        OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
668
+                        exit;
669
+                    } catch (\Exception $e) {
670
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
671
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
672
+                    }
673
+                }
674
+
675
+                // Convert l10n string into regular string for usage in database
676
+                $staticErrors = [];
677
+                foreach ($errors as $error) {
678
+                    echo $error['error'] . "\n";
679
+                    echo $error['hint'] . "\n\n";
680
+                    $staticErrors[] = [
681
+                        'error' => (string)$error['error'],
682
+                        'hint' => (string)$error['hint'],
683
+                    ];
684
+                }
685
+
686
+                try {
687
+                    \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
688
+                } catch (\Exception $e) {
689
+                    echo('Writing to database failed');
690
+                }
691
+                exit(1);
692
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
693
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
694
+            }
695
+        }
696
+        //try to set the session lifetime
697
+        $sessionLifeTime = self::getSessionLifeTime();
698
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
699
+
700
+        $systemConfig = \OC::$server->getSystemConfig();
701
+
702
+        // User and Groups
703
+        if (!$systemConfig->getValue("installed", false)) {
704
+            self::$server->getSession()->set('user_id', '');
705
+        }
706
+
707
+        OC_User::useBackend(new \OC\User\Database());
708
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
709
+
710
+        // Subscribe to the hook
711
+        \OCP\Util::connectHook(
712
+            '\OCA\Files_Sharing\API\Server2Server',
713
+            'preLoginNameUsedAsUserName',
714
+            '\OC\User\Database',
715
+            'preLoginNameUsedAsUserName'
716
+        );
717
+
718
+        //setup extra user backends
719
+        if (!\OCP\Util::needUpgrade()) {
720
+            OC_User::setupBackends();
721
+        } else {
722
+            // Run upgrades in incognito mode
723
+            OC_User::setIncognitoMode(true);
724
+        }
725
+
726
+        self::registerCleanupHooks();
727
+        self::registerFilesystemHooks();
728
+        self::registerShareHooks();
729
+        self::registerEncryptionWrapper();
730
+        self::registerEncryptionHooks();
731
+        self::registerAccountHooks();
732
+        self::registerResourceCollectionHooks();
733
+        self::registerAppRestrictionsHooks();
734
+
735
+        // Make sure that the application class is not loaded before the database is setup
736
+        if ($systemConfig->getValue("installed", false)) {
737
+            OC_App::loadApp('settings');
738
+        }
739
+
740
+        //make sure temporary files are cleaned up
741
+        $tmpManager = \OC::$server->getTempManager();
742
+        register_shutdown_function([$tmpManager, 'clean']);
743
+        $lockProvider = \OC::$server->getLockingProvider();
744
+        register_shutdown_function([$lockProvider, 'releaseAll']);
745
+
746
+        // Check whether the sample configuration has been copied
747
+        if ($systemConfig->getValue('copied_sample_config', false)) {
748
+            $l = \OC::$server->getL10N('lib');
749
+            OC_Template::printErrorPage(
750
+                $l->t('Sample configuration detected'),
751
+                $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'),
752
+                503
753
+            );
754
+            return;
755
+        }
756
+
757
+        $request = \OC::$server->getRequest();
758
+        $host = $request->getInsecureServerHost();
759
+        /**
760
+         * if the host passed in headers isn't trusted
761
+         * FIXME: Should not be in here at all :see_no_evil:
762
+         */
763
+        if (!OC::$CLI
764
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
765
+            && self::$server->getConfig()->getSystemValue('installed', false)
766
+        ) {
767
+            // Allow access to CSS resources
768
+            $isScssRequest = false;
769
+            if (strpos($request->getPathInfo(), '/css/') === 0) {
770
+                $isScssRequest = true;
771
+            }
772
+
773
+            if (substr($request->getRequestUri(), -11) === '/status.php') {
774
+                http_response_code(400);
775
+                header('Content-Type: application/json');
776
+                echo '{"error": "Trusted domain error.", "code": 15}';
777
+                exit();
778
+            }
779
+
780
+            if (!$isScssRequest) {
781
+                http_response_code(400);
782
+
783
+                \OC::$server->getLogger()->info(
784
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
785
+                    [
786
+                        'app' => 'core',
787
+                        'remoteAddress' => $request->getRemoteAddress(),
788
+                        'host' => $host,
789
+                    ]
790
+                );
791
+
792
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
793
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
794
+                $tmpl->printPage();
795
+
796
+                exit();
797
+            }
798
+        }
799
+        \OC::$server->getEventLogger()->end('boot');
800
+    }
801
+
802
+    /**
803
+     * register hooks for the cleanup of cache and bruteforce protection
804
+     */
805
+    public static function registerCleanupHooks() {
806
+        //don't try to do this before we are properly setup
807
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
808
+
809
+            // NOTE: This will be replaced to use OCP
810
+            $userSession = self::$server->getUserSession();
811
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
812
+                if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
813
+                    // reset brute force delay for this IP address and username
814
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
815
+                    $request = \OC::$server->getRequest();
816
+                    $throttler = \OC::$server->getBruteForceThrottler();
817
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
818
+                }
819
+
820
+                try {
821
+                    $cache = new \OC\Cache\File();
822
+                    $cache->gc();
823
+                } catch (\OC\ServerNotAvailableException $e) {
824
+                    // not a GC exception, pass it on
825
+                    throw $e;
826
+                } catch (\OC\ForbiddenException $e) {
827
+                    // filesystem blocked for this request, ignore
828
+                } catch (\Exception $e) {
829
+                    // a GC exception should not prevent users from using OC,
830
+                    // so log the exception
831
+                    \OC::$server->getLogger()->logException($e, [
832
+                        'message' => 'Exception when running cache gc.',
833
+                        'level' => ILogger::WARN,
834
+                        'app' => 'core',
835
+                    ]);
836
+                }
837
+            });
838
+        }
839
+    }
840
+
841
+    private static function registerEncryptionWrapper() {
842
+        $manager = self::$server->getEncryptionManager();
843
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
844
+    }
845
+
846
+    private static function registerEncryptionHooks() {
847
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
848
+        if ($enabled) {
849
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
850
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
851
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
852
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
853
+        }
854
+    }
855
+
856
+    private static function registerAccountHooks() {
857
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
858
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
859
+    }
860
+
861
+    private static function registerAppRestrictionsHooks() {
862
+        $groupManager = self::$server->query(\OCP\IGroupManager::class);
863
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
864
+            $appManager = self::$server->getAppManager();
865
+            $apps = $appManager->getEnabledAppsForGroup($group);
866
+            foreach ($apps as $appId) {
867
+                $restrictions = $appManager->getAppRestriction($appId);
868
+                if (empty($restrictions)) {
869
+                    continue;
870
+                }
871
+                $key = array_search($group->getGID(), $restrictions);
872
+                unset($restrictions[$key]);
873
+                $restrictions = array_values($restrictions);
874
+                if (empty($restrictions)) {
875
+                    $appManager->disableApp($appId);
876
+                } else {
877
+                    $appManager->enableAppForGroups($appId, $restrictions);
878
+                }
879
+            }
880
+        });
881
+    }
882
+
883
+    private static function registerResourceCollectionHooks() {
884
+        \OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
885
+    }
886
+
887
+    /**
888
+     * register hooks for the filesystem
889
+     */
890
+    public static function registerFilesystemHooks() {
891
+        // Check for blacklisted files
892
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
893
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
894
+    }
895
+
896
+    /**
897
+     * register hooks for sharing
898
+     */
899
+    public static function registerShareHooks() {
900
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
901
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
902
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
903
+
904
+            /** @var IEventDispatcher $dispatcher */
905
+            $dispatcher = \OC::$server->get(IEventDispatcher::class);
906
+            $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
907
+        }
908
+    }
909
+
910
+    protected static function registerAutoloaderCache() {
911
+        // The class loader takes an optional low-latency cache, which MUST be
912
+        // namespaced. The instanceid is used for namespacing, but might be
913
+        // unavailable at this point. Furthermore, it might not be possible to
914
+        // generate an instanceid via \OC_Util::getInstanceId() because the
915
+        // config file may not be writable. As such, we only register a class
916
+        // loader cache if instanceid is available without trying to create one.
917
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
918
+        if ($instanceId) {
919
+            try {
920
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
921
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
922
+            } catch (\Exception $ex) {
923
+            }
924
+        }
925
+    }
926
+
927
+    /**
928
+     * Handle the request
929
+     */
930
+    public static function handleRequest() {
931
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
932
+        $systemConfig = \OC::$server->getSystemConfig();
933
+
934
+        // Check if Nextcloud is installed or in maintenance (update) mode
935
+        if (!$systemConfig->getValue('installed', false)) {
936
+            \OC::$server->getSession()->clear();
937
+            $setupHelper = new OC\Setup(
938
+                $systemConfig,
939
+                \OC::$server->getIniWrapper(),
940
+                \OC::$server->getL10N('lib'),
941
+                \OC::$server->query(\OCP\Defaults::class),
942
+                \OC::$server->getLogger(),
943
+                \OC::$server->getSecureRandom(),
944
+                \OC::$server->query(\OC\Installer::class)
945
+            );
946
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
947
+            $controller->run($_POST);
948
+            exit();
949
+        }
950
+
951
+        $request = \OC::$server->getRequest();
952
+        $requestPath = $request->getRawPathInfo();
953
+        if ($requestPath === '/heartbeat') {
954
+            return;
955
+        }
956
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
957
+            self::checkMaintenanceMode();
958
+
959
+            if (\OCP\Util::needUpgrade()) {
960
+                if (function_exists('opcache_reset')) {
961
+                    opcache_reset();
962
+                }
963
+                if (!((bool) $systemConfig->getValue('maintenance', false))) {
964
+                    self::printUpgradePage($systemConfig);
965
+                    exit();
966
+                }
967
+            }
968
+        }
969
+
970
+        // emergency app disabling
971
+        if ($requestPath === '/disableapp'
972
+            && $request->getMethod() === 'POST'
973
+            && ((array)$request->getParam('appid')) !== ''
974
+        ) {
975
+            \OC_JSON::callCheck();
976
+            \OC_JSON::checkAdminUser();
977
+            $appIds = (array)$request->getParam('appid');
978
+            foreach ($appIds as $appId) {
979
+                $appId = \OC_App::cleanAppId($appId);
980
+                \OC::$server->getAppManager()->disableApp($appId);
981
+            }
982
+            \OC_JSON::success();
983
+            exit();
984
+        }
985
+
986
+        // Always load authentication apps
987
+        OC_App::loadApps(['authentication']);
988
+
989
+        // Load minimum set of apps
990
+        if (!\OCP\Util::needUpgrade()
991
+            && !((bool) $systemConfig->getValue('maintenance', false))) {
992
+            // For logged-in users: Load everything
993
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
994
+                OC_App::loadApps();
995
+            } else {
996
+                // For guests: Load only filesystem and logging
997
+                OC_App::loadApps(['filesystem', 'logging']);
998
+                self::handleLogin($request);
999
+            }
1000
+        }
1001
+
1002
+        if (!self::$CLI) {
1003
+            try {
1004
+                if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1005
+                    OC_App::loadApps(['filesystem', 'logging']);
1006
+                    OC_App::loadApps();
1007
+                }
1008
+                OC_Util::setupFS();
1009
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1010
+                return;
1011
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1012
+                //header('HTTP/1.0 404 Not Found');
1013
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1014
+                http_response_code(405);
1015
+                return;
1016
+            }
1017
+        }
1018
+
1019
+        // Handle WebDAV
1020
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1021
+            // not allowed any more to prevent people
1022
+            // mounting this root directly.
1023
+            // Users need to mount remote.php/webdav instead.
1024
+            http_response_code(405);
1025
+            return;
1026
+        }
1027
+
1028
+        // Someone is logged in
1029
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1030
+            OC_App::loadApps();
1031
+            OC_User::setupBackends();
1032
+            OC_Util::setupFS();
1033
+            // FIXME
1034
+            // Redirect to default application
1035
+            OC_Util::redirectToDefaultPage();
1036
+        } else {
1037
+            // Not handled and not logged in
1038
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1039
+        }
1040
+    }
1041
+
1042
+    /**
1043
+     * Check login: apache auth, auth token, basic auth
1044
+     *
1045
+     * @param OCP\IRequest $request
1046
+     * @return boolean
1047
+     */
1048
+    public static function handleLogin(OCP\IRequest $request) {
1049
+        $userSession = self::$server->getUserSession();
1050
+        if (OC_User::handleApacheAuth()) {
1051
+            return true;
1052
+        }
1053
+        if ($userSession->tryTokenLogin($request)) {
1054
+            return true;
1055
+        }
1056
+        if (isset($_COOKIE['nc_username'])
1057
+            && isset($_COOKIE['nc_token'])
1058
+            && isset($_COOKIE['nc_session_id'])
1059
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1060
+            return true;
1061
+        }
1062
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1063
+            return true;
1064
+        }
1065
+        return false;
1066
+    }
1067
+
1068
+    protected static function handleAuthHeaders() {
1069
+        //copy http auth headers for apache+php-fcgid work around
1070
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1071
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1072
+        }
1073
+
1074
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1075
+        $vars = [
1076
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1077
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1078
+        ];
1079
+        foreach ($vars as $var) {
1080
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1081
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1082
+                if (count($credentials) === 2) {
1083
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1084
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1085
+                    break;
1086
+                }
1087
+            }
1088
+        }
1089
+    }
1090 1090
 }
1091 1091
 
1092 1092
 OC::init();
Please login to merge, or discard this patch.
lib/public/Group/Events/BeforeUserRemovedEvent.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -39,37 +39,37 @@
 block discarded – undo
39 39
  */
40 40
 class BeforeUserRemovedEvent extends Event {
41 41
 
42
-	/** @var IGroup */
43
-	private $group;
42
+    /** @var IGroup */
43
+    private $group;
44 44
 
45
-	/*** @var IUser */
46
-	private $user;
45
+    /*** @var IUser */
46
+    private $user;
47 47
 
48
-	/**
49
-	 * @since 18.0.0
50
-	 * @deprecated 20.0.0
51
-	 */
52
-	public function __construct(IGroup $group, IUser $user) {
53
-		parent::__construct();
54
-		$this->group = $group;
55
-		$this->user = $user;
56
-	}
48
+    /**
49
+     * @since 18.0.0
50
+     * @deprecated 20.0.0
51
+     */
52
+    public function __construct(IGroup $group, IUser $user) {
53
+        parent::__construct();
54
+        $this->group = $group;
55
+        $this->user = $user;
56
+    }
57 57
 
58
-	/**
59
-	 * @return IGroup
60
-	 * @since 18.0.0
61
-	 * @deprecated 20.0.0
62
-	 */
63
-	public function getGroup(): IGroup {
64
-		return $this->group;
65
-	}
58
+    /**
59
+     * @return IGroup
60
+     * @since 18.0.0
61
+     * @deprecated 20.0.0
62
+     */
63
+    public function getGroup(): IGroup {
64
+        return $this->group;
65
+    }
66 66
 
67
-	/**
68
-	 * @return IUser
69
-	 * @since 18.0.0
70
-	 * @deprecated 20.0.0
71
-	 */
72
-	public function getUser(): IUser {
73
-		return $this->user;
74
-	}
67
+    /**
68
+     * @return IUser
69
+     * @since 18.0.0
70
+     * @deprecated 20.0.0
71
+     */
72
+    public function getUser(): IUser {
73
+        return $this->user;
74
+    }
75 75
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Jobs/UpdateGroups.php 1 patch
Indentation   +171 added lines, -171 removed lines patch added patch discarded remove patch
@@ -49,190 +49,190 @@
 block discarded – undo
49 49
 use OCP\ILogger;
50 50
 
51 51
 class UpdateGroups extends \OC\BackgroundJob\TimedJob {
52
-	private static $groupsFromDB;
53
-
54
-	private static $groupBE;
55
-
56
-	public function __construct() {
57
-		$this->interval = self::getRefreshInterval();
58
-	}
59
-
60
-	/**
61
-	 * @param mixed $argument
62
-	 */
63
-	public function run($argument) {
64
-		self::updateGroups();
65
-	}
66
-
67
-	public static function updateGroups() {
68
-		\OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', ILogger::DEBUG);
69
-
70
-		$knownGroups = array_keys(self::getKnownGroups());
71
-		$actualGroups = self::getGroupBE()->getGroups();
72
-
73
-		if (empty($actualGroups) && empty($knownGroups)) {
74
-			\OCP\Util::writeLog('user_ldap',
75
-				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
76
-				ILogger::INFO);
77
-			return;
78
-		}
79
-
80
-		self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
81
-		self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
82
-		self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
83
-
84
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', ILogger::DEBUG);
85
-	}
86
-
87
-	/**
88
-	 * @return int
89
-	 */
90
-	private static function getRefreshInterval() {
91
-		//defaults to every hour
92
-		return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
93
-	}
94
-
95
-	/**
96
-	 * @param string[] $groups
97
-	 */
98
-	private static function handleKnownGroups($groups) {
99
-		$dispatcher = \OC::$server->query(IEventDispatcher::class);
100
-		$groupManager = \OC::$server->getGroupManager();
101
-		$userManager = \OC::$server->getUserManager();
102
-
103
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', ILogger::DEBUG);
104
-		$query = \OC_DB::prepare('
52
+    private static $groupsFromDB;
53
+
54
+    private static $groupBE;
55
+
56
+    public function __construct() {
57
+        $this->interval = self::getRefreshInterval();
58
+    }
59
+
60
+    /**
61
+     * @param mixed $argument
62
+     */
63
+    public function run($argument) {
64
+        self::updateGroups();
65
+    }
66
+
67
+    public static function updateGroups() {
68
+        \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', ILogger::DEBUG);
69
+
70
+        $knownGroups = array_keys(self::getKnownGroups());
71
+        $actualGroups = self::getGroupBE()->getGroups();
72
+
73
+        if (empty($actualGroups) && empty($knownGroups)) {
74
+            \OCP\Util::writeLog('user_ldap',
75
+                'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
76
+                ILogger::INFO);
77
+            return;
78
+        }
79
+
80
+        self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
81
+        self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
82
+        self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
83
+
84
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', ILogger::DEBUG);
85
+    }
86
+
87
+    /**
88
+     * @return int
89
+     */
90
+    private static function getRefreshInterval() {
91
+        //defaults to every hour
92
+        return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
93
+    }
94
+
95
+    /**
96
+     * @param string[] $groups
97
+     */
98
+    private static function handleKnownGroups($groups) {
99
+        $dispatcher = \OC::$server->query(IEventDispatcher::class);
100
+        $groupManager = \OC::$server->getGroupManager();
101
+        $userManager = \OC::$server->getUserManager();
102
+
103
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', ILogger::DEBUG);
104
+        $query = \OC_DB::prepare('
105 105
 			UPDATE `*PREFIX*ldap_group_members`
106 106
 			SET `owncloudusers` = ?
107 107
 			WHERE `owncloudname` = ?
108 108
 		');
109
-		foreach ($groups as $group) {
110
-			//we assume, that self::$groupsFromDB has been retrieved already
111
-			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
112
-			$actualUsers = self::getGroupBE()->usersInGroup($group);
113
-			$hasChanged = false;
114
-
115
-			$groupObject = $groupManager->get($group);
116
-			foreach (array_diff($knownUsers, $actualUsers) as $removedUser) {
117
-				$userObject = $userManager->get($removedUser);
118
-				$dispatcher->dispatchTyped(new UserRemovedEvent($groupObject, $userObject));
119
-				\OCP\Util::writeLog('user_ldap',
120
-				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
121
-					ILogger::INFO);
122
-				$hasChanged = true;
123
-			}
124
-			foreach (array_diff($actualUsers, $knownUsers) as $addedUser) {
125
-				\OCP\Util::emitHook('OC_User', 'post_addToGroup', ['uid' => $addedUser, 'gid' => $group]);
126
-				\OCP\Util::writeLog('user_ldap',
127
-				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
128
-					ILogger::INFO);
129
-				$hasChanged = true;
130
-			}
131
-			if ($hasChanged) {
132
-				$query->execute([serialize($actualUsers), $group]);
133
-			}
134
-		}
135
-		\OCP\Util::writeLog('user_ldap',
136
-			'bgJ "updateGroups" – FINISHED dealing with known Groups.',
137
-			ILogger::DEBUG);
138
-	}
139
-
140
-	/**
141
-	 * @param string[] $createdGroups
142
-	 */
143
-	private static function handleCreatedGroups($createdGroups) {
144
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', ILogger::DEBUG);
145
-		$query = \OC_DB::prepare('
109
+        foreach ($groups as $group) {
110
+            //we assume, that self::$groupsFromDB has been retrieved already
111
+            $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
112
+            $actualUsers = self::getGroupBE()->usersInGroup($group);
113
+            $hasChanged = false;
114
+
115
+            $groupObject = $groupManager->get($group);
116
+            foreach (array_diff($knownUsers, $actualUsers) as $removedUser) {
117
+                $userObject = $userManager->get($removedUser);
118
+                $dispatcher->dispatchTyped(new UserRemovedEvent($groupObject, $userObject));
119
+                \OCP\Util::writeLog('user_ldap',
120
+                'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
121
+                    ILogger::INFO);
122
+                $hasChanged = true;
123
+            }
124
+            foreach (array_diff($actualUsers, $knownUsers) as $addedUser) {
125
+                \OCP\Util::emitHook('OC_User', 'post_addToGroup', ['uid' => $addedUser, 'gid' => $group]);
126
+                \OCP\Util::writeLog('user_ldap',
127
+                'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
128
+                    ILogger::INFO);
129
+                $hasChanged = true;
130
+            }
131
+            if ($hasChanged) {
132
+                $query->execute([serialize($actualUsers), $group]);
133
+            }
134
+        }
135
+        \OCP\Util::writeLog('user_ldap',
136
+            'bgJ "updateGroups" – FINISHED dealing with known Groups.',
137
+            ILogger::DEBUG);
138
+    }
139
+
140
+    /**
141
+     * @param string[] $createdGroups
142
+     */
143
+    private static function handleCreatedGroups($createdGroups) {
144
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', ILogger::DEBUG);
145
+        $query = \OC_DB::prepare('
146 146
 			INSERT
147 147
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
148 148
 			VALUES (?, ?)
149 149
 		');
150
-		foreach ($createdGroups as $createdGroup) {
151
-			\OCP\Util::writeLog('user_ldap',
152
-				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
153
-				ILogger::INFO);
154
-			$users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
155
-			$query->execute([$createdGroup, $users]);
156
-		}
157
-		\OCP\Util::writeLog('user_ldap',
158
-			'bgJ "updateGroups" – FINISHED dealing with created Groups.',
159
-			ILogger::DEBUG);
160
-	}
161
-
162
-	/**
163
-	 * @param string[] $removedGroups
164
-	 */
165
-	private static function handleRemovedGroups($removedGroups) {
166
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', ILogger::DEBUG);
167
-		$query = \OC_DB::prepare('
150
+        foreach ($createdGroups as $createdGroup) {
151
+            \OCP\Util::writeLog('user_ldap',
152
+                'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
153
+                ILogger::INFO);
154
+            $users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
155
+            $query->execute([$createdGroup, $users]);
156
+        }
157
+        \OCP\Util::writeLog('user_ldap',
158
+            'bgJ "updateGroups" – FINISHED dealing with created Groups.',
159
+            ILogger::DEBUG);
160
+    }
161
+
162
+    /**
163
+     * @param string[] $removedGroups
164
+     */
165
+    private static function handleRemovedGroups($removedGroups) {
166
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', ILogger::DEBUG);
167
+        $query = \OC_DB::prepare('
168 168
 			DELETE
169 169
 			FROM `*PREFIX*ldap_group_members`
170 170
 			WHERE `owncloudname` = ?
171 171
 		');
172
-		foreach ($removedGroups as $removedGroup) {
173
-			\OCP\Util::writeLog('user_ldap',
174
-				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
175
-				ILogger::INFO);
176
-			$query->execute([$removedGroup]);
177
-		}
178
-		\OCP\Util::writeLog('user_ldap',
179
-			'bgJ "updateGroups" – FINISHED dealing with removed groups.',
180
-			ILogger::DEBUG);
181
-	}
182
-
183
-	/**
184
-	 * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
185
-	 */
186
-	private static function getGroupBE() {
187
-		if (!is_null(self::$groupBE)) {
188
-			return self::$groupBE;
189
-		}
190
-		$helper = new Helper(\OC::$server->getConfig());
191
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
192
-		$ldapWrapper = new LDAP();
193
-		if (count($configPrefixes) === 1) {
194
-			//avoid the proxy when there is only one LDAP server configured
195
-			$dbc = \OC::$server->getDatabaseConnection();
196
-			$userManager = new Manager(
197
-				\OC::$server->getConfig(),
198
-				new FilesystemHelper(),
199
-				new LogWrapper(),
200
-				\OC::$server->getAvatarManager(),
201
-				new \OCP\Image(),
202
-				$dbc,
203
-				\OC::$server->getUserManager(),
204
-				\OC::$server->getNotificationManager());
205
-			$connector = new Connection($ldapWrapper, $configPrefixes[0]);
206
-			$ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig(), \OC::$server->getUserManager());
207
-			$groupMapper = new GroupMapping($dbc);
208
-			$userMapper  = new UserMapping($dbc);
209
-			$ldapAccess->setGroupMapper($groupMapper);
210
-			$ldapAccess->setUserMapper($userMapper);
211
-			self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query(GroupPluginManager::class));
212
-		} else {
213
-			self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query(GroupPluginManager::class));
214
-		}
215
-
216
-		return self::$groupBE;
217
-	}
218
-
219
-	/**
220
-	 * @return array
221
-	 */
222
-	private static function getKnownGroups() {
223
-		if (is_array(self::$groupsFromDB)) {
224
-			return self::$groupsFromDB;
225
-		}
226
-		$query = \OC_DB::prepare('
172
+        foreach ($removedGroups as $removedGroup) {
173
+            \OCP\Util::writeLog('user_ldap',
174
+                'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
175
+                ILogger::INFO);
176
+            $query->execute([$removedGroup]);
177
+        }
178
+        \OCP\Util::writeLog('user_ldap',
179
+            'bgJ "updateGroups" – FINISHED dealing with removed groups.',
180
+            ILogger::DEBUG);
181
+    }
182
+
183
+    /**
184
+     * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
185
+     */
186
+    private static function getGroupBE() {
187
+        if (!is_null(self::$groupBE)) {
188
+            return self::$groupBE;
189
+        }
190
+        $helper = new Helper(\OC::$server->getConfig());
191
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
192
+        $ldapWrapper = new LDAP();
193
+        if (count($configPrefixes) === 1) {
194
+            //avoid the proxy when there is only one LDAP server configured
195
+            $dbc = \OC::$server->getDatabaseConnection();
196
+            $userManager = new Manager(
197
+                \OC::$server->getConfig(),
198
+                new FilesystemHelper(),
199
+                new LogWrapper(),
200
+                \OC::$server->getAvatarManager(),
201
+                new \OCP\Image(),
202
+                $dbc,
203
+                \OC::$server->getUserManager(),
204
+                \OC::$server->getNotificationManager());
205
+            $connector = new Connection($ldapWrapper, $configPrefixes[0]);
206
+            $ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig(), \OC::$server->getUserManager());
207
+            $groupMapper = new GroupMapping($dbc);
208
+            $userMapper  = new UserMapping($dbc);
209
+            $ldapAccess->setGroupMapper($groupMapper);
210
+            $ldapAccess->setUserMapper($userMapper);
211
+            self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query(GroupPluginManager::class));
212
+        } else {
213
+            self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query(GroupPluginManager::class));
214
+        }
215
+
216
+        return self::$groupBE;
217
+    }
218
+
219
+    /**
220
+     * @return array
221
+     */
222
+    private static function getKnownGroups() {
223
+        if (is_array(self::$groupsFromDB)) {
224
+            return self::$groupsFromDB;
225
+        }
226
+        $query = \OC_DB::prepare('
227 227
 			SELECT `owncloudname`, `owncloudusers`
228 228
 			FROM `*PREFIX*ldap_group_members`
229 229
 		');
230
-		$result = $query->execute()->fetchAll();
231
-		self::$groupsFromDB = [];
232
-		foreach ($result as $dataset) {
233
-			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
234
-		}
235
-
236
-		return self::$groupsFromDB;
237
-	}
230
+        $result = $query->execute()->fetchAll();
231
+        self::$groupsFromDB = [];
232
+        foreach ($result as $dataset) {
233
+            self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
234
+        }
235
+
236
+        return self::$groupsFromDB;
237
+    }
238 238
 }
Please login to merge, or discard this patch.