Completed
Push — master ( 44adca...ee4262 )
by Lukas
15:07
created
lib/private/Security/Bruteforce/Throttler.php 2 patches
Indentation   +235 added lines, -235 removed lines patch added patch discarded remove patch
@@ -46,239 +46,239 @@
 block discarded – undo
46 46
  * @package OC\Security\Bruteforce
47 47
  */
48 48
 class Throttler {
49
-	const LOGIN_ACTION = 'login';
50
-
51
-	/** @var IDBConnection */
52
-	private $db;
53
-	/** @var ITimeFactory */
54
-	private $timeFactory;
55
-	/** @var ILogger */
56
-	private $logger;
57
-	/** @var IConfig */
58
-	private $config;
59
-
60
-	/**
61
-	 * @param IDBConnection $db
62
-	 * @param ITimeFactory $timeFactory
63
-	 * @param ILogger $logger
64
-	 * @param IConfig $config
65
-	 */
66
-	public function __construct(IDBConnection $db,
67
-								ITimeFactory $timeFactory,
68
-								ILogger $logger,
69
-								IConfig $config) {
70
-		$this->db = $db;
71
-		$this->timeFactory = $timeFactory;
72
-		$this->logger = $logger;
73
-		$this->config = $config;
74
-	}
75
-
76
-	/**
77
-	 * Convert a number of seconds into the appropriate DateInterval
78
-	 *
79
-	 * @param int $expire
80
-	 * @return \DateInterval
81
-	 */
82
-	private function getCutoff($expire) {
83
-		$d1 = new \DateTime();
84
-		$d2 = clone $d1;
85
-		$d2->sub(new \DateInterval('PT' . $expire . 'S'));
86
-		return $d2->diff($d1);
87
-	}
88
-
89
-	/**
90
-	 * Register a failed attempt to bruteforce a security control
91
-	 *
92
-	 * @param string $action
93
-	 * @param string $ip
94
-	 * @param array $metadata Optional metadata logged to the database
95
-	 * @suppress SqlInjectionChecker
96
-	 */
97
-	public function registerAttempt($action,
98
-									$ip,
99
-									array $metadata = []) {
100
-		// No need to log if the bruteforce protection is disabled
101
-		if($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) {
102
-			return;
103
-		}
104
-
105
-		$ipAddress = new IpAddress($ip);
106
-		$values = [
107
-			'action' => $action,
108
-			'occurred' => $this->timeFactory->getTime(),
109
-			'ip' => (string)$ipAddress,
110
-			'subnet' => $ipAddress->getSubnet(),
111
-			'metadata' => json_encode($metadata),
112
-		];
113
-
114
-		$this->logger->notice(
115
-			sprintf(
116
-				'Bruteforce attempt from "%s" detected for action "%s".',
117
-				$ip,
118
-				$action
119
-			),
120
-			[
121
-				'app' => 'core',
122
-			]
123
-		);
124
-
125
-		$qb = $this->db->getQueryBuilder();
126
-		$qb->insert('bruteforce_attempts');
127
-		foreach($values as $column => $value) {
128
-			$qb->setValue($column, $qb->createNamedParameter($value));
129
-		}
130
-		$qb->execute();
131
-	}
132
-
133
-	/**
134
-	 * Check if the IP is whitelisted
135
-	 *
136
-	 * @param string $ip
137
-	 * @return bool
138
-	 */
139
-	private function isIPWhitelisted($ip) {
140
-		if($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) {
141
-			return true;
142
-		}
143
-
144
-		$keys = $this->config->getAppKeys('bruteForce');
145
-		$keys = array_filter($keys, function($key) {
146
-			$regex = '/^whitelist_/S';
147
-			return preg_match($regex, $key) === 1;
148
-		});
149
-
150
-		if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
151
-			$type = 4;
152
-		} else if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
153
-			$type = 6;
154
-		} else {
155
-			return false;
156
-		}
157
-
158
-		$ip = inet_pton($ip);
159
-
160
-		foreach ($keys as $key) {
161
-			$cidr = $this->config->getAppValue('bruteForce', $key, null);
162
-
163
-			$cx = explode('/', $cidr);
164
-			$addr = $cx[0];
165
-			$mask = (int)$cx[1];
166
-
167
-			// Do not compare ipv4 to ipv6
168
-			if (($type === 4 && !filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) ||
169
-				($type === 6 && !filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))) {
170
-				continue;
171
-			}
172
-
173
-			$addr = inet_pton($addr);
174
-
175
-			$valid = true;
176
-			for($i = 0; $i < $mask; $i++) {
177
-				$part = ord($addr[(int)($i/8)]);
178
-				$orig = ord($ip[(int)($i/8)]);
179
-
180
-				$part = $part & (15 << (1 - ($i % 2)));
181
-				$orig = $orig & (15 << (1 - ($i % 2)));
182
-
183
-				if ($part !== $orig) {
184
-					$valid = false;
185
-					break;
186
-				}
187
-			}
188
-
189
-			if ($valid === true) {
190
-				return true;
191
-			}
192
-		}
193
-
194
-		return false;
195
-
196
-	}
197
-
198
-	/**
199
-	 * Get the throttling delay (in milliseconds)
200
-	 *
201
-	 * @param string $ip
202
-	 * @param string $action optionally filter by action
203
-	 * @return int
204
-	 */
205
-	public function getDelay($ip, $action = '') {
206
-		$ipAddress = new IpAddress($ip);
207
-		if ($this->isIPWhitelisted((string)$ipAddress)) {
208
-			return 0;
209
-		}
210
-
211
-		$cutoffTime = (new \DateTime())
212
-			->sub($this->getCutoff(43200))
213
-			->getTimestamp();
214
-
215
-		$qb = $this->db->getQueryBuilder();
216
-		$qb->select('*')
217
-			->from('bruteforce_attempts')
218
-			->where($qb->expr()->gt('occurred', $qb->createNamedParameter($cutoffTime)))
219
-			->andWhere($qb->expr()->eq('subnet', $qb->createNamedParameter($ipAddress->getSubnet())));
220
-
221
-		if ($action !== '') {
222
-			$qb->andWhere($qb->expr()->eq('action', $qb->createNamedParameter($action)));
223
-		}
224
-
225
-		$attempts = count($qb->execute()->fetchAll());
226
-
227
-		if ($attempts === 0) {
228
-			return 0;
229
-		}
230
-
231
-		$maxDelay = 30;
232
-		$firstDelay = 0.1;
233
-		if ($attempts > (8 * PHP_INT_SIZE - 1))  {
234
-			// Don't ever overflow. Just assume the maxDelay time:s
235
-			$firstDelay = $maxDelay;
236
-		} else {
237
-			$firstDelay *= pow(2, $attempts);
238
-			if ($firstDelay > $maxDelay) {
239
-				$firstDelay = $maxDelay;
240
-			}
241
-		}
242
-		return (int) \ceil($firstDelay * 1000);
243
-	}
244
-
245
-	/**
246
-	 * Reset the throttling delay for an IP address, action and metadata
247
-	 *
248
-	 * @param string $ip
249
-	 * @param string $action
250
-	 * @param string $metadata
251
-	 */
252
-	public function resetDelay($ip, $action, $metadata) {
253
-		$ipAddress = new IpAddress($ip);
254
-		if ($this->isIPWhitelisted((string)$ipAddress)) {
255
-			return;
256
-		}
257
-
258
-		$cutoffTime = (new \DateTime())
259
-			->sub($this->getCutoff(43200))
260
-			->getTimestamp();
261
-
262
-		$qb = $this->db->getQueryBuilder();
263
-		$qb->delete('bruteforce_attempts')
264
-			->where($qb->expr()->gt('occurred', $qb->createNamedParameter($cutoffTime)))
265
-			->andWhere($qb->expr()->eq('subnet', $qb->createNamedParameter($ipAddress->getSubnet())))
266
-			->andWhere($qb->expr()->eq('action', $qb->createNamedParameter($action)))
267
-			->andWhere($qb->expr()->eq('metadata', $qb->createNamedParameter(json_encode($metadata))));
268
-
269
-		$qb->execute();
270
-	}
271
-
272
-	/**
273
-	 * Will sleep for the defined amount of time
274
-	 *
275
-	 * @param string $ip
276
-	 * @param string $action optionally filter by action
277
-	 * @return int the time spent sleeping
278
-	 */
279
-	public function sleepDelay($ip, $action = '') {
280
-		$delay = $this->getDelay($ip, $action);
281
-		usleep($delay * 1000);
282
-		return $delay;
283
-	}
49
+    const LOGIN_ACTION = 'login';
50
+
51
+    /** @var IDBConnection */
52
+    private $db;
53
+    /** @var ITimeFactory */
54
+    private $timeFactory;
55
+    /** @var ILogger */
56
+    private $logger;
57
+    /** @var IConfig */
58
+    private $config;
59
+
60
+    /**
61
+     * @param IDBConnection $db
62
+     * @param ITimeFactory $timeFactory
63
+     * @param ILogger $logger
64
+     * @param IConfig $config
65
+     */
66
+    public function __construct(IDBConnection $db,
67
+                                ITimeFactory $timeFactory,
68
+                                ILogger $logger,
69
+                                IConfig $config) {
70
+        $this->db = $db;
71
+        $this->timeFactory = $timeFactory;
72
+        $this->logger = $logger;
73
+        $this->config = $config;
74
+    }
75
+
76
+    /**
77
+     * Convert a number of seconds into the appropriate DateInterval
78
+     *
79
+     * @param int $expire
80
+     * @return \DateInterval
81
+     */
82
+    private function getCutoff($expire) {
83
+        $d1 = new \DateTime();
84
+        $d2 = clone $d1;
85
+        $d2->sub(new \DateInterval('PT' . $expire . 'S'));
86
+        return $d2->diff($d1);
87
+    }
88
+
89
+    /**
90
+     * Register a failed attempt to bruteforce a security control
91
+     *
92
+     * @param string $action
93
+     * @param string $ip
94
+     * @param array $metadata Optional metadata logged to the database
95
+     * @suppress SqlInjectionChecker
96
+     */
97
+    public function registerAttempt($action,
98
+                                    $ip,
99
+                                    array $metadata = []) {
100
+        // No need to log if the bruteforce protection is disabled
101
+        if($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) {
102
+            return;
103
+        }
104
+
105
+        $ipAddress = new IpAddress($ip);
106
+        $values = [
107
+            'action' => $action,
108
+            'occurred' => $this->timeFactory->getTime(),
109
+            'ip' => (string)$ipAddress,
110
+            'subnet' => $ipAddress->getSubnet(),
111
+            'metadata' => json_encode($metadata),
112
+        ];
113
+
114
+        $this->logger->notice(
115
+            sprintf(
116
+                'Bruteforce attempt from "%s" detected for action "%s".',
117
+                $ip,
118
+                $action
119
+            ),
120
+            [
121
+                'app' => 'core',
122
+            ]
123
+        );
124
+
125
+        $qb = $this->db->getQueryBuilder();
126
+        $qb->insert('bruteforce_attempts');
127
+        foreach($values as $column => $value) {
128
+            $qb->setValue($column, $qb->createNamedParameter($value));
129
+        }
130
+        $qb->execute();
131
+    }
132
+
133
+    /**
134
+     * Check if the IP is whitelisted
135
+     *
136
+     * @param string $ip
137
+     * @return bool
138
+     */
139
+    private function isIPWhitelisted($ip) {
140
+        if($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) {
141
+            return true;
142
+        }
143
+
144
+        $keys = $this->config->getAppKeys('bruteForce');
145
+        $keys = array_filter($keys, function($key) {
146
+            $regex = '/^whitelist_/S';
147
+            return preg_match($regex, $key) === 1;
148
+        });
149
+
150
+        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
151
+            $type = 4;
152
+        } else if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
153
+            $type = 6;
154
+        } else {
155
+            return false;
156
+        }
157
+
158
+        $ip = inet_pton($ip);
159
+
160
+        foreach ($keys as $key) {
161
+            $cidr = $this->config->getAppValue('bruteForce', $key, null);
162
+
163
+            $cx = explode('/', $cidr);
164
+            $addr = $cx[0];
165
+            $mask = (int)$cx[1];
166
+
167
+            // Do not compare ipv4 to ipv6
168
+            if (($type === 4 && !filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) ||
169
+                ($type === 6 && !filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))) {
170
+                continue;
171
+            }
172
+
173
+            $addr = inet_pton($addr);
174
+
175
+            $valid = true;
176
+            for($i = 0; $i < $mask; $i++) {
177
+                $part = ord($addr[(int)($i/8)]);
178
+                $orig = ord($ip[(int)($i/8)]);
179
+
180
+                $part = $part & (15 << (1 - ($i % 2)));
181
+                $orig = $orig & (15 << (1 - ($i % 2)));
182
+
183
+                if ($part !== $orig) {
184
+                    $valid = false;
185
+                    break;
186
+                }
187
+            }
188
+
189
+            if ($valid === true) {
190
+                return true;
191
+            }
192
+        }
193
+
194
+        return false;
195
+
196
+    }
197
+
198
+    /**
199
+     * Get the throttling delay (in milliseconds)
200
+     *
201
+     * @param string $ip
202
+     * @param string $action optionally filter by action
203
+     * @return int
204
+     */
205
+    public function getDelay($ip, $action = '') {
206
+        $ipAddress = new IpAddress($ip);
207
+        if ($this->isIPWhitelisted((string)$ipAddress)) {
208
+            return 0;
209
+        }
210
+
211
+        $cutoffTime = (new \DateTime())
212
+            ->sub($this->getCutoff(43200))
213
+            ->getTimestamp();
214
+
215
+        $qb = $this->db->getQueryBuilder();
216
+        $qb->select('*')
217
+            ->from('bruteforce_attempts')
218
+            ->where($qb->expr()->gt('occurred', $qb->createNamedParameter($cutoffTime)))
219
+            ->andWhere($qb->expr()->eq('subnet', $qb->createNamedParameter($ipAddress->getSubnet())));
220
+
221
+        if ($action !== '') {
222
+            $qb->andWhere($qb->expr()->eq('action', $qb->createNamedParameter($action)));
223
+        }
224
+
225
+        $attempts = count($qb->execute()->fetchAll());
226
+
227
+        if ($attempts === 0) {
228
+            return 0;
229
+        }
230
+
231
+        $maxDelay = 30;
232
+        $firstDelay = 0.1;
233
+        if ($attempts > (8 * PHP_INT_SIZE - 1))  {
234
+            // Don't ever overflow. Just assume the maxDelay time:s
235
+            $firstDelay = $maxDelay;
236
+        } else {
237
+            $firstDelay *= pow(2, $attempts);
238
+            if ($firstDelay > $maxDelay) {
239
+                $firstDelay = $maxDelay;
240
+            }
241
+        }
242
+        return (int) \ceil($firstDelay * 1000);
243
+    }
244
+
245
+    /**
246
+     * Reset the throttling delay for an IP address, action and metadata
247
+     *
248
+     * @param string $ip
249
+     * @param string $action
250
+     * @param string $metadata
251
+     */
252
+    public function resetDelay($ip, $action, $metadata) {
253
+        $ipAddress = new IpAddress($ip);
254
+        if ($this->isIPWhitelisted((string)$ipAddress)) {
255
+            return;
256
+        }
257
+
258
+        $cutoffTime = (new \DateTime())
259
+            ->sub($this->getCutoff(43200))
260
+            ->getTimestamp();
261
+
262
+        $qb = $this->db->getQueryBuilder();
263
+        $qb->delete('bruteforce_attempts')
264
+            ->where($qb->expr()->gt('occurred', $qb->createNamedParameter($cutoffTime)))
265
+            ->andWhere($qb->expr()->eq('subnet', $qb->createNamedParameter($ipAddress->getSubnet())))
266
+            ->andWhere($qb->expr()->eq('action', $qb->createNamedParameter($action)))
267
+            ->andWhere($qb->expr()->eq('metadata', $qb->createNamedParameter(json_encode($metadata))));
268
+
269
+        $qb->execute();
270
+    }
271
+
272
+    /**
273
+     * Will sleep for the defined amount of time
274
+     *
275
+     * @param string $ip
276
+     * @param string $action optionally filter by action
277
+     * @return int the time spent sleeping
278
+     */
279
+    public function sleepDelay($ip, $action = '') {
280
+        $delay = $this->getDelay($ip, $action);
281
+        usleep($delay * 1000);
282
+        return $delay;
283
+    }
284 284
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
 	private function getCutoff($expire) {
83 83
 		$d1 = new \DateTime();
84 84
 		$d2 = clone $d1;
85
-		$d2->sub(new \DateInterval('PT' . $expire . 'S'));
85
+		$d2->sub(new \DateInterval('PT'.$expire.'S'));
86 86
 		return $d2->diff($d1);
87 87
 	}
88 88
 
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 									$ip,
99 99
 									array $metadata = []) {
100 100
 		// No need to log if the bruteforce protection is disabled
101
-		if($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) {
101
+		if ($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) {
102 102
 			return;
103 103
 		}
104 104
 
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
 		$values = [
107 107
 			'action' => $action,
108 108
 			'occurred' => $this->timeFactory->getTime(),
109
-			'ip' => (string)$ipAddress,
109
+			'ip' => (string) $ipAddress,
110 110
 			'subnet' => $ipAddress->getSubnet(),
111 111
 			'metadata' => json_encode($metadata),
112 112
 		];
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
 
125 125
 		$qb = $this->db->getQueryBuilder();
126 126
 		$qb->insert('bruteforce_attempts');
127
-		foreach($values as $column => $value) {
127
+		foreach ($values as $column => $value) {
128 128
 			$qb->setValue($column, $qb->createNamedParameter($value));
129 129
 		}
130 130
 		$qb->execute();
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	 * @return bool
138 138
 	 */
139 139
 	private function isIPWhitelisted($ip) {
140
-		if($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) {
140
+		if ($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) {
141 141
 			return true;
142 142
 		}
143 143
 
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 
163 163
 			$cx = explode('/', $cidr);
164 164
 			$addr = $cx[0];
165
-			$mask = (int)$cx[1];
165
+			$mask = (int) $cx[1];
166 166
 
167 167
 			// Do not compare ipv4 to ipv6
168 168
 			if (($type === 4 && !filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) ||
@@ -173,9 +173,9 @@  discard block
 block discarded – undo
173 173
 			$addr = inet_pton($addr);
174 174
 
175 175
 			$valid = true;
176
-			for($i = 0; $i < $mask; $i++) {
177
-				$part = ord($addr[(int)($i/8)]);
178
-				$orig = ord($ip[(int)($i/8)]);
176
+			for ($i = 0; $i < $mask; $i++) {
177
+				$part = ord($addr[(int) ($i / 8)]);
178
+				$orig = ord($ip[(int) ($i / 8)]);
179 179
 
180 180
 				$part = $part & (15 << (1 - ($i % 2)));
181 181
 				$orig = $orig & (15 << (1 - ($i % 2)));
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
 	 */
205 205
 	public function getDelay($ip, $action = '') {
206 206
 		$ipAddress = new IpAddress($ip);
207
-		if ($this->isIPWhitelisted((string)$ipAddress)) {
207
+		if ($this->isIPWhitelisted((string) $ipAddress)) {
208 208
 			return 0;
209 209
 		}
210 210
 
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 
231 231
 		$maxDelay = 30;
232 232
 		$firstDelay = 0.1;
233
-		if ($attempts > (8 * PHP_INT_SIZE - 1))  {
233
+		if ($attempts > (8 * PHP_INT_SIZE - 1)) {
234 234
 			// Don't ever overflow. Just assume the maxDelay time:s
235 235
 			$firstDelay = $maxDelay;
236 236
 		} else {
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
 	 */
252 252
 	public function resetDelay($ip, $action, $metadata) {
253 253
 		$ipAddress = new IpAddress($ip);
254
-		if ($this->isIPWhitelisted((string)$ipAddress)) {
254
+		if ($this->isIPWhitelisted((string) $ipAddress)) {
255 255
 			return;
256 256
 		}
257 257
 
Please login to merge, or discard this patch.
lib/base.php 2 patches
Indentation   +998 added lines, -998 removed lines patch added patch discarded remove patch
@@ -62,1004 +62,1004 @@
 block discarded – undo
62 62
  * OC_autoload!
63 63
  */
64 64
 class OC {
65
-	/**
66
-	 * Associative array for autoloading. classname => filename
67
-	 */
68
-	public static $CLASSPATH = array();
69
-	/**
70
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
71
-	 */
72
-	public static $SERVERROOT = '';
73
-	/**
74
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
75
-	 */
76
-	private static $SUBURI = '';
77
-	/**
78
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
79
-	 */
80
-	public static $WEBROOT = '';
81
-	/**
82
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
83
-	 * web path in 'url'
84
-	 */
85
-	public static $APPSROOTS = array();
86
-
87
-	/**
88
-	 * @var string
89
-	 */
90
-	public static $configDir;
91
-
92
-	/**
93
-	 * requested app
94
-	 */
95
-	public static $REQUESTEDAPP = '';
96
-
97
-	/**
98
-	 * check if Nextcloud runs in cli mode
99
-	 */
100
-	public static $CLI = false;
101
-
102
-	/**
103
-	 * @var \OC\Autoloader $loader
104
-	 */
105
-	public static $loader = null;
106
-
107
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
108
-	public static $composerAutoloader = null;
109
-
110
-	/**
111
-	 * @var \OC\Server
112
-	 */
113
-	public static $server = null;
114
-
115
-	/**
116
-	 * @var \OC\Config
117
-	 */
118
-	private static $config = null;
119
-
120
-	/**
121
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
122
-	 * the app path list is empty or contains an invalid path
123
-	 */
124
-	public static function initPaths() {
125
-		if(defined('PHPUNIT_CONFIG_DIR')) {
126
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
127
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
128
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
129
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
-			self::$configDir = rtrim($dir, '/') . '/';
131
-		} else {
132
-			self::$configDir = OC::$SERVERROOT . '/config/';
133
-		}
134
-		self::$config = new \OC\Config(self::$configDir);
135
-
136
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
137
-		/**
138
-		 * FIXME: The following lines are required because we can't yet instantiate
139
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
140
-		 */
141
-		$params = [
142
-			'server' => [
143
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
144
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
145
-			],
146
-		];
147
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
148
-		$scriptName = $fakeRequest->getScriptName();
149
-		if (substr($scriptName, -1) == '/') {
150
-			$scriptName .= 'index.php';
151
-			//make sure suburi follows the same rules as scriptName
152
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
153
-				if (substr(OC::$SUBURI, -1) != '/') {
154
-					OC::$SUBURI = OC::$SUBURI . '/';
155
-				}
156
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
157
-			}
158
-		}
159
-
160
-
161
-		if (OC::$CLI) {
162
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
163
-		} else {
164
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
165
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
166
-
167
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
168
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
169
-				}
170
-			} else {
171
-				// The scriptName is not ending with OC::$SUBURI
172
-				// This most likely means that we are calling from CLI.
173
-				// However some cron jobs still need to generate
174
-				// a web URL, so we use overwritewebroot as a fallback.
175
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
176
-			}
177
-
178
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
179
-			// slash which is required by URL generation.
180
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
181
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
182
-				header('Location: '.\OC::$WEBROOT.'/');
183
-				exit();
184
-			}
185
-		}
186
-
187
-		// search the apps folder
188
-		$config_paths = self::$config->getValue('apps_paths', array());
189
-		if (!empty($config_paths)) {
190
-			foreach ($config_paths as $paths) {
191
-				if (isset($paths['url']) && isset($paths['path'])) {
192
-					$paths['url'] = rtrim($paths['url'], '/');
193
-					$paths['path'] = rtrim($paths['path'], '/');
194
-					OC::$APPSROOTS[] = $paths;
195
-				}
196
-			}
197
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
198
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
199
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
200
-			OC::$APPSROOTS[] = array(
201
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
202
-				'url' => '/apps',
203
-				'writable' => true
204
-			);
205
-		}
206
-
207
-		if (empty(OC::$APPSROOTS)) {
208
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
209
-				. ' or the folder above. You can also configure the location in the config.php file.');
210
-		}
211
-		$paths = array();
212
-		foreach (OC::$APPSROOTS as $path) {
213
-			$paths[] = $path['path'];
214
-			if (!is_dir($path['path'])) {
215
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
216
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
217
-					. ' config.php file.', $path['path']));
218
-			}
219
-		}
220
-
221
-		// set the right include path
222
-		set_include_path(
223
-			implode(PATH_SEPARATOR, $paths)
224
-		);
225
-	}
226
-
227
-	public static function checkConfig() {
228
-		$l = \OC::$server->getL10N('lib');
229
-
230
-		// Create config if it does not already exist
231
-		$configFilePath = self::$configDir .'/config.php';
232
-		if(!file_exists($configFilePath)) {
233
-			@touch($configFilePath);
234
-		}
235
-
236
-		// Check if config is writable
237
-		$configFileWritable = is_writable($configFilePath);
238
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
239
-			|| !$configFileWritable && self::checkUpgrade(false)) {
240
-
241
-			$urlGenerator = \OC::$server->getURLGenerator();
242
-
243
-			if (self::$CLI) {
244
-				echo $l->t('Cannot write into "config" directory!')."\n";
245
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246
-				echo "\n";
247
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
248
-				exit;
249
-			} else {
250
-				OC_Template::printErrorPage(
251
-					$l->t('Cannot write into "config" directory!'),
252
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
253
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
254
-				);
255
-			}
256
-		}
257
-	}
258
-
259
-	public static function checkInstalled() {
260
-		if (defined('OC_CONSOLE')) {
261
-			return;
262
-		}
263
-		// Redirect to installer if not installed
264
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
265
-			if (OC::$CLI) {
266
-				throw new Exception('Not installed');
267
-			} else {
268
-				$url = OC::$WEBROOT . '/index.php';
269
-				header('Location: ' . $url);
270
-			}
271
-			exit();
272
-		}
273
-	}
274
-
275
-	public static function checkMaintenanceMode() {
276
-		// Allow ajax update script to execute without being stopped
277
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
278
-			// send http status 503
279
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
280
-			header('Status: 503 Service Temporarily Unavailable');
281
-			header('Retry-After: 120');
282
-
283
-			// render error page
284
-			$template = new OC_Template('', 'update.user', 'guest');
285
-			OC_Util::addScript('maintenance-check');
286
-			OC_Util::addStyle('core', 'guest');
287
-			$template->printPage();
288
-			die();
289
-		}
290
-	}
291
-
292
-	/**
293
-	 * Checks if the version requires an update and shows
294
-	 * @param bool $showTemplate Whether an update screen should get shown
295
-	 * @return bool|void
296
-	 */
297
-	public static function checkUpgrade($showTemplate = true) {
298
-		if (\OCP\Util::needUpgrade()) {
299
-			if (function_exists('opcache_reset')) {
300
-				opcache_reset();
301
-			}
302
-			$systemConfig = \OC::$server->getSystemConfig();
303
-			if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
304
-				self::printUpgradePage();
305
-				exit();
306
-			} else {
307
-				return true;
308
-			}
309
-		}
310
-		return false;
311
-	}
312
-
313
-	/**
314
-	 * Prints the upgrade page
315
-	 */
316
-	private static function printUpgradePage() {
317
-		$systemConfig = \OC::$server->getSystemConfig();
318
-
319
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
320
-		$tooBig = false;
321
-		if (!$disableWebUpdater) {
322
-			$apps = \OC::$server->getAppManager();
323
-			$tooBig = false;
324
-			if ($apps->isInstalled('user_ldap')) {
325
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
326
-
327
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
328
-					->from('ldap_user_mapping')
329
-					->execute();
330
-				$row = $result->fetch();
331
-				$result->closeCursor();
332
-
333
-				$tooBig = ($row['user_count'] > 50);
334
-			}
335
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
336
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
337
-
338
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
339
-					->from('user_saml_users')
340
-					->execute();
341
-				$row = $result->fetch();
342
-				$result->closeCursor();
343
-
344
-				$tooBig = ($row['user_count'] > 50);
345
-			}
346
-			if (!$tooBig) {
347
-				// count users
348
-				$stats = \OC::$server->getUserManager()->countUsers();
349
-				$totalUsers = array_sum($stats);
350
-				$tooBig = ($totalUsers > 50);
351
-			}
352
-		}
353
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
354
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
355
-
356
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
357
-			// send http status 503
358
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
359
-			header('Status: 503 Service Temporarily Unavailable');
360
-			header('Retry-After: 120');
361
-
362
-			// render error page
363
-			$template = new OC_Template('', 'update.use-cli', 'guest');
364
-			$template->assign('productName', 'nextcloud'); // for now
365
-			$template->assign('version', OC_Util::getVersionString());
366
-			$template->assign('tooBig', $tooBig);
367
-
368
-			$template->printPage();
369
-			die();
370
-		}
371
-
372
-		// check whether this is a core update or apps update
373
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
374
-		$currentVersion = implode('.', \OCP\Util::getVersion());
375
-
376
-		// if not a core upgrade, then it's apps upgrade
377
-		$isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
378
-
379
-		$oldTheme = $systemConfig->getValue('theme');
380
-		$systemConfig->setValue('theme', '');
381
-		OC_Util::addScript('config'); // needed for web root
382
-		OC_Util::addScript('update');
383
-
384
-		/** @var \OC\App\AppManager $appManager */
385
-		$appManager = \OC::$server->getAppManager();
386
-
387
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
388
-		$tmpl->assign('version', OC_Util::getVersionString());
389
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
390
-
391
-		// get third party apps
392
-		$ocVersion = \OCP\Util::getVersion();
393
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
394
-		$incompatibleShippedApps = [];
395
-		foreach ($incompatibleApps as $appInfo) {
396
-			if ($appManager->isShipped($appInfo['id'])) {
397
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
398
-			}
399
-		}
400
-
401
-		if (!empty($incompatibleShippedApps)) {
402
-			$l = \OC::$server->getL10N('core');
403
-			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
404
-			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);
405
-		}
406
-
407
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
408
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
409
-		$tmpl->assign('productName', 'Nextcloud'); // for now
410
-		$tmpl->assign('oldTheme', $oldTheme);
411
-		$tmpl->printPage();
412
-	}
413
-
414
-	public static function initSession() {
415
-		// prevents javascript from accessing php session cookies
416
-		ini_set('session.cookie_httponly', true);
417
-
418
-		// set the cookie path to the Nextcloud directory
419
-		$cookie_path = OC::$WEBROOT ? : '/';
420
-		ini_set('session.cookie_path', $cookie_path);
421
-
422
-		// Let the session name be changed in the initSession Hook
423
-		$sessionName = OC_Util::getInstanceId();
424
-
425
-		try {
426
-			// Allow session apps to create a custom session object
427
-			$useCustomSession = false;
428
-			$session = self::$server->getSession();
429
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
430
-			if (!$useCustomSession) {
431
-				// set the session name to the instance id - which is unique
432
-				$session = new \OC\Session\Internal($sessionName);
433
-			}
434
-
435
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
436
-			$session = $cryptoWrapper->wrapSession($session);
437
-			self::$server->setSession($session);
438
-
439
-			// if session can't be started break with http 500 error
440
-		} catch (Exception $e) {
441
-			\OCP\Util::logException('base', $e);
442
-			//show the user a detailed error page
443
-			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
444
-			OC_Template::printExceptionErrorPage($e);
445
-			die();
446
-		}
447
-
448
-		$sessionLifeTime = self::getSessionLifeTime();
449
-
450
-		// session timeout
451
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
452
-			if (isset($_COOKIE[session_name()])) {
453
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
454
-			}
455
-			\OC::$server->getUserSession()->logout();
456
-		}
457
-
458
-		$session->set('LAST_ACTIVITY', time());
459
-	}
460
-
461
-	/**
462
-	 * @return string
463
-	 */
464
-	private static function getSessionLifeTime() {
465
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
466
-	}
467
-
468
-	public static function loadAppClassPaths() {
469
-		foreach (OC_App::getEnabledApps() as $app) {
470
-			$appPath = OC_App::getAppPath($app);
471
-			if ($appPath === false) {
472
-				continue;
473
-			}
474
-
475
-			$file = $appPath . '/appinfo/classpath.php';
476
-			if (file_exists($file)) {
477
-				require_once $file;
478
-			}
479
-		}
480
-	}
481
-
482
-	/**
483
-	 * Try to set some values to the required Nextcloud default
484
-	 */
485
-	public static function setRequiredIniValues() {
486
-		@ini_set('default_charset', 'UTF-8');
487
-		@ini_set('gd.jpeg_ignore_warning', 1);
488
-	}
489
-
490
-	/**
491
-	 * Send the same site cookies
492
-	 */
493
-	private static function sendSameSiteCookies() {
494
-		$cookieParams = session_get_cookie_params();
495
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
496
-		$policies = [
497
-			'lax',
498
-			'strict',
499
-		];
500
-
501
-		// Append __Host to the cookie if it meets the requirements
502
-		$cookiePrefix = '';
503
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
504
-			$cookiePrefix = '__Host-';
505
-		}
506
-
507
-		foreach($policies as $policy) {
508
-			header(
509
-				sprintf(
510
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
511
-					$cookiePrefix,
512
-					$policy,
513
-					$cookieParams['path'],
514
-					$policy
515
-				),
516
-				false
517
-			);
518
-		}
519
-	}
520
-
521
-	/**
522
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
523
-	 * be set in every request if cookies are sent to add a second level of
524
-	 * defense against CSRF.
525
-	 *
526
-	 * If the cookie is not sent this will set the cookie and reload the page.
527
-	 * We use an additional cookie since we want to protect logout CSRF and
528
-	 * also we can't directly interfere with PHP's session mechanism.
529
-	 */
530
-	private static function performSameSiteCookieProtection() {
531
-		$request = \OC::$server->getRequest();
532
-
533
-		// Some user agents are notorious and don't really properly follow HTTP
534
-		// specifications. For those, have an automated opt-out. Since the protection
535
-		// for remote.php is applied in base.php as starting point we need to opt out
536
-		// here.
537
-		$incompatibleUserAgents = [
538
-			// OS X Finder
539
-			'/^WebDAVFS/',
540
-		];
541
-		if($request->isUserAgent($incompatibleUserAgents)) {
542
-			return;
543
-		}
544
-
545
-		if(count($_COOKIE) > 0) {
546
-			$requestUri = $request->getScriptName();
547
-			$processingScript = explode('/', $requestUri);
548
-			$processingScript = $processingScript[count($processingScript)-1];
549
-
550
-			// index.php routes are handled in the middleware
551
-			if($processingScript === 'index.php') {
552
-				return;
553
-			}
554
-
555
-			// All other endpoints require the lax and the strict cookie
556
-			if(!$request->passesStrictCookieCheck()) {
557
-				self::sendSameSiteCookies();
558
-				// Debug mode gets access to the resources without strict cookie
559
-				// due to the fact that the SabreDAV browser also lives there.
560
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
561
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
562
-					exit();
563
-				}
564
-			}
565
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
566
-			self::sendSameSiteCookies();
567
-		}
568
-	}
569
-
570
-	public static function init() {
571
-		// calculate the root directories
572
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
573
-
574
-		// register autoloader
575
-		$loaderStart = microtime(true);
576
-		require_once __DIR__ . '/autoloader.php';
577
-		self::$loader = new \OC\Autoloader([
578
-			OC::$SERVERROOT . '/lib/private/legacy',
579
-		]);
580
-		if (defined('PHPUNIT_RUN')) {
581
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
582
-		}
583
-		spl_autoload_register(array(self::$loader, 'load'));
584
-		$loaderEnd = microtime(true);
585
-
586
-		self::$CLI = (php_sapi_name() == 'cli');
587
-
588
-		// Add default composer PSR-4 autoloader
589
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
590
-
591
-		try {
592
-			self::initPaths();
593
-			// setup 3rdparty autoloader
594
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
595
-			if (!file_exists($vendorAutoLoad)) {
596
-				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".');
597
-			}
598
-			require_once $vendorAutoLoad;
599
-
600
-		} catch (\RuntimeException $e) {
601
-			if (!self::$CLI) {
602
-				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
603
-				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
604
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
605
-			}
606
-			// we can't use the template error page here, because this needs the
607
-			// DI container which isn't available yet
608
-			print($e->getMessage());
609
-			exit();
610
-		}
611
-
612
-		// setup the basic server
613
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
614
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
615
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
616
-
617
-		// Don't display errors and log them
618
-		error_reporting(E_ALL | E_STRICT);
619
-		@ini_set('display_errors', 0);
620
-		@ini_set('log_errors', 1);
621
-
622
-		if(!date_default_timezone_set('UTC')) {
623
-			throw new \RuntimeException('Could not set timezone to UTC');
624
-		};
625
-
626
-		//try to configure php to enable big file uploads.
627
-		//this doesn´t work always depending on the webserver and php configuration.
628
-		//Let´s try to overwrite some defaults anyway
629
-
630
-		//try to set the maximum execution time to 60min
631
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
632
-			@set_time_limit(3600);
633
-		}
634
-		@ini_set('max_execution_time', 3600);
635
-		@ini_set('max_input_time', 3600);
636
-
637
-		//try to set the maximum filesize to 10G
638
-		@ini_set('upload_max_filesize', '10G');
639
-		@ini_set('post_max_size', '10G');
640
-		@ini_set('file_uploads', '50');
641
-
642
-		self::setRequiredIniValues();
643
-		self::handleAuthHeaders();
644
-		self::registerAutoloaderCache();
645
-
646
-		// initialize intl fallback is necessary
647
-		\Patchwork\Utf8\Bootup::initIntl();
648
-		OC_Util::isSetLocaleWorking();
649
-
650
-		if (!defined('PHPUNIT_RUN')) {
651
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
652
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
653
-			OC\Log\ErrorHandler::register($debug);
654
-		}
655
-
656
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
657
-		OC_App::loadApps(array('session'));
658
-		if (!self::$CLI) {
659
-			self::initSession();
660
-		}
661
-		\OC::$server->getEventLogger()->end('init_session');
662
-		self::checkConfig();
663
-		self::checkInstalled();
664
-
665
-		OC_Response::addSecurityHeaders();
666
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
667
-			ini_set('session.cookie_secure', true);
668
-		}
669
-
670
-		self::performSameSiteCookieProtection();
671
-
672
-		if (!defined('OC_CONSOLE')) {
673
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
674
-			if (count($errors) > 0) {
675
-				if (self::$CLI) {
676
-					// Convert l10n string into regular string for usage in database
677
-					$staticErrors = [];
678
-					foreach ($errors as $error) {
679
-						echo $error['error'] . "\n";
680
-						echo $error['hint'] . "\n\n";
681
-						$staticErrors[] = [
682
-							'error' => (string)$error['error'],
683
-							'hint' => (string)$error['hint'],
684
-						];
685
-					}
686
-
687
-					try {
688
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
689
-					} catch (\Exception $e) {
690
-						echo('Writing to database failed');
691
-					}
692
-					exit(1);
693
-				} else {
694
-					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
695
-					OC_Util::addStyle('guest');
696
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
697
-					exit;
698
-				}
699
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
700
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
701
-			}
702
-		}
703
-		//try to set the session lifetime
704
-		$sessionLifeTime = self::getSessionLifeTime();
705
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
706
-
707
-		$systemConfig = \OC::$server->getSystemConfig();
708
-
709
-		// User and Groups
710
-		if (!$systemConfig->getValue("installed", false)) {
711
-			self::$server->getSession()->set('user_id', '');
712
-		}
713
-
714
-		OC_User::useBackend(new \OC\User\Database());
715
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
716
-
717
-		// Subscribe to the hook
718
-		\OCP\Util::connectHook(
719
-			'\OCA\Files_Sharing\API\Server2Server',
720
-			'preLoginNameUsedAsUserName',
721
-			'\OC\User\Database',
722
-			'preLoginNameUsedAsUserName'
723
-		);
724
-
725
-		//setup extra user backends
726
-		if (!self::checkUpgrade(false)) {
727
-			OC_User::setupBackends();
728
-		} else {
729
-			// Run upgrades in incognito mode
730
-			OC_User::setIncognitoMode(true);
731
-		}
732
-
733
-		self::registerCleanupHooks();
734
-		self::registerFilesystemHooks();
735
-		self::registerShareHooks();
736
-		self::registerEncryptionWrapper();
737
-		self::registerEncryptionHooks();
738
-		self::registerAccountHooks();
739
-		self::registerSettingsHooks();
740
-
741
-		$settings = new \OC\Settings\Application();
742
-		$settings->register();
743
-
744
-		//make sure temporary files are cleaned up
745
-		$tmpManager = \OC::$server->getTempManager();
746
-		register_shutdown_function(array($tmpManager, 'clean'));
747
-		$lockProvider = \OC::$server->getLockingProvider();
748
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
749
-
750
-		// Check whether the sample configuration has been copied
751
-		if($systemConfig->getValue('copied_sample_config', false)) {
752
-			$l = \OC::$server->getL10N('lib');
753
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
754
-			header('Status: 503 Service Temporarily Unavailable');
755
-			OC_Template::printErrorPage(
756
-				$l->t('Sample configuration detected'),
757
-				$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')
758
-			);
759
-			return;
760
-		}
761
-
762
-		$request = \OC::$server->getRequest();
763
-		$host = $request->getInsecureServerHost();
764
-		/**
765
-		 * if the host passed in headers isn't trusted
766
-		 * FIXME: Should not be in here at all :see_no_evil:
767
-		 */
768
-		if (!OC::$CLI
769
-			// overwritehost is always trusted, workaround to not have to make
770
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
771
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
772
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
773
-			&& self::$server->getConfig()->getSystemValue('installed', false)
774
-		) {
775
-			// Allow access to CSS resources
776
-			$isScssRequest = false;
777
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
778
-				$isScssRequest = true;
779
-			}
780
-
781
-			if (!$isScssRequest) {
782
-				header('HTTP/1.1 400 Bad Request');
783
-				header('Status: 400 Bad Request');
784
-
785
-				\OC::$server->getLogger()->warning(
786
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
787
-					[
788
-						'app' => 'core',
789
-						'remoteAddress' => $request->getRemoteAddress(),
790
-						'host' => $host,
791
-					]
792
-				);
793
-
794
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
795
-				$tmpl->assign('domain', $host);
796
-				$tmpl->printPage();
797
-
798
-				exit();
799
-			}
800
-		}
801
-		\OC::$server->getEventLogger()->end('boot');
802
-	}
803
-
804
-	/**
805
-	 * register hooks for the cleanup of cache and bruteforce protection
806
-	 */
807
-	public static function registerCleanupHooks() {
808
-		//don't try to do this before we are properly setup
809
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
810
-
811
-			// NOTE: This will be replaced to use OCP
812
-			$userSession = self::$server->getUserSession();
813
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
814
-				if (!defined('PHPUNIT_RUN')) {
815
-					// reset brute force delay for this IP address and username
816
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
817
-					$request = \OC::$server->getRequest();
818
-					$throttler = \OC::$server->getBruteForceThrottler();
819
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
820
-				}
821
-
822
-				try {
823
-					$cache = new \OC\Cache\File();
824
-					$cache->gc();
825
-				} catch (\OC\ServerNotAvailableException $e) {
826
-					// not a GC exception, pass it on
827
-					throw $e;
828
-				} catch (\OC\ForbiddenException $e) {
829
-					// filesystem blocked for this request, ignore
830
-				} catch (\Exception $e) {
831
-					// a GC exception should not prevent users from using OC,
832
-					// so log the exception
833
-					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
834
-				}
835
-			});
836
-		}
837
-	}
838
-
839
-	public static function registerSettingsHooks() {
840
-		$dispatcher = \OC::$server->getEventDispatcher();
841
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
842
-			/** @var \OCP\App\ManagerEvent $event */
843
-			\OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
844
-		});
845
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
846
-			/** @var \OCP\App\ManagerEvent $event */
847
-			$jobList = \OC::$server->getJobList();
848
-			$job = 'OC\\Settings\\RemoveOrphaned';
849
-			if(!($jobList->has($job, null))) {
850
-				$jobList->add($job);
851
-			}
852
-		});
853
-	}
854
-
855
-	private static function registerEncryptionWrapper() {
856
-		$manager = self::$server->getEncryptionManager();
857
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
858
-	}
859
-
860
-	private static function registerEncryptionHooks() {
861
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
862
-		if ($enabled) {
863
-			\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
864
-			\OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
865
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
866
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
867
-		}
868
-	}
869
-
870
-	private static function registerAccountHooks() {
871
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
872
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
873
-	}
874
-
875
-	/**
876
-	 * register hooks for the filesystem
877
-	 */
878
-	public static function registerFilesystemHooks() {
879
-		// Check for blacklisted files
880
-		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
881
-		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
882
-	}
883
-
884
-	/**
885
-	 * register hooks for sharing
886
-	 */
887
-	public static function registerShareHooks() {
888
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
889
-			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
890
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
891
-			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
892
-		}
893
-	}
894
-
895
-	protected static function registerAutoloaderCache() {
896
-		// The class loader takes an optional low-latency cache, which MUST be
897
-		// namespaced. The instanceid is used for namespacing, but might be
898
-		// unavailable at this point. Furthermore, it might not be possible to
899
-		// generate an instanceid via \OC_Util::getInstanceId() because the
900
-		// config file may not be writable. As such, we only register a class
901
-		// loader cache if instanceid is available without trying to create one.
902
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
903
-		if ($instanceId) {
904
-			try {
905
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
906
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
907
-			} catch (\Exception $ex) {
908
-			}
909
-		}
910
-	}
911
-
912
-	/**
913
-	 * Handle the request
914
-	 */
915
-	public static function handleRequest() {
916
-
917
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
918
-		$systemConfig = \OC::$server->getSystemConfig();
919
-		// load all the classpaths from the enabled apps so they are available
920
-		// in the routing files of each app
921
-		OC::loadAppClassPaths();
922
-
923
-		// Check if Nextcloud is installed or in maintenance (update) mode
924
-		if (!$systemConfig->getValue('installed', false)) {
925
-			\OC::$server->getSession()->clear();
926
-			$setupHelper = new OC\Setup(\OC::$server->getSystemConfig(), \OC::$server->getIniWrapper(),
927
-				\OC::$server->getL10N('lib'), \OC::$server->query(\OCP\Defaults::class), \OC::$server->getLogger(),
928
-				\OC::$server->getSecureRandom());
929
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
930
-			$controller->run($_POST);
931
-			exit();
932
-		}
933
-
934
-		$request = \OC::$server->getRequest();
935
-		$requestPath = $request->getRawPathInfo();
936
-		if ($requestPath === '/heartbeat') {
937
-			return;
938
-		}
939
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
940
-			self::checkMaintenanceMode();
941
-			self::checkUpgrade();
942
-		}
943
-
944
-		// emergency app disabling
945
-		if ($requestPath === '/disableapp'
946
-			&& $request->getMethod() === 'POST'
947
-			&& ((array)$request->getParam('appid')) !== ''
948
-		) {
949
-			\OCP\JSON::callCheck();
950
-			\OCP\JSON::checkAdminUser();
951
-			$appIds = (array)$request->getParam('appid');
952
-			foreach($appIds as $appId) {
953
-				$appId = \OC_App::cleanAppId($appId);
954
-				\OC_App::disable($appId);
955
-			}
956
-			\OC_JSON::success();
957
-			exit();
958
-		}
959
-
960
-		// Always load authentication apps
961
-		OC_App::loadApps(['authentication']);
962
-
963
-		// Load minimum set of apps
964
-		if (!self::checkUpgrade(false)
965
-			&& !$systemConfig->getValue('maintenance', false)) {
966
-			// For logged-in users: Load everything
967
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
968
-				OC_App::loadApps();
969
-			} else {
970
-				// For guests: Load only filesystem and logging
971
-				OC_App::loadApps(array('filesystem', 'logging'));
972
-				self::handleLogin($request);
973
-			}
974
-		}
975
-
976
-		if (!self::$CLI) {
977
-			try {
978
-				if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
979
-					OC_App::loadApps(array('filesystem', 'logging'));
980
-					OC_App::loadApps();
981
-				}
982
-				OC_Util::setupFS();
983
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
984
-				return;
985
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
986
-				//header('HTTP/1.0 404 Not Found');
987
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
988
-				OC_Response::setStatus(405);
989
-				return;
990
-			}
991
-		}
992
-
993
-		// Handle WebDAV
994
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
995
-			// not allowed any more to prevent people
996
-			// mounting this root directly.
997
-			// Users need to mount remote.php/webdav instead.
998
-			header('HTTP/1.1 405 Method Not Allowed');
999
-			header('Status: 405 Method Not Allowed');
1000
-			return;
1001
-		}
1002
-
1003
-		// Someone is logged in
1004
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1005
-			OC_App::loadApps();
1006
-			OC_User::setupBackends();
1007
-			OC_Util::setupFS();
1008
-			// FIXME
1009
-			// Redirect to default application
1010
-			OC_Util::redirectToDefaultPage();
1011
-		} else {
1012
-			// Not handled and not logged in
1013
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1014
-		}
1015
-	}
1016
-
1017
-	/**
1018
-	 * Check login: apache auth, auth token, basic auth
1019
-	 *
1020
-	 * @param OCP\IRequest $request
1021
-	 * @return boolean
1022
-	 */
1023
-	static function handleLogin(OCP\IRequest $request) {
1024
-		$userSession = self::$server->getUserSession();
1025
-		if (OC_User::handleApacheAuth()) {
1026
-			return true;
1027
-		}
1028
-		if ($userSession->tryTokenLogin($request)) {
1029
-			return true;
1030
-		}
1031
-		if (isset($_COOKIE['nc_username'])
1032
-			&& isset($_COOKIE['nc_token'])
1033
-			&& isset($_COOKIE['nc_session_id'])
1034
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1035
-			return true;
1036
-		}
1037
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1038
-			return true;
1039
-		}
1040
-		return false;
1041
-	}
1042
-
1043
-	protected static function handleAuthHeaders() {
1044
-		//copy http auth headers for apache+php-fcgid work around
1045
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1046
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1047
-		}
1048
-
1049
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1050
-		$vars = array(
1051
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1052
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1053
-		);
1054
-		foreach ($vars as $var) {
1055
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1056
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1057
-				$_SERVER['PHP_AUTH_USER'] = $name;
1058
-				$_SERVER['PHP_AUTH_PW'] = $password;
1059
-				break;
1060
-			}
1061
-		}
1062
-	}
65
+    /**
66
+     * Associative array for autoloading. classname => filename
67
+     */
68
+    public static $CLASSPATH = array();
69
+    /**
70
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
71
+     */
72
+    public static $SERVERROOT = '';
73
+    /**
74
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
75
+     */
76
+    private static $SUBURI = '';
77
+    /**
78
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
79
+     */
80
+    public static $WEBROOT = '';
81
+    /**
82
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
83
+     * web path in 'url'
84
+     */
85
+    public static $APPSROOTS = array();
86
+
87
+    /**
88
+     * @var string
89
+     */
90
+    public static $configDir;
91
+
92
+    /**
93
+     * requested app
94
+     */
95
+    public static $REQUESTEDAPP = '';
96
+
97
+    /**
98
+     * check if Nextcloud runs in cli mode
99
+     */
100
+    public static $CLI = false;
101
+
102
+    /**
103
+     * @var \OC\Autoloader $loader
104
+     */
105
+    public static $loader = null;
106
+
107
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
108
+    public static $composerAutoloader = null;
109
+
110
+    /**
111
+     * @var \OC\Server
112
+     */
113
+    public static $server = null;
114
+
115
+    /**
116
+     * @var \OC\Config
117
+     */
118
+    private static $config = null;
119
+
120
+    /**
121
+     * @throws \RuntimeException when the 3rdparty directory is missing or
122
+     * the app path list is empty or contains an invalid path
123
+     */
124
+    public static function initPaths() {
125
+        if(defined('PHPUNIT_CONFIG_DIR')) {
126
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
127
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
128
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
129
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
+            self::$configDir = rtrim($dir, '/') . '/';
131
+        } else {
132
+            self::$configDir = OC::$SERVERROOT . '/config/';
133
+        }
134
+        self::$config = new \OC\Config(self::$configDir);
135
+
136
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
137
+        /**
138
+         * FIXME: The following lines are required because we can't yet instantiate
139
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
140
+         */
141
+        $params = [
142
+            'server' => [
143
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
144
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
145
+            ],
146
+        ];
147
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
148
+        $scriptName = $fakeRequest->getScriptName();
149
+        if (substr($scriptName, -1) == '/') {
150
+            $scriptName .= 'index.php';
151
+            //make sure suburi follows the same rules as scriptName
152
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
153
+                if (substr(OC::$SUBURI, -1) != '/') {
154
+                    OC::$SUBURI = OC::$SUBURI . '/';
155
+                }
156
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
157
+            }
158
+        }
159
+
160
+
161
+        if (OC::$CLI) {
162
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
163
+        } else {
164
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
165
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
166
+
167
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
168
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
169
+                }
170
+            } else {
171
+                // The scriptName is not ending with OC::$SUBURI
172
+                // This most likely means that we are calling from CLI.
173
+                // However some cron jobs still need to generate
174
+                // a web URL, so we use overwritewebroot as a fallback.
175
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
176
+            }
177
+
178
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
179
+            // slash which is required by URL generation.
180
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
181
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
182
+                header('Location: '.\OC::$WEBROOT.'/');
183
+                exit();
184
+            }
185
+        }
186
+
187
+        // search the apps folder
188
+        $config_paths = self::$config->getValue('apps_paths', array());
189
+        if (!empty($config_paths)) {
190
+            foreach ($config_paths as $paths) {
191
+                if (isset($paths['url']) && isset($paths['path'])) {
192
+                    $paths['url'] = rtrim($paths['url'], '/');
193
+                    $paths['path'] = rtrim($paths['path'], '/');
194
+                    OC::$APPSROOTS[] = $paths;
195
+                }
196
+            }
197
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
198
+            OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
199
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
200
+            OC::$APPSROOTS[] = array(
201
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
202
+                'url' => '/apps',
203
+                'writable' => true
204
+            );
205
+        }
206
+
207
+        if (empty(OC::$APPSROOTS)) {
208
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
209
+                . ' or the folder above. You can also configure the location in the config.php file.');
210
+        }
211
+        $paths = array();
212
+        foreach (OC::$APPSROOTS as $path) {
213
+            $paths[] = $path['path'];
214
+            if (!is_dir($path['path'])) {
215
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
216
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
217
+                    . ' config.php file.', $path['path']));
218
+            }
219
+        }
220
+
221
+        // set the right include path
222
+        set_include_path(
223
+            implode(PATH_SEPARATOR, $paths)
224
+        );
225
+    }
226
+
227
+    public static function checkConfig() {
228
+        $l = \OC::$server->getL10N('lib');
229
+
230
+        // Create config if it does not already exist
231
+        $configFilePath = self::$configDir .'/config.php';
232
+        if(!file_exists($configFilePath)) {
233
+            @touch($configFilePath);
234
+        }
235
+
236
+        // Check if config is writable
237
+        $configFileWritable = is_writable($configFilePath);
238
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
239
+            || !$configFileWritable && self::checkUpgrade(false)) {
240
+
241
+            $urlGenerator = \OC::$server->getURLGenerator();
242
+
243
+            if (self::$CLI) {
244
+                echo $l->t('Cannot write into "config" directory!')."\n";
245
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246
+                echo "\n";
247
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
248
+                exit;
249
+            } else {
250
+                OC_Template::printErrorPage(
251
+                    $l->t('Cannot write into "config" directory!'),
252
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
253
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
254
+                );
255
+            }
256
+        }
257
+    }
258
+
259
+    public static function checkInstalled() {
260
+        if (defined('OC_CONSOLE')) {
261
+            return;
262
+        }
263
+        // Redirect to installer if not installed
264
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
265
+            if (OC::$CLI) {
266
+                throw new Exception('Not installed');
267
+            } else {
268
+                $url = OC::$WEBROOT . '/index.php';
269
+                header('Location: ' . $url);
270
+            }
271
+            exit();
272
+        }
273
+    }
274
+
275
+    public static function checkMaintenanceMode() {
276
+        // Allow ajax update script to execute without being stopped
277
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
278
+            // send http status 503
279
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
280
+            header('Status: 503 Service Temporarily Unavailable');
281
+            header('Retry-After: 120');
282
+
283
+            // render error page
284
+            $template = new OC_Template('', 'update.user', 'guest');
285
+            OC_Util::addScript('maintenance-check');
286
+            OC_Util::addStyle('core', 'guest');
287
+            $template->printPage();
288
+            die();
289
+        }
290
+    }
291
+
292
+    /**
293
+     * Checks if the version requires an update and shows
294
+     * @param bool $showTemplate Whether an update screen should get shown
295
+     * @return bool|void
296
+     */
297
+    public static function checkUpgrade($showTemplate = true) {
298
+        if (\OCP\Util::needUpgrade()) {
299
+            if (function_exists('opcache_reset')) {
300
+                opcache_reset();
301
+            }
302
+            $systemConfig = \OC::$server->getSystemConfig();
303
+            if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
304
+                self::printUpgradePage();
305
+                exit();
306
+            } else {
307
+                return true;
308
+            }
309
+        }
310
+        return false;
311
+    }
312
+
313
+    /**
314
+     * Prints the upgrade page
315
+     */
316
+    private static function printUpgradePage() {
317
+        $systemConfig = \OC::$server->getSystemConfig();
318
+
319
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
320
+        $tooBig = false;
321
+        if (!$disableWebUpdater) {
322
+            $apps = \OC::$server->getAppManager();
323
+            $tooBig = false;
324
+            if ($apps->isInstalled('user_ldap')) {
325
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
326
+
327
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
328
+                    ->from('ldap_user_mapping')
329
+                    ->execute();
330
+                $row = $result->fetch();
331
+                $result->closeCursor();
332
+
333
+                $tooBig = ($row['user_count'] > 50);
334
+            }
335
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
336
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
337
+
338
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
339
+                    ->from('user_saml_users')
340
+                    ->execute();
341
+                $row = $result->fetch();
342
+                $result->closeCursor();
343
+
344
+                $tooBig = ($row['user_count'] > 50);
345
+            }
346
+            if (!$tooBig) {
347
+                // count users
348
+                $stats = \OC::$server->getUserManager()->countUsers();
349
+                $totalUsers = array_sum($stats);
350
+                $tooBig = ($totalUsers > 50);
351
+            }
352
+        }
353
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
354
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
355
+
356
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
357
+            // send http status 503
358
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
359
+            header('Status: 503 Service Temporarily Unavailable');
360
+            header('Retry-After: 120');
361
+
362
+            // render error page
363
+            $template = new OC_Template('', 'update.use-cli', 'guest');
364
+            $template->assign('productName', 'nextcloud'); // for now
365
+            $template->assign('version', OC_Util::getVersionString());
366
+            $template->assign('tooBig', $tooBig);
367
+
368
+            $template->printPage();
369
+            die();
370
+        }
371
+
372
+        // check whether this is a core update or apps update
373
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
374
+        $currentVersion = implode('.', \OCP\Util::getVersion());
375
+
376
+        // if not a core upgrade, then it's apps upgrade
377
+        $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
378
+
379
+        $oldTheme = $systemConfig->getValue('theme');
380
+        $systemConfig->setValue('theme', '');
381
+        OC_Util::addScript('config'); // needed for web root
382
+        OC_Util::addScript('update');
383
+
384
+        /** @var \OC\App\AppManager $appManager */
385
+        $appManager = \OC::$server->getAppManager();
386
+
387
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
388
+        $tmpl->assign('version', OC_Util::getVersionString());
389
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
390
+
391
+        // get third party apps
392
+        $ocVersion = \OCP\Util::getVersion();
393
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
394
+        $incompatibleShippedApps = [];
395
+        foreach ($incompatibleApps as $appInfo) {
396
+            if ($appManager->isShipped($appInfo['id'])) {
397
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
398
+            }
399
+        }
400
+
401
+        if (!empty($incompatibleShippedApps)) {
402
+            $l = \OC::$server->getL10N('core');
403
+            $hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
404
+            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);
405
+        }
406
+
407
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
408
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
409
+        $tmpl->assign('productName', 'Nextcloud'); // for now
410
+        $tmpl->assign('oldTheme', $oldTheme);
411
+        $tmpl->printPage();
412
+    }
413
+
414
+    public static function initSession() {
415
+        // prevents javascript from accessing php session cookies
416
+        ini_set('session.cookie_httponly', true);
417
+
418
+        // set the cookie path to the Nextcloud directory
419
+        $cookie_path = OC::$WEBROOT ? : '/';
420
+        ini_set('session.cookie_path', $cookie_path);
421
+
422
+        // Let the session name be changed in the initSession Hook
423
+        $sessionName = OC_Util::getInstanceId();
424
+
425
+        try {
426
+            // Allow session apps to create a custom session object
427
+            $useCustomSession = false;
428
+            $session = self::$server->getSession();
429
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
430
+            if (!$useCustomSession) {
431
+                // set the session name to the instance id - which is unique
432
+                $session = new \OC\Session\Internal($sessionName);
433
+            }
434
+
435
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
436
+            $session = $cryptoWrapper->wrapSession($session);
437
+            self::$server->setSession($session);
438
+
439
+            // if session can't be started break with http 500 error
440
+        } catch (Exception $e) {
441
+            \OCP\Util::logException('base', $e);
442
+            //show the user a detailed error page
443
+            OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
444
+            OC_Template::printExceptionErrorPage($e);
445
+            die();
446
+        }
447
+
448
+        $sessionLifeTime = self::getSessionLifeTime();
449
+
450
+        // session timeout
451
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
452
+            if (isset($_COOKIE[session_name()])) {
453
+                setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
454
+            }
455
+            \OC::$server->getUserSession()->logout();
456
+        }
457
+
458
+        $session->set('LAST_ACTIVITY', time());
459
+    }
460
+
461
+    /**
462
+     * @return string
463
+     */
464
+    private static function getSessionLifeTime() {
465
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
466
+    }
467
+
468
+    public static function loadAppClassPaths() {
469
+        foreach (OC_App::getEnabledApps() as $app) {
470
+            $appPath = OC_App::getAppPath($app);
471
+            if ($appPath === false) {
472
+                continue;
473
+            }
474
+
475
+            $file = $appPath . '/appinfo/classpath.php';
476
+            if (file_exists($file)) {
477
+                require_once $file;
478
+            }
479
+        }
480
+    }
481
+
482
+    /**
483
+     * Try to set some values to the required Nextcloud default
484
+     */
485
+    public static function setRequiredIniValues() {
486
+        @ini_set('default_charset', 'UTF-8');
487
+        @ini_set('gd.jpeg_ignore_warning', 1);
488
+    }
489
+
490
+    /**
491
+     * Send the same site cookies
492
+     */
493
+    private static function sendSameSiteCookies() {
494
+        $cookieParams = session_get_cookie_params();
495
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
496
+        $policies = [
497
+            'lax',
498
+            'strict',
499
+        ];
500
+
501
+        // Append __Host to the cookie if it meets the requirements
502
+        $cookiePrefix = '';
503
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
504
+            $cookiePrefix = '__Host-';
505
+        }
506
+
507
+        foreach($policies as $policy) {
508
+            header(
509
+                sprintf(
510
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
511
+                    $cookiePrefix,
512
+                    $policy,
513
+                    $cookieParams['path'],
514
+                    $policy
515
+                ),
516
+                false
517
+            );
518
+        }
519
+    }
520
+
521
+    /**
522
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
523
+     * be set in every request if cookies are sent to add a second level of
524
+     * defense against CSRF.
525
+     *
526
+     * If the cookie is not sent this will set the cookie and reload the page.
527
+     * We use an additional cookie since we want to protect logout CSRF and
528
+     * also we can't directly interfere with PHP's session mechanism.
529
+     */
530
+    private static function performSameSiteCookieProtection() {
531
+        $request = \OC::$server->getRequest();
532
+
533
+        // Some user agents are notorious and don't really properly follow HTTP
534
+        // specifications. For those, have an automated opt-out. Since the protection
535
+        // for remote.php is applied in base.php as starting point we need to opt out
536
+        // here.
537
+        $incompatibleUserAgents = [
538
+            // OS X Finder
539
+            '/^WebDAVFS/',
540
+        ];
541
+        if($request->isUserAgent($incompatibleUserAgents)) {
542
+            return;
543
+        }
544
+
545
+        if(count($_COOKIE) > 0) {
546
+            $requestUri = $request->getScriptName();
547
+            $processingScript = explode('/', $requestUri);
548
+            $processingScript = $processingScript[count($processingScript)-1];
549
+
550
+            // index.php routes are handled in the middleware
551
+            if($processingScript === 'index.php') {
552
+                return;
553
+            }
554
+
555
+            // All other endpoints require the lax and the strict cookie
556
+            if(!$request->passesStrictCookieCheck()) {
557
+                self::sendSameSiteCookies();
558
+                // Debug mode gets access to the resources without strict cookie
559
+                // due to the fact that the SabreDAV browser also lives there.
560
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
561
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
562
+                    exit();
563
+                }
564
+            }
565
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
566
+            self::sendSameSiteCookies();
567
+        }
568
+    }
569
+
570
+    public static function init() {
571
+        // calculate the root directories
572
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
573
+
574
+        // register autoloader
575
+        $loaderStart = microtime(true);
576
+        require_once __DIR__ . '/autoloader.php';
577
+        self::$loader = new \OC\Autoloader([
578
+            OC::$SERVERROOT . '/lib/private/legacy',
579
+        ]);
580
+        if (defined('PHPUNIT_RUN')) {
581
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
582
+        }
583
+        spl_autoload_register(array(self::$loader, 'load'));
584
+        $loaderEnd = microtime(true);
585
+
586
+        self::$CLI = (php_sapi_name() == 'cli');
587
+
588
+        // Add default composer PSR-4 autoloader
589
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
590
+
591
+        try {
592
+            self::initPaths();
593
+            // setup 3rdparty autoloader
594
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
595
+            if (!file_exists($vendorAutoLoad)) {
596
+                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".');
597
+            }
598
+            require_once $vendorAutoLoad;
599
+
600
+        } catch (\RuntimeException $e) {
601
+            if (!self::$CLI) {
602
+                $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
603
+                $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
604
+                header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
605
+            }
606
+            // we can't use the template error page here, because this needs the
607
+            // DI container which isn't available yet
608
+            print($e->getMessage());
609
+            exit();
610
+        }
611
+
612
+        // setup the basic server
613
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
614
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
615
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
616
+
617
+        // Don't display errors and log them
618
+        error_reporting(E_ALL | E_STRICT);
619
+        @ini_set('display_errors', 0);
620
+        @ini_set('log_errors', 1);
621
+
622
+        if(!date_default_timezone_set('UTC')) {
623
+            throw new \RuntimeException('Could not set timezone to UTC');
624
+        };
625
+
626
+        //try to configure php to enable big file uploads.
627
+        //this doesn´t work always depending on the webserver and php configuration.
628
+        //Let´s try to overwrite some defaults anyway
629
+
630
+        //try to set the maximum execution time to 60min
631
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
632
+            @set_time_limit(3600);
633
+        }
634
+        @ini_set('max_execution_time', 3600);
635
+        @ini_set('max_input_time', 3600);
636
+
637
+        //try to set the maximum filesize to 10G
638
+        @ini_set('upload_max_filesize', '10G');
639
+        @ini_set('post_max_size', '10G');
640
+        @ini_set('file_uploads', '50');
641
+
642
+        self::setRequiredIniValues();
643
+        self::handleAuthHeaders();
644
+        self::registerAutoloaderCache();
645
+
646
+        // initialize intl fallback is necessary
647
+        \Patchwork\Utf8\Bootup::initIntl();
648
+        OC_Util::isSetLocaleWorking();
649
+
650
+        if (!defined('PHPUNIT_RUN')) {
651
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
652
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
653
+            OC\Log\ErrorHandler::register($debug);
654
+        }
655
+
656
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
657
+        OC_App::loadApps(array('session'));
658
+        if (!self::$CLI) {
659
+            self::initSession();
660
+        }
661
+        \OC::$server->getEventLogger()->end('init_session');
662
+        self::checkConfig();
663
+        self::checkInstalled();
664
+
665
+        OC_Response::addSecurityHeaders();
666
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
667
+            ini_set('session.cookie_secure', true);
668
+        }
669
+
670
+        self::performSameSiteCookieProtection();
671
+
672
+        if (!defined('OC_CONSOLE')) {
673
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
674
+            if (count($errors) > 0) {
675
+                if (self::$CLI) {
676
+                    // Convert l10n string into regular string for usage in database
677
+                    $staticErrors = [];
678
+                    foreach ($errors as $error) {
679
+                        echo $error['error'] . "\n";
680
+                        echo $error['hint'] . "\n\n";
681
+                        $staticErrors[] = [
682
+                            'error' => (string)$error['error'],
683
+                            'hint' => (string)$error['hint'],
684
+                        ];
685
+                    }
686
+
687
+                    try {
688
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
689
+                    } catch (\Exception $e) {
690
+                        echo('Writing to database failed');
691
+                    }
692
+                    exit(1);
693
+                } else {
694
+                    OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
695
+                    OC_Util::addStyle('guest');
696
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
697
+                    exit;
698
+                }
699
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
700
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
701
+            }
702
+        }
703
+        //try to set the session lifetime
704
+        $sessionLifeTime = self::getSessionLifeTime();
705
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
706
+
707
+        $systemConfig = \OC::$server->getSystemConfig();
708
+
709
+        // User and Groups
710
+        if (!$systemConfig->getValue("installed", false)) {
711
+            self::$server->getSession()->set('user_id', '');
712
+        }
713
+
714
+        OC_User::useBackend(new \OC\User\Database());
715
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
716
+
717
+        // Subscribe to the hook
718
+        \OCP\Util::connectHook(
719
+            '\OCA\Files_Sharing\API\Server2Server',
720
+            'preLoginNameUsedAsUserName',
721
+            '\OC\User\Database',
722
+            'preLoginNameUsedAsUserName'
723
+        );
724
+
725
+        //setup extra user backends
726
+        if (!self::checkUpgrade(false)) {
727
+            OC_User::setupBackends();
728
+        } else {
729
+            // Run upgrades in incognito mode
730
+            OC_User::setIncognitoMode(true);
731
+        }
732
+
733
+        self::registerCleanupHooks();
734
+        self::registerFilesystemHooks();
735
+        self::registerShareHooks();
736
+        self::registerEncryptionWrapper();
737
+        self::registerEncryptionHooks();
738
+        self::registerAccountHooks();
739
+        self::registerSettingsHooks();
740
+
741
+        $settings = new \OC\Settings\Application();
742
+        $settings->register();
743
+
744
+        //make sure temporary files are cleaned up
745
+        $tmpManager = \OC::$server->getTempManager();
746
+        register_shutdown_function(array($tmpManager, 'clean'));
747
+        $lockProvider = \OC::$server->getLockingProvider();
748
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
749
+
750
+        // Check whether the sample configuration has been copied
751
+        if($systemConfig->getValue('copied_sample_config', false)) {
752
+            $l = \OC::$server->getL10N('lib');
753
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
754
+            header('Status: 503 Service Temporarily Unavailable');
755
+            OC_Template::printErrorPage(
756
+                $l->t('Sample configuration detected'),
757
+                $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')
758
+            );
759
+            return;
760
+        }
761
+
762
+        $request = \OC::$server->getRequest();
763
+        $host = $request->getInsecureServerHost();
764
+        /**
765
+         * if the host passed in headers isn't trusted
766
+         * FIXME: Should not be in here at all :see_no_evil:
767
+         */
768
+        if (!OC::$CLI
769
+            // overwritehost is always trusted, workaround to not have to make
770
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
771
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
772
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
773
+            && self::$server->getConfig()->getSystemValue('installed', false)
774
+        ) {
775
+            // Allow access to CSS resources
776
+            $isScssRequest = false;
777
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
778
+                $isScssRequest = true;
779
+            }
780
+
781
+            if (!$isScssRequest) {
782
+                header('HTTP/1.1 400 Bad Request');
783
+                header('Status: 400 Bad Request');
784
+
785
+                \OC::$server->getLogger()->warning(
786
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
787
+                    [
788
+                        'app' => 'core',
789
+                        'remoteAddress' => $request->getRemoteAddress(),
790
+                        'host' => $host,
791
+                    ]
792
+                );
793
+
794
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
795
+                $tmpl->assign('domain', $host);
796
+                $tmpl->printPage();
797
+
798
+                exit();
799
+            }
800
+        }
801
+        \OC::$server->getEventLogger()->end('boot');
802
+    }
803
+
804
+    /**
805
+     * register hooks for the cleanup of cache and bruteforce protection
806
+     */
807
+    public static function registerCleanupHooks() {
808
+        //don't try to do this before we are properly setup
809
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
810
+
811
+            // NOTE: This will be replaced to use OCP
812
+            $userSession = self::$server->getUserSession();
813
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
814
+                if (!defined('PHPUNIT_RUN')) {
815
+                    // reset brute force delay for this IP address and username
816
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
817
+                    $request = \OC::$server->getRequest();
818
+                    $throttler = \OC::$server->getBruteForceThrottler();
819
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
820
+                }
821
+
822
+                try {
823
+                    $cache = new \OC\Cache\File();
824
+                    $cache->gc();
825
+                } catch (\OC\ServerNotAvailableException $e) {
826
+                    // not a GC exception, pass it on
827
+                    throw $e;
828
+                } catch (\OC\ForbiddenException $e) {
829
+                    // filesystem blocked for this request, ignore
830
+                } catch (\Exception $e) {
831
+                    // a GC exception should not prevent users from using OC,
832
+                    // so log the exception
833
+                    \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
834
+                }
835
+            });
836
+        }
837
+    }
838
+
839
+    public static function registerSettingsHooks() {
840
+        $dispatcher = \OC::$server->getEventDispatcher();
841
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
842
+            /** @var \OCP\App\ManagerEvent $event */
843
+            \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
844
+        });
845
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
846
+            /** @var \OCP\App\ManagerEvent $event */
847
+            $jobList = \OC::$server->getJobList();
848
+            $job = 'OC\\Settings\\RemoveOrphaned';
849
+            if(!($jobList->has($job, null))) {
850
+                $jobList->add($job);
851
+            }
852
+        });
853
+    }
854
+
855
+    private static function registerEncryptionWrapper() {
856
+        $manager = self::$server->getEncryptionManager();
857
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
858
+    }
859
+
860
+    private static function registerEncryptionHooks() {
861
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
862
+        if ($enabled) {
863
+            \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
864
+            \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
865
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
866
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
867
+        }
868
+    }
869
+
870
+    private static function registerAccountHooks() {
871
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
872
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
873
+    }
874
+
875
+    /**
876
+     * register hooks for the filesystem
877
+     */
878
+    public static function registerFilesystemHooks() {
879
+        // Check for blacklisted files
880
+        OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
881
+        OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
882
+    }
883
+
884
+    /**
885
+     * register hooks for sharing
886
+     */
887
+    public static function registerShareHooks() {
888
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
889
+            OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
890
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
891
+            OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
892
+        }
893
+    }
894
+
895
+    protected static function registerAutoloaderCache() {
896
+        // The class loader takes an optional low-latency cache, which MUST be
897
+        // namespaced. The instanceid is used for namespacing, but might be
898
+        // unavailable at this point. Furthermore, it might not be possible to
899
+        // generate an instanceid via \OC_Util::getInstanceId() because the
900
+        // config file may not be writable. As such, we only register a class
901
+        // loader cache if instanceid is available without trying to create one.
902
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
903
+        if ($instanceId) {
904
+            try {
905
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
906
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
907
+            } catch (\Exception $ex) {
908
+            }
909
+        }
910
+    }
911
+
912
+    /**
913
+     * Handle the request
914
+     */
915
+    public static function handleRequest() {
916
+
917
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
918
+        $systemConfig = \OC::$server->getSystemConfig();
919
+        // load all the classpaths from the enabled apps so they are available
920
+        // in the routing files of each app
921
+        OC::loadAppClassPaths();
922
+
923
+        // Check if Nextcloud is installed or in maintenance (update) mode
924
+        if (!$systemConfig->getValue('installed', false)) {
925
+            \OC::$server->getSession()->clear();
926
+            $setupHelper = new OC\Setup(\OC::$server->getSystemConfig(), \OC::$server->getIniWrapper(),
927
+                \OC::$server->getL10N('lib'), \OC::$server->query(\OCP\Defaults::class), \OC::$server->getLogger(),
928
+                \OC::$server->getSecureRandom());
929
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
930
+            $controller->run($_POST);
931
+            exit();
932
+        }
933
+
934
+        $request = \OC::$server->getRequest();
935
+        $requestPath = $request->getRawPathInfo();
936
+        if ($requestPath === '/heartbeat') {
937
+            return;
938
+        }
939
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
940
+            self::checkMaintenanceMode();
941
+            self::checkUpgrade();
942
+        }
943
+
944
+        // emergency app disabling
945
+        if ($requestPath === '/disableapp'
946
+            && $request->getMethod() === 'POST'
947
+            && ((array)$request->getParam('appid')) !== ''
948
+        ) {
949
+            \OCP\JSON::callCheck();
950
+            \OCP\JSON::checkAdminUser();
951
+            $appIds = (array)$request->getParam('appid');
952
+            foreach($appIds as $appId) {
953
+                $appId = \OC_App::cleanAppId($appId);
954
+                \OC_App::disable($appId);
955
+            }
956
+            \OC_JSON::success();
957
+            exit();
958
+        }
959
+
960
+        // Always load authentication apps
961
+        OC_App::loadApps(['authentication']);
962
+
963
+        // Load minimum set of apps
964
+        if (!self::checkUpgrade(false)
965
+            && !$systemConfig->getValue('maintenance', false)) {
966
+            // For logged-in users: Load everything
967
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
968
+                OC_App::loadApps();
969
+            } else {
970
+                // For guests: Load only filesystem and logging
971
+                OC_App::loadApps(array('filesystem', 'logging'));
972
+                self::handleLogin($request);
973
+            }
974
+        }
975
+
976
+        if (!self::$CLI) {
977
+            try {
978
+                if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
979
+                    OC_App::loadApps(array('filesystem', 'logging'));
980
+                    OC_App::loadApps();
981
+                }
982
+                OC_Util::setupFS();
983
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
984
+                return;
985
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
986
+                //header('HTTP/1.0 404 Not Found');
987
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
988
+                OC_Response::setStatus(405);
989
+                return;
990
+            }
991
+        }
992
+
993
+        // Handle WebDAV
994
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
995
+            // not allowed any more to prevent people
996
+            // mounting this root directly.
997
+            // Users need to mount remote.php/webdav instead.
998
+            header('HTTP/1.1 405 Method Not Allowed');
999
+            header('Status: 405 Method Not Allowed');
1000
+            return;
1001
+        }
1002
+
1003
+        // Someone is logged in
1004
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1005
+            OC_App::loadApps();
1006
+            OC_User::setupBackends();
1007
+            OC_Util::setupFS();
1008
+            // FIXME
1009
+            // Redirect to default application
1010
+            OC_Util::redirectToDefaultPage();
1011
+        } else {
1012
+            // Not handled and not logged in
1013
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1014
+        }
1015
+    }
1016
+
1017
+    /**
1018
+     * Check login: apache auth, auth token, basic auth
1019
+     *
1020
+     * @param OCP\IRequest $request
1021
+     * @return boolean
1022
+     */
1023
+    static function handleLogin(OCP\IRequest $request) {
1024
+        $userSession = self::$server->getUserSession();
1025
+        if (OC_User::handleApacheAuth()) {
1026
+            return true;
1027
+        }
1028
+        if ($userSession->tryTokenLogin($request)) {
1029
+            return true;
1030
+        }
1031
+        if (isset($_COOKIE['nc_username'])
1032
+            && isset($_COOKIE['nc_token'])
1033
+            && isset($_COOKIE['nc_session_id'])
1034
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1035
+            return true;
1036
+        }
1037
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1038
+            return true;
1039
+        }
1040
+        return false;
1041
+    }
1042
+
1043
+    protected static function handleAuthHeaders() {
1044
+        //copy http auth headers for apache+php-fcgid work around
1045
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1046
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1047
+        }
1048
+
1049
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1050
+        $vars = array(
1051
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1052
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1053
+        );
1054
+        foreach ($vars as $var) {
1055
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1056
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1057
+                $_SERVER['PHP_AUTH_USER'] = $name;
1058
+                $_SERVER['PHP_AUTH_PW'] = $password;
1059
+                break;
1060
+            }
1061
+        }
1062
+    }
1063 1063
 }
1064 1064
 
1065 1065
 OC::init();
Please login to merge, or discard this patch.
Spacing   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -122,14 +122,14 @@  discard block
 block discarded – undo
122 122
 	 * the app path list is empty or contains an invalid path
123 123
 	 */
124 124
 	public static function initPaths() {
125
-		if(defined('PHPUNIT_CONFIG_DIR')) {
126
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
127
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
128
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
129
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
-			self::$configDir = rtrim($dir, '/') . '/';
125
+		if (defined('PHPUNIT_CONFIG_DIR')) {
126
+			self::$configDir = OC::$SERVERROOT.'/'.PHPUNIT_CONFIG_DIR.'/';
127
+		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT.'/tests/config/')) {
128
+			self::$configDir = OC::$SERVERROOT.'/tests/config/';
129
+		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
+			self::$configDir = rtrim($dir, '/').'/';
131 131
 		} else {
132
-			self::$configDir = OC::$SERVERROOT . '/config/';
132
+			self::$configDir = OC::$SERVERROOT.'/config/';
133 133
 		}
134 134
 		self::$config = new \OC\Config(self::$configDir);
135 135
 
@@ -151,9 +151,9 @@  discard block
 block discarded – undo
151 151
 			//make sure suburi follows the same rules as scriptName
152 152
 			if (substr(OC::$SUBURI, -9) != 'index.php') {
153 153
 				if (substr(OC::$SUBURI, -1) != '/') {
154
-					OC::$SUBURI = OC::$SUBURI . '/';
154
+					OC::$SUBURI = OC::$SUBURI.'/';
155 155
 				}
156
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
156
+				OC::$SUBURI = OC::$SUBURI.'index.php';
157 157
 			}
158 158
 		}
159 159
 
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
166 166
 
167 167
 				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
168
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
168
+					OC::$WEBROOT = '/'.OC::$WEBROOT;
169 169
 				}
170 170
 			} else {
171 171
 				// The scriptName is not ending with OC::$SUBURI
@@ -194,11 +194,11 @@  discard block
 block discarded – undo
194 194
 					OC::$APPSROOTS[] = $paths;
195 195
 				}
196 196
 			}
197
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
198
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
199
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
197
+		} elseif (file_exists(OC::$SERVERROOT.'/apps')) {
198
+			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT.'/apps', 'url' => '/apps', 'writable' => true);
199
+		} elseif (file_exists(OC::$SERVERROOT.'/../apps')) {
200 200
 			OC::$APPSROOTS[] = array(
201
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
201
+				'path' => rtrim(dirname(OC::$SERVERROOT), '/').'/apps',
202 202
 				'url' => '/apps',
203 203
 				'writable' => true
204 204
 			);
@@ -228,8 +228,8 @@  discard block
 block discarded – undo
228 228
 		$l = \OC::$server->getL10N('lib');
229 229
 
230 230
 		// Create config if it does not already exist
231
-		$configFilePath = self::$configDir .'/config.php';
232
-		if(!file_exists($configFilePath)) {
231
+		$configFilePath = self::$configDir.'/config.php';
232
+		if (!file_exists($configFilePath)) {
233 233
 			@touch($configFilePath);
234 234
 		}
235 235
 
@@ -244,13 +244,13 @@  discard block
 block discarded – undo
244 244
 				echo $l->t('Cannot write into "config" directory!')."\n";
245 245
 				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246 246
 				echo "\n";
247
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
247
+				echo $l->t('See %s', [$urlGenerator->linkToDocs('admin-dir_permissions')])."\n";
248 248
 				exit;
249 249
 			} else {
250 250
 				OC_Template::printErrorPage(
251 251
 					$l->t('Cannot write into "config" directory!'),
252 252
 					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
253
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
253
+					 [$urlGenerator->linkToDocs('admin-dir_permissions')])
254 254
 				);
255 255
 			}
256 256
 		}
@@ -265,8 +265,8 @@  discard block
 block discarded – undo
265 265
 			if (OC::$CLI) {
266 266
 				throw new Exception('Not installed');
267 267
 			} else {
268
-				$url = OC::$WEBROOT . '/index.php';
269
-				header('Location: ' . $url);
268
+				$url = OC::$WEBROOT.'/index.php';
269
+				header('Location: '.$url);
270 270
 			}
271 271
 			exit();
272 272
 		}
@@ -394,14 +394,14 @@  discard block
 block discarded – undo
394 394
 		$incompatibleShippedApps = [];
395 395
 		foreach ($incompatibleApps as $appInfo) {
396 396
 			if ($appManager->isShipped($appInfo['id'])) {
397
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
397
+				$incompatibleShippedApps[] = $appInfo['name'].' ('.$appInfo['id'].')';
398 398
 			}
399 399
 		}
400 400
 
401 401
 		if (!empty($incompatibleShippedApps)) {
402 402
 			$l = \OC::$server->getL10N('core');
403 403
 			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
404
-			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);
404
+			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);
405 405
 		}
406 406
 
407 407
 		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
@@ -416,7 +416,7 @@  discard block
 block discarded – undo
416 416
 		ini_set('session.cookie_httponly', true);
417 417
 
418 418
 		// set the cookie path to the Nextcloud directory
419
-		$cookie_path = OC::$WEBROOT ? : '/';
419
+		$cookie_path = OC::$WEBROOT ?: '/';
420 420
 		ini_set('session.cookie_path', $cookie_path);
421 421
 
422 422
 		// Let the session name be changed in the initSession Hook
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
 		// session timeout
451 451
 		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
452 452
 			if (isset($_COOKIE[session_name()])) {
453
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
453
+				setcookie(session_name(), null, -1, self::$WEBROOT ?: '/');
454 454
 			}
455 455
 			\OC::$server->getUserSession()->logout();
456 456
 		}
@@ -472,7 +472,7 @@  discard block
 block discarded – undo
472 472
 				continue;
473 473
 			}
474 474
 
475
-			$file = $appPath . '/appinfo/classpath.php';
475
+			$file = $appPath.'/appinfo/classpath.php';
476 476
 			if (file_exists($file)) {
477 477
 				require_once $file;
478 478
 			}
@@ -500,14 +500,14 @@  discard block
 block discarded – undo
500 500
 
501 501
 		// Append __Host to the cookie if it meets the requirements
502 502
 		$cookiePrefix = '';
503
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
503
+		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
504 504
 			$cookiePrefix = '__Host-';
505 505
 		}
506 506
 
507
-		foreach($policies as $policy) {
507
+		foreach ($policies as $policy) {
508 508
 			header(
509 509
 				sprintf(
510
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
510
+					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;'.$secureCookie.'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
511 511
 					$cookiePrefix,
512 512
 					$policy,
513 513
 					$cookieParams['path'],
@@ -538,31 +538,31 @@  discard block
 block discarded – undo
538 538
 			// OS X Finder
539 539
 			'/^WebDAVFS/',
540 540
 		];
541
-		if($request->isUserAgent($incompatibleUserAgents)) {
541
+		if ($request->isUserAgent($incompatibleUserAgents)) {
542 542
 			return;
543 543
 		}
544 544
 
545
-		if(count($_COOKIE) > 0) {
545
+		if (count($_COOKIE) > 0) {
546 546
 			$requestUri = $request->getScriptName();
547 547
 			$processingScript = explode('/', $requestUri);
548
-			$processingScript = $processingScript[count($processingScript)-1];
548
+			$processingScript = $processingScript[count($processingScript) - 1];
549 549
 
550 550
 			// index.php routes are handled in the middleware
551
-			if($processingScript === 'index.php') {
551
+			if ($processingScript === 'index.php') {
552 552
 				return;
553 553
 			}
554 554
 
555 555
 			// All other endpoints require the lax and the strict cookie
556
-			if(!$request->passesStrictCookieCheck()) {
556
+			if (!$request->passesStrictCookieCheck()) {
557 557
 				self::sendSameSiteCookies();
558 558
 				// Debug mode gets access to the resources without strict cookie
559 559
 				// due to the fact that the SabreDAV browser also lives there.
560
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
560
+				if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
561 561
 					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
562 562
 					exit();
563 563
 				}
564 564
 			}
565
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
565
+		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
566 566
 			self::sendSameSiteCookies();
567 567
 		}
568 568
 	}
@@ -573,12 +573,12 @@  discard block
 block discarded – undo
573 573
 
574 574
 		// register autoloader
575 575
 		$loaderStart = microtime(true);
576
-		require_once __DIR__ . '/autoloader.php';
576
+		require_once __DIR__.'/autoloader.php';
577 577
 		self::$loader = new \OC\Autoloader([
578
-			OC::$SERVERROOT . '/lib/private/legacy',
578
+			OC::$SERVERROOT.'/lib/private/legacy',
579 579
 		]);
580 580
 		if (defined('PHPUNIT_RUN')) {
581
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
581
+			self::$loader->addValidRoot(OC::$SERVERROOT.'/tests');
582 582
 		}
583 583
 		spl_autoload_register(array(self::$loader, 'load'));
584 584
 		$loaderEnd = microtime(true);
@@ -586,12 +586,12 @@  discard block
 block discarded – undo
586 586
 		self::$CLI = (php_sapi_name() == 'cli');
587 587
 
588 588
 		// Add default composer PSR-4 autoloader
589
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
589
+		self::$composerAutoloader = require_once OC::$SERVERROOT.'/lib/composer/autoload.php';
590 590
 
591 591
 		try {
592 592
 			self::initPaths();
593 593
 			// setup 3rdparty autoloader
594
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
594
+			$vendorAutoLoad = OC::$SERVERROOT.'/3rdparty/autoload.php';
595 595
 			if (!file_exists($vendorAutoLoad)) {
596 596
 				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".');
597 597
 			}
@@ -601,7 +601,7 @@  discard block
 block discarded – undo
601 601
 			if (!self::$CLI) {
602 602
 				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
603 603
 				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
604
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
604
+				header($protocol.' '.OC_Response::STATUS_SERVICE_UNAVAILABLE);
605 605
 			}
606 606
 			// we can't use the template error page here, because this needs the
607 607
 			// DI container which isn't available yet
@@ -619,7 +619,7 @@  discard block
 block discarded – undo
619 619
 		@ini_set('display_errors', 0);
620 620
 		@ini_set('log_errors', 1);
621 621
 
622
-		if(!date_default_timezone_set('UTC')) {
622
+		if (!date_default_timezone_set('UTC')) {
623 623
 			throw new \RuntimeException('Could not set timezone to UTC');
624 624
 		};
625 625
 
@@ -663,7 +663,7 @@  discard block
 block discarded – undo
663 663
 		self::checkInstalled();
664 664
 
665 665
 		OC_Response::addSecurityHeaders();
666
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
666
+		if (self::$server->getRequest()->getServerProtocol() === 'https') {
667 667
 			ini_set('session.cookie_secure', true);
668 668
 		}
669 669
 
@@ -676,11 +676,11 @@  discard block
 block discarded – undo
676 676
 					// Convert l10n string into regular string for usage in database
677 677
 					$staticErrors = [];
678 678
 					foreach ($errors as $error) {
679
-						echo $error['error'] . "\n";
680
-						echo $error['hint'] . "\n\n";
679
+						echo $error['error']."\n";
680
+						echo $error['hint']."\n\n";
681 681
 						$staticErrors[] = [
682
-							'error' => (string)$error['error'],
683
-							'hint' => (string)$error['hint'],
682
+							'error' => (string) $error['error'],
683
+							'hint' => (string) $error['hint'],
684 684
 						];
685 685
 					}
686 686
 
@@ -702,7 +702,7 @@  discard block
 block discarded – undo
702 702
 		}
703 703
 		//try to set the session lifetime
704 704
 		$sessionLifeTime = self::getSessionLifeTime();
705
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
705
+		@ini_set('gc_maxlifetime', (string) $sessionLifeTime);
706 706
 
707 707
 		$systemConfig = \OC::$server->getSystemConfig();
708 708
 
@@ -748,7 +748,7 @@  discard block
 block discarded – undo
748 748
 		register_shutdown_function(array($lockProvider, 'releaseAll'));
749 749
 
750 750
 		// Check whether the sample configuration has been copied
751
-		if($systemConfig->getValue('copied_sample_config', false)) {
751
+		if ($systemConfig->getValue('copied_sample_config', false)) {
752 752
 			$l = \OC::$server->getL10N('lib');
753 753
 			header('HTTP/1.1 503 Service Temporarily Unavailable');
754 754
 			header('Status: 503 Service Temporarily Unavailable');
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
 		) {
775 775
 			// Allow access to CSS resources
776 776
 			$isScssRequest = false;
777
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
777
+			if (strpos($request->getPathInfo(), '/css/') === 0) {
778 778
 				$isScssRequest = true;
779 779
 			}
780 780
 
@@ -810,7 +810,7 @@  discard block
 block discarded – undo
810 810
 
811 811
 			// NOTE: This will be replaced to use OCP
812 812
 			$userSession = self::$server->getUserSession();
813
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
813
+			$userSession->listen('\OC\User', 'postLogin', function() use ($userSession) {
814 814
 				if (!defined('PHPUNIT_RUN')) {
815 815
 					// reset brute force delay for this IP address and username
816 816
 					$uid = \OC::$server->getUserSession()->getUser()->getUID();
@@ -830,7 +830,7 @@  discard block
 block discarded – undo
830 830
 				} catch (\Exception $e) {
831 831
 					// a GC exception should not prevent users from using OC,
832 832
 					// so log the exception
833
-					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
833
+					\OC::$server->getLogger()->warning('Exception when running cache gc: '.$e->getMessage(), array('app' => 'core'));
834 834
 				}
835 835
 			});
836 836
 		}
@@ -846,7 +846,7 @@  discard block
 block discarded – undo
846 846
 			/** @var \OCP\App\ManagerEvent $event */
847 847
 			$jobList = \OC::$server->getJobList();
848 848
 			$job = 'OC\\Settings\\RemoveOrphaned';
849
-			if(!($jobList->has($job, null))) {
849
+			if (!($jobList->has($job, null))) {
850 850
 				$jobList->add($job);
851 851
 			}
852 852
 		});
@@ -944,12 +944,12 @@  discard block
 block discarded – undo
944 944
 		// emergency app disabling
945 945
 		if ($requestPath === '/disableapp'
946 946
 			&& $request->getMethod() === 'POST'
947
-			&& ((array)$request->getParam('appid')) !== ''
947
+			&& ((array) $request->getParam('appid')) !== ''
948 948
 		) {
949 949
 			\OCP\JSON::callCheck();
950 950
 			\OCP\JSON::checkAdminUser();
951
-			$appIds = (array)$request->getParam('appid');
952
-			foreach($appIds as $appId) {
951
+			$appIds = (array) $request->getParam('appid');
952
+			foreach ($appIds as $appId) {
953 953
 				$appId = \OC_App::cleanAppId($appId);
954 954
 				\OC_App::disable($appId);
955 955
 			}
@@ -964,7 +964,7 @@  discard block
 block discarded – undo
964 964
 		if (!self::checkUpgrade(false)
965 965
 			&& !$systemConfig->getValue('maintenance', false)) {
966 966
 			// For logged-in users: Load everything
967
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
967
+			if (\OC::$server->getUserSession()->isLoggedIn()) {
968 968
 				OC_App::loadApps();
969 969
 			} else {
970 970
 				// For guests: Load only filesystem and logging
Please login to merge, or discard this patch.