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