Passed
Push — master ( 645109...008e6d )
by Christoph
12:14 queued 12s
created
lib/public/Diagnostics/IQueryLogger.php 1 patch
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -34,43 +34,43 @@
 block discarded – undo
34 34
  * @since 8.0.0
35 35
  */
36 36
 interface IQueryLogger extends SQLLogger {
37
-	/**
38
-	 * Mark the start of a query providing query SQL statement, its parameters and types.
39
-	 * This method should be called as close to the DB as possible and after
40
-	 * query is finished finalized with stopQuery() method.
41
-	 *
42
-	 * @param string $sql
43
-	 * @param array|null $params
44
-	 * @param array|null $types
45
-	 * @since 8.0.0
46
-	 */
47
-	public function startQuery($sql, array $params = null, array $types = null);
37
+    /**
38
+     * Mark the start of a query providing query SQL statement, its parameters and types.
39
+     * This method should be called as close to the DB as possible and after
40
+     * query is finished finalized with stopQuery() method.
41
+     *
42
+     * @param string $sql
43
+     * @param array|null $params
44
+     * @param array|null $types
45
+     * @since 8.0.0
46
+     */
47
+    public function startQuery($sql, array $params = null, array $types = null);
48 48
 
49
-	/**
50
-	 * Mark the end of the current active query. Ending query should store \OCP\Diagnostics\IQuery to
51
-	 * be returned with getQueries() method.
52
-	 *
53
-	 * @return mixed
54
-	 * @since 8.0.0
55
-	 */
56
-	public function stopQuery();
49
+    /**
50
+     * Mark the end of the current active query. Ending query should store \OCP\Diagnostics\IQuery to
51
+     * be returned with getQueries() method.
52
+     *
53
+     * @return mixed
54
+     * @since 8.0.0
55
+     */
56
+    public function stopQuery();
57 57
 
58
-	/**
59
-	 * This method should return all \OCP\Diagnostics\IQuery objects stored using
60
-	 * startQuery()/stopQuery() methods.
61
-	 *
62
-	 * @return \OCP\Diagnostics\IQuery[]
63
-	 * @since 8.0.0
64
-	 */
65
-	public function getQueries();
58
+    /**
59
+     * This method should return all \OCP\Diagnostics\IQuery objects stored using
60
+     * startQuery()/stopQuery() methods.
61
+     *
62
+     * @return \OCP\Diagnostics\IQuery[]
63
+     * @since 8.0.0
64
+     */
65
+    public function getQueries();
66 66
 
67
-	/**
68
-	 * Activate the module for the duration of the request. Deactivated module
69
-	 * does not create and store \OCP\Diagnostics\IQuery objects.
70
-	 * Only activated module should create and store objects to be
71
-	 * returned with getQueries() call.
72
-	 *
73
-	 * @since 12.0.0
74
-	 */
75
-	public function activate();
67
+    /**
68
+     * Activate the module for the duration of the request. Deactivated module
69
+     * does not create and store \OCP\Diagnostics\IQuery objects.
70
+     * Only activated module should create and store objects to be
71
+     * returned with getQueries() call.
72
+     *
73
+     * @since 12.0.0
74
+     */
75
+    public function activate();
76 76
 }
Please login to merge, or discard this patch.
lib/public/Contacts/IManager.php 1 patch
Indentation   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -54,132 +54,132 @@
 block discarded – undo
54 54
  */
55 55
 interface IManager {
56 56
 
57
-	/**
58
-	 * This function is used to search and find contacts within the users address books.
59
-	 * In case $pattern is empty all contacts will be returned.
60
-	 *
61
-	 * Example:
62
-	 *  Following function shows how to search for contacts for the name and the email address.
63
-	 *
64
-	 *		public static function getMatchingRecipient($term) {
65
-	 *			$cm = \OC::$server->getContactsManager();
66
-	 *			// The API is not active -> nothing to do
67
-	 *			if (!$cm->isEnabled()) {
68
-	 *				return array();
69
-	 *			}
70
-	 *
71
-	 *			$result = $cm->search($term, array('FN', 'EMAIL'));
72
-	 *			$receivers = array();
73
-	 *			foreach ($result as $r) {
74
-	 *				$id = $r['id'];
75
-	 *				$fn = $r['FN'];
76
-	 *				$email = $r['EMAIL'];
77
-	 *				if (!is_array($email)) {
78
-	 *					$email = array($email);
79
-	 *				}
80
-	 *
81
-	 *				// loop through all email addresses of this contact
82
-	 *				foreach ($email as $e) {
83
-	 *				$displayName = $fn . " <$e>";
84
-	 *				$receivers[] = array(
85
-	 *					'id'    => $id,
86
-	 *					'label' => $displayName,
87
-	 *					'value' => $displayName);
88
-	 *				}
89
-	 *			}
90
-	 *
91
-	 *			return $receivers;
92
-	 *		}
93
-	 *
94
-	 *
95
-	 * @param string $pattern which should match within the $searchProperties
96
-	 * @param array $searchProperties defines the properties within the query pattern should match
97
-	 * @param array $options = array() to define the search behavior
98
-	 * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped
99
-	 * @return array an array of contacts which are arrays of key-value-pairs
100
-	 * @since 6.0.0
101
-	 */
102
-	public function search($pattern, $searchProperties = [], $options = []);
57
+    /**
58
+     * This function is used to search and find contacts within the users address books.
59
+     * In case $pattern is empty all contacts will be returned.
60
+     *
61
+     * Example:
62
+     *  Following function shows how to search for contacts for the name and the email address.
63
+     *
64
+     *		public static function getMatchingRecipient($term) {
65
+     *			$cm = \OC::$server->getContactsManager();
66
+     *			// The API is not active -> nothing to do
67
+     *			if (!$cm->isEnabled()) {
68
+     *				return array();
69
+     *			}
70
+     *
71
+     *			$result = $cm->search($term, array('FN', 'EMAIL'));
72
+     *			$receivers = array();
73
+     *			foreach ($result as $r) {
74
+     *				$id = $r['id'];
75
+     *				$fn = $r['FN'];
76
+     *				$email = $r['EMAIL'];
77
+     *				if (!is_array($email)) {
78
+     *					$email = array($email);
79
+     *				}
80
+     *
81
+     *				// loop through all email addresses of this contact
82
+     *				foreach ($email as $e) {
83
+     *				$displayName = $fn . " <$e>";
84
+     *				$receivers[] = array(
85
+     *					'id'    => $id,
86
+     *					'label' => $displayName,
87
+     *					'value' => $displayName);
88
+     *				}
89
+     *			}
90
+     *
91
+     *			return $receivers;
92
+     *		}
93
+     *
94
+     *
95
+     * @param string $pattern which should match within the $searchProperties
96
+     * @param array $searchProperties defines the properties within the query pattern should match
97
+     * @param array $options = array() to define the search behavior
98
+     * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped
99
+     * @return array an array of contacts which are arrays of key-value-pairs
100
+     * @since 6.0.0
101
+     */
102
+    public function search($pattern, $searchProperties = [], $options = []);
103 103
 
104
-	/**
105
-	 * This function can be used to delete the contact identified by the given id
106
-	 *
107
-	 * @param object $id the unique identifier to a contact
108
-	 * @param string $address_book_key identifier of the address book in which the contact shall be deleted
109
-	 * @return bool successful or not
110
-	 * @since 6.0.0
111
-	 */
112
-	public function delete($id, $address_book_key);
104
+    /**
105
+     * This function can be used to delete the contact identified by the given id
106
+     *
107
+     * @param object $id the unique identifier to a contact
108
+     * @param string $address_book_key identifier of the address book in which the contact shall be deleted
109
+     * @return bool successful or not
110
+     * @since 6.0.0
111
+     */
112
+    public function delete($id, $address_book_key);
113 113
 
114
-	/**
115
-	 * This function is used to create a new contact if 'id' is not given or not present.
116
-	 * Otherwise the contact will be updated by replacing the entire data set.
117
-	 *
118
-	 * @param array $properties this array if key-value-pairs defines a contact
119
-	 * @param string $address_book_key identifier of the address book in which the contact shall be created or updated
120
-	 * @return array an array representing the contact just created or updated
121
-	 * @since 6.0.0
122
-	 */
123
-	public function createOrUpdate($properties, $address_book_key);
114
+    /**
115
+     * This function is used to create a new contact if 'id' is not given or not present.
116
+     * Otherwise the contact will be updated by replacing the entire data set.
117
+     *
118
+     * @param array $properties this array if key-value-pairs defines a contact
119
+     * @param string $address_book_key identifier of the address book in which the contact shall be created or updated
120
+     * @return array an array representing the contact just created or updated
121
+     * @since 6.0.0
122
+     */
123
+    public function createOrUpdate($properties, $address_book_key);
124 124
 
125
-	/**
126
-	 * Check if contacts are available (e.g. contacts app enabled)
127
-	 *
128
-	 * @return bool true if enabled, false if not
129
-	 * @since 6.0.0
130
-	 */
131
-	public function isEnabled();
125
+    /**
126
+     * Check if contacts are available (e.g. contacts app enabled)
127
+     *
128
+     * @return bool true if enabled, false if not
129
+     * @since 6.0.0
130
+     */
131
+    public function isEnabled();
132 132
 
133
-	/**
134
-	 * Registers an address book
135
-	 *
136
-	 * @param \OCP\IAddressBook $address_book
137
-	 * @return void
138
-	 * @since 6.0.0
139
-	 */
140
-	public function registerAddressBook(\OCP\IAddressBook $address_book);
133
+    /**
134
+     * Registers an address book
135
+     *
136
+     * @param \OCP\IAddressBook $address_book
137
+     * @return void
138
+     * @since 6.0.0
139
+     */
140
+    public function registerAddressBook(\OCP\IAddressBook $address_book);
141 141
 
142
-	/**
143
-	 * Unregisters an address book
144
-	 *
145
-	 * @param \OCP\IAddressBook $address_book
146
-	 * @return void
147
-	 * @since 6.0.0
148
-	 */
149
-	public function unregisterAddressBook(\OCP\IAddressBook $address_book);
142
+    /**
143
+     * Unregisters an address book
144
+     *
145
+     * @param \OCP\IAddressBook $address_book
146
+     * @return void
147
+     * @since 6.0.0
148
+     */
149
+    public function unregisterAddressBook(\OCP\IAddressBook $address_book);
150 150
 
151
-	/**
152
-	 * In order to improve lazy loading a closure can be registered which will be called in case
153
-	 * address books are actually requested
154
-	 *
155
-	 * @param \Closure $callable
156
-	 * @return void
157
-	 * @since 6.0.0
158
-	 */
159
-	public function register(\Closure $callable);
151
+    /**
152
+     * In order to improve lazy loading a closure can be registered which will be called in case
153
+     * address books are actually requested
154
+     *
155
+     * @param \Closure $callable
156
+     * @return void
157
+     * @since 6.0.0
158
+     */
159
+    public function register(\Closure $callable);
160 160
 
161
-	/**
162
-	 * Return a list of the user's addressbooks display names
163
-	 *
164
-	 * @return array
165
-	 * @since 6.0.0
166
-	 * @deprecated 16.0.0 - Use `$this->getUserAddressBooks()` instead
167
-	 */
168
-	public function getAddressBooks();
161
+    /**
162
+     * Return a list of the user's addressbooks display names
163
+     *
164
+     * @return array
165
+     * @since 6.0.0
166
+     * @deprecated 16.0.0 - Use `$this->getUserAddressBooks()` instead
167
+     */
168
+    public function getAddressBooks();
169 169
 
170
-	/**
171
-	 * Return a list of the user's addressbooks
172
-	 *
173
-	 * @return IAddressBook[]
174
-	 * @since 16.0.0
175
-	 */
176
-	public function getUserAddressBooks();
170
+    /**
171
+     * Return a list of the user's addressbooks
172
+     *
173
+     * @return IAddressBook[]
174
+     * @since 16.0.0
175
+     */
176
+    public function getUserAddressBooks();
177 177
 
178
-	/**
179
-	 * removes all registered address book instances
180
-	 *
181
-	 * @return void
182
-	 * @since 6.0.0
183
-	 */
184
-	public function clear();
178
+    /**
179
+     * removes all registered address book instances
180
+     *
181
+     * @return void
182
+     * @since 6.0.0
183
+     */
184
+    public function clear();
185 185
 }
Please login to merge, or discard this patch.
lib/public/LDAP/ILDAPProvider.php 1 patch
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -34,128 +34,128 @@
 block discarded – undo
34 34
  * @since 11.0.0
35 35
  */
36 36
 interface ILDAPProvider {
37
-	/**
38
-	 * Translate a user id to LDAP DN.
39
-	 * @param string $uid user id
40
-	 * @return string
41
-	 * @since 11.0.0
42
-	 */
43
-	public function getUserDN($uid);
37
+    /**
38
+     * Translate a user id to LDAP DN.
39
+     * @param string $uid user id
40
+     * @return string
41
+     * @since 11.0.0
42
+     */
43
+    public function getUserDN($uid);
44 44
 
45
-	/**
46
-	 * Translate a group id to LDAP DN.
47
-	 * @param string $gid group id
48
-	 * @return string
49
-	 * @since 13.0.0
50
-	 */
51
-	public function getGroupDN($gid);
45
+    /**
46
+     * Translate a group id to LDAP DN.
47
+     * @param string $gid group id
48
+     * @return string
49
+     * @since 13.0.0
50
+     */
51
+    public function getGroupDN($gid);
52 52
 
53
-	/**
54
-	 * Translate a LDAP DN to an internal user name.
55
-	 * @param string $dn LDAP DN
56
-	 * @return string with the internal user name
57
-	 * @throws \Exception if translation was unsuccessful
58
-	 * @since 11.0.0
59
-	 */
60
-	public function getUserName($dn);
53
+    /**
54
+     * Translate a LDAP DN to an internal user name.
55
+     * @param string $dn LDAP DN
56
+     * @return string with the internal user name
57
+     * @throws \Exception if translation was unsuccessful
58
+     * @since 11.0.0
59
+     */
60
+    public function getUserName($dn);
61 61
 	
62
-	/**
63
-	 * Convert a stored DN so it can be used as base parameter for LDAP queries.
64
-	 * @param string $dn the DN
65
-	 * @return string
66
-	 * @since 11.0.0
67
-	 */
68
-	public function DNasBaseParameter($dn);
62
+    /**
63
+     * Convert a stored DN so it can be used as base parameter for LDAP queries.
64
+     * @param string $dn the DN
65
+     * @return string
66
+     * @since 11.0.0
67
+     */
68
+    public function DNasBaseParameter($dn);
69 69
 	
70
-	/**
71
-	 * Sanitize a DN received from the LDAP server.
72
-	 * @param array $dn the DN in question
73
-	 * @return array the sanitized DN
74
-	 * @since 11.0.0
75
-	 */
76
-	public function sanitizeDN($dn);
70
+    /**
71
+     * Sanitize a DN received from the LDAP server.
72
+     * @param array $dn the DN in question
73
+     * @return array the sanitized DN
74
+     * @since 11.0.0
75
+     */
76
+    public function sanitizeDN($dn);
77 77
 	
78
-	/**
79
-	 * Return a new LDAP connection resource for the specified user.
80
-	 * @param string $uid user id
81
-	 * @return resource of the LDAP connection
82
-	 * @since 11.0.0
83
-	 */
84
-	public function getLDAPConnection($uid);
78
+    /**
79
+     * Return a new LDAP connection resource for the specified user.
80
+     * @param string $uid user id
81
+     * @return resource of the LDAP connection
82
+     * @since 11.0.0
83
+     */
84
+    public function getLDAPConnection($uid);
85 85
 
86
-	/**
87
-	 * Return a new LDAP connection resource for the specified group.
88
-	 * @param string $gid group id
89
-	 * @return resource of the LDAP connection
90
-	 * @since 13.0.0
91
-	 */
92
-	public function getGroupLDAPConnection($gid);
86
+    /**
87
+     * Return a new LDAP connection resource for the specified group.
88
+     * @param string $gid group id
89
+     * @return resource of the LDAP connection
90
+     * @since 13.0.0
91
+     */
92
+    public function getGroupLDAPConnection($gid);
93 93
 	
94
-	/**
95
-	 * Get the LDAP base for users.
96
-	 * @param string $uid user id
97
-	 * @return string the base for users
98
-	 * @throws \Exception if user id was not found in LDAP
99
-	 * @since 11.0.0
100
-	 */
101
-	public function getLDAPBaseUsers($uid);
94
+    /**
95
+     * Get the LDAP base for users.
96
+     * @param string $uid user id
97
+     * @return string the base for users
98
+     * @throws \Exception if user id was not found in LDAP
99
+     * @since 11.0.0
100
+     */
101
+    public function getLDAPBaseUsers($uid);
102 102
 	
103
-	/**
104
-	 * Get the LDAP base for groups.
105
-	 * @param string $uid user id
106
-	 * @return string the base for groups
107
-	 * @throws \Exception if user id was not found in LDAP
108
-	 * @since 11.0.0
109
-	 */
110
-	public function getLDAPBaseGroups($uid);
103
+    /**
104
+     * Get the LDAP base for groups.
105
+     * @param string $uid user id
106
+     * @return string the base for groups
107
+     * @throws \Exception if user id was not found in LDAP
108
+     * @since 11.0.0
109
+     */
110
+    public function getLDAPBaseGroups($uid);
111 111
 	
112
-	/**
113
-	 * Check whether a LDAP DN exists
114
-	 * @param string $dn LDAP DN
115
-	 * @return bool whether the DN exists
116
-	 * @since 11.0.0
117
-	 */
118
-	public function dnExists($dn);
112
+    /**
113
+     * Check whether a LDAP DN exists
114
+     * @param string $dn LDAP DN
115
+     * @return bool whether the DN exists
116
+     * @since 11.0.0
117
+     */
118
+    public function dnExists($dn);
119 119
 	
120
-	/**
121
-	 * Clear the cache if a cache is used, otherwise do nothing.
122
-	 * @param string $uid user id
123
-	 * @since 11.0.0
124
-	 */
125
-	public function clearCache($uid);
120
+    /**
121
+     * Clear the cache if a cache is used, otherwise do nothing.
122
+     * @param string $uid user id
123
+     * @since 11.0.0
124
+     */
125
+    public function clearCache($uid);
126 126
 
127
-	/**
128
-	 * Clear the cache if a cache is used, otherwise do nothing.
129
-	 * @param string $gid group id
130
-	 * @since 13.0.0
131
-	 */
132
-	public function clearGroupCache($gid);
127
+    /**
128
+     * Clear the cache if a cache is used, otherwise do nothing.
129
+     * @param string $gid group id
130
+     * @since 13.0.0
131
+     */
132
+    public function clearGroupCache($gid);
133 133
 
134
-	/**
135
-	 * Get the LDAP attribute name for the user's display name
136
-	 * @param string $uid user id
137
-	 * @return string the display name field
138
-	 * @throws \Exception if user id was not found in LDAP
139
-	 * @since 12.0.0
140
-	 */
141
-	public function getLDAPDisplayNameField($uid);
134
+    /**
135
+     * Get the LDAP attribute name for the user's display name
136
+     * @param string $uid user id
137
+     * @return string the display name field
138
+     * @throws \Exception if user id was not found in LDAP
139
+     * @since 12.0.0
140
+     */
141
+    public function getLDAPDisplayNameField($uid);
142 142
 
143
-	/**
144
-	 * Get the LDAP attribute name for the email
145
-	 * @param string $uid user id
146
-	 * @return string the email field
147
-	 * @throws \Exception if user id was not found in LDAP
148
-	 * @since 12.0.0
149
-	 */
150
-	public function getLDAPEmailField($uid);
143
+    /**
144
+     * Get the LDAP attribute name for the email
145
+     * @param string $uid user id
146
+     * @return string the email field
147
+     * @throws \Exception if user id was not found in LDAP
148
+     * @since 12.0.0
149
+     */
150
+    public function getLDAPEmailField($uid);
151 151
 
152
-	/**
153
-	 * Get the LDAP attribute name for the type of association betweeen users and groups
154
-	 * @param string $gid group id
155
-	 * @return string the configuration, one of: 'memberUid', 'uniqueMember', 'member', 'gidNumber', ''
156
-	 * @throws \Exception if group id was not found in LDAP
157
-	 * @since 13.0.0
158
-	 */
159
-	public function getLDAPGroupMemberAssoc($gid);
152
+    /**
153
+     * Get the LDAP attribute name for the type of association betweeen users and groups
154
+     * @param string $gid group id
155
+     * @return string the configuration, one of: 'memberUid', 'uniqueMember', 'member', 'gidNumber', ''
156
+     * @throws \Exception if group id was not found in LDAP
157
+     * @since 13.0.0
158
+     */
159
+    public function getLDAPGroupMemberAssoc($gid);
160 160
 
161 161
 }
Please login to merge, or discard this patch.
lib/public/Security/ISecureRandom.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -41,30 +41,30 @@
 block discarded – undo
41 41
  */
42 42
 interface ISecureRandom {
43 43
 
44
-	/**
45
-	 * Flags for characters that can be used for <code>generate($length, $characters)</code>
46
-	 */
47
-	const CHAR_UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
48
-	const CHAR_LOWER = 'abcdefghijklmnopqrstuvwxyz';
49
-	const CHAR_DIGITS = '0123456789';
50
-	const CHAR_SYMBOLS = '!\"#$%&\\\'()*+,-./:;<=>?@[\]^_`{|}~';
44
+    /**
45
+     * Flags for characters that can be used for <code>generate($length, $characters)</code>
46
+     */
47
+    const CHAR_UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
48
+    const CHAR_LOWER = 'abcdefghijklmnopqrstuvwxyz';
49
+    const CHAR_DIGITS = '0123456789';
50
+    const CHAR_SYMBOLS = '!\"#$%&\\\'()*+,-./:;<=>?@[\]^_`{|}~';
51 51
 
52
-	/**
53
-	 * Characters that can be used for <code>generate($length, $characters)</code>, to
54
-	 * generate human readable random strings. Lower- and upper-case characters and digits
55
-	 * are included. Characters which are ambiguous are excluded, such as I, l, and 1 and so on.
56
-	 */
57
-	const CHAR_HUMAN_READABLE = 'abcdefgijkmnopqrstwxyzABCDEFGHJKLMNPQRSTWXYZ23456789';
52
+    /**
53
+     * Characters that can be used for <code>generate($length, $characters)</code>, to
54
+     * generate human readable random strings. Lower- and upper-case characters and digits
55
+     * are included. Characters which are ambiguous are excluded, such as I, l, and 1 and so on.
56
+     */
57
+    const CHAR_HUMAN_READABLE = 'abcdefgijkmnopqrstwxyzABCDEFGHJKLMNPQRSTWXYZ23456789';
58 58
 
59
-	/**
60
-	 * Generate a random string of specified length.
61
-	 * @param int $length The length of the generated string
62
-	 * @param string $characters An optional list of characters to use if no character list is
63
-	 * 							specified all valid base64 characters are used.
64
-	 * @return string
65
-	 * @since 8.0.0
66
-	 */
67
-	public function generate(int $length,
68
-							 string $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'): string;
59
+    /**
60
+     * Generate a random string of specified length.
61
+     * @param int $length The length of the generated string
62
+     * @param string $characters An optional list of characters to use if no character list is
63
+     * 							specified all valid base64 characters are used.
64
+     * @return string
65
+     * @since 8.0.0
66
+     */
67
+    public function generate(int $length,
68
+                                string $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'): string;
69 69
 
70 70
 }
Please login to merge, or discard this patch.
lib/public/Util.php 2 patches
Indentation   +469 added lines, -469 removed lines patch added patch discarded remove patch
@@ -57,473 +57,473 @@
 block discarded – undo
57 57
  * @since 4.0.0
58 58
  */
59 59
 class Util {
60
-	/**
61
-	 * @deprecated 14.0.0 use \OCP\ILogger::DEBUG
62
-	 */
63
-	const DEBUG=0;
64
-	/**
65
-	 * @deprecated 14.0.0 use \OCP\ILogger::INFO
66
-	 */
67
-	const INFO=1;
68
-	/**
69
-	 * @deprecated 14.0.0 use \OCP\ILogger::WARN
70
-	 */
71
-	const WARN=2;
72
-	/**
73
-	 * @deprecated 14.0.0 use \OCP\ILogger::ERROR
74
-	 */
75
-	const ERROR=3;
76
-	/**
77
-	 * @deprecated 14.0.0 use \OCP\ILogger::FATAL
78
-	 */
79
-	const FATAL=4;
80
-
81
-	/** \OCP\Share\IManager */
82
-	private static $shareManager;
83
-
84
-	/**
85
-	 * get the current installed version of Nextcloud
86
-	 * @return array
87
-	 * @since 4.0.0
88
-	 */
89
-	public static function getVersion() {
90
-		return \OC_Util::getVersion();
91
-	}
92
-
93
-	/**
94
-	 * @since 17.0.0
95
-	 */
96
-	public static function hasExtendedSupport(): bool {
97
-		try {
98
-			/** @var \OCP\Support\Subscription\IRegistry */
99
-			$subscriptionRegistry = \OC::$server->query(\OCP\Support\Subscription\IRegistry::class);
100
-			return $subscriptionRegistry->delegateHasExtendedSupport();
101
-		} catch (AppFramework\QueryException $e) {}
102
-		return \OC::$server->getConfig()->getSystemValueBool('extendedSupport', false);
103
-	}
104
-
105
-	/**
106
-	 * Set current update channel
107
-	 * @param string $channel
108
-	 * @since 8.1.0
109
-	 */
110
-	public static function setChannel($channel) {
111
-		\OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
112
-	}
113
-
114
-	/**
115
-	 * Get current update channel
116
-	 * @return string
117
-	 * @since 8.1.0
118
-	 */
119
-	public static function getChannel() {
120
-		return \OC_Util::getChannel();
121
-	}
122
-
123
-	/**
124
-	 * write a message in the log
125
-	 * @param string $app
126
-	 * @param string $message
127
-	 * @param int $level
128
-	 * @since 4.0.0
129
-	 * @deprecated 13.0.0 use log of \OCP\ILogger
130
-	 */
131
-	public static function writeLog($app, $message, $level) {
132
-		$context = ['app' => $app];
133
-		\OC::$server->getLogger()->log($level, $message, $context);
134
-	}
135
-
136
-	/**
137
-	 * check if sharing is disabled for the current user
138
-	 *
139
-	 * @return boolean
140
-	 * @since 7.0.0
141
-	 * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
142
-	 */
143
-	public static function isSharingDisabledForUser() {
144
-		if (self::$shareManager === null) {
145
-			self::$shareManager = \OC::$server->getShareManager();
146
-		}
147
-
148
-		$user = \OC::$server->getUserSession()->getUser();
149
-		if ($user !== null) {
150
-			$user = $user->getUID();
151
-		}
152
-
153
-		return self::$shareManager->sharingDisabledForUser($user);
154
-	}
155
-
156
-	/**
157
-	 * get l10n object
158
-	 * @param string $application
159
-	 * @param string|null $language
160
-	 * @return \OCP\IL10N
161
-	 * @since 6.0.0 - parameter $language was added in 8.0.0
162
-	 */
163
-	public static function getL10N($application, $language = null) {
164
-		return \OC::$server->getL10N($application, $language);
165
-	}
166
-
167
-	/**
168
-	 * add a css file
169
-	 * @param string $application
170
-	 * @param string $file
171
-	 * @since 4.0.0
172
-	 */
173
-	public static function addStyle($application, $file = null) {
174
-		\OC_Util::addStyle($application, $file);
175
-	}
176
-
177
-	/**
178
-	 * add a javascript file
179
-	 * @param string $application
180
-	 * @param string $file
181
-	 * @since 4.0.0
182
-	 */
183
-	public static function addScript($application, $file = null) {
184
-		\OC_Util::addScript($application, $file);
185
-	}
186
-
187
-	/**
188
-	 * Add a translation JS file
189
-	 * @param string $application application id
190
-	 * @param string $languageCode language code, defaults to the current locale
191
-	 * @since 8.0.0
192
-	 */
193
-	public static function addTranslations($application, $languageCode = null) {
194
-		\OC_Util::addTranslations($application, $languageCode);
195
-	}
196
-
197
-	/**
198
-	 * Add a custom element to the header
199
-	 * If $text is null then the element will be written as empty element.
200
-	 * So use "" to get a closing tag.
201
-	 * @param string $tag tag name of the element
202
-	 * @param array $attributes array of attributes for the element
203
-	 * @param string $text the text content for the element
204
-	 * @since 4.0.0
205
-	 */
206
-	public static function addHeader($tag, $attributes, $text=null) {
207
-		\OC_Util::addHeader($tag, $attributes, $text);
208
-	}
209
-
210
-	/**
211
-	 * Creates an absolute url to the given app and file.
212
-	 * @param string $app app
213
-	 * @param string $file file
214
-	 * @param array $args array with param=>value, will be appended to the returned url
215
-	 * 	The value of $args will be urlencoded
216
-	 * @return string the url
217
-	 * @since 4.0.0 - parameter $args was added in 4.5.0
218
-	 */
219
-	public static function linkToAbsolute($app, $file, $args = []) {
220
-		$urlGenerator = \OC::$server->getURLGenerator();
221
-		return $urlGenerator->getAbsoluteURL(
222
-			$urlGenerator->linkTo($app, $file, $args)
223
-		);
224
-	}
225
-
226
-	/**
227
-	 * Creates an absolute url for remote use.
228
-	 * @param string $service id
229
-	 * @return string the url
230
-	 * @since 4.0.0
231
-	 */
232
-	public static function linkToRemote($service) {
233
-		$urlGenerator = \OC::$server->getURLGenerator();
234
-		$remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
235
-		return $urlGenerator->getAbsoluteURL(
236
-			$remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
237
-		);
238
-	}
239
-
240
-	/**
241
-	 * Creates an absolute url for public use
242
-	 * @param string $service id
243
-	 * @return string the url
244
-	 * @since 4.5.0
245
-	 * @deprecated 15.0.0 - use OCP\IURLGenerator
246
-	 */
247
-	public static function linkToPublic($service) {
248
-		$urlGenerator = \OC::$server->getURLGenerator();
249
-		if ($service === 'files') {
250
-			return $urlGenerator->getAbsoluteURL('/s');
251
-		}
252
-		return $urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'public.php').'?service='.$service);
253
-	}
254
-
255
-	/**
256
-	 * Returns the server host name without an eventual port number
257
-	 * @return string the server hostname
258
-	 * @since 5.0.0
259
-	 */
260
-	public static function getServerHostName() {
261
-		$host_name = \OC::$server->getRequest()->getServerHost();
262
-		// strip away port number (if existing)
263
-		$colon_pos = strpos($host_name, ':');
264
-		if ($colon_pos != false) {
265
-			$host_name = substr($host_name, 0, $colon_pos);
266
-		}
267
-		return $host_name;
268
-	}
269
-
270
-	/**
271
-	 * Returns the default email address
272
-	 * @param string $user_part the user part of the address
273
-	 * @return string the default email address
274
-	 *
275
-	 * Assembles a default email address (using the server hostname
276
-	 * and the given user part, and returns it
277
-	 * Example: when given lostpassword-noreply as $user_part param,
278
-	 *     and is currently accessed via http(s)://example.com/,
279
-	 *     it would return '[email protected]'
280
-	 *
281
-	 * If the configuration value 'mail_from_address' is set in
282
-	 * config.php, this value will override the $user_part that
283
-	 * is passed to this function
284
-	 * @since 5.0.0
285
-	 */
286
-	public static function getDefaultEmailAddress($user_part) {
287
-		$config = \OC::$server->getConfig();
288
-		$user_part = $config->getSystemValue('mail_from_address', $user_part);
289
-		$host_name = self::getServerHostName();
290
-		$host_name = $config->getSystemValue('mail_domain', $host_name);
291
-		$defaultEmailAddress = $user_part.'@'.$host_name;
292
-
293
-		$mailer = \OC::$server->getMailer();
294
-		if ($mailer->validateMailAddress($defaultEmailAddress)) {
295
-			return $defaultEmailAddress;
296
-		}
297
-
298
-		// in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
299
-		return $user_part.'@localhost.localdomain';
300
-	}
301
-
302
-	/**
303
-	 * Make a human file size (2048 to 2 kB)
304
-	 * @param int $bytes file size in bytes
305
-	 * @return string a human readable file size
306
-	 * @since 4.0.0
307
-	 */
308
-	public static function humanFileSize($bytes) {
309
-		return \OC_Helper::humanFileSize($bytes);
310
-	}
311
-
312
-	/**
313
-	 * Make a computer file size (2 kB to 2048)
314
-	 * @param string $str file size in a fancy format
315
-	 * @return float a file size in bytes
316
-	 *
317
-	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
318
-	 * @since 4.0.0
319
-	 */
320
-	public static function computerFileSize($str) {
321
-		return \OC_Helper::computerFileSize($str);
322
-	}
323
-
324
-	/**
325
-	 * connects a function to a hook
326
-	 *
327
-	 * @param string $signalClass class name of emitter
328
-	 * @param string $signalName name of signal
329
-	 * @param string|object $slotClass class name of slot
330
-	 * @param string $slotName name of slot
331
-	 * @return bool
332
-	 *
333
-	 * This function makes it very easy to connect to use hooks.
334
-	 *
335
-	 * TODO: write example
336
-	 * @since 4.0.0
337
-	 */
338
-	static public function connectHook($signalClass, $signalName, $slotClass, $slotName) {
339
-		return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
340
-	}
341
-
342
-	/**
343
-	 * Emits a signal. To get data from the slot use references!
344
-	 * @param string $signalclass class name of emitter
345
-	 * @param string $signalname name of signal
346
-	 * @param array $params default: array() array with additional data
347
-	 * @return bool true if slots exists or false if not
348
-	 *
349
-	 * TODO: write example
350
-	 * @since 4.0.0
351
-	 */
352
-	static public function emitHook($signalclass, $signalname, $params = []) {
353
-		return \OC_Hook::emit($signalclass, $signalname, $params);
354
-	}
355
-
356
-	/**
357
-	 * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
358
-	 * multiple OC_Template elements which invoke `callRegister`. If the value
359
-	 * would not be cached these unit-tests would fail.
360
-	 * @var string
361
-	 */
362
-	private static $token = '';
363
-
364
-	/**
365
-	 * Register an get/post call. This is important to prevent CSRF attacks
366
-	 * @since 4.5.0
367
-	 */
368
-	public static function callRegister() {
369
-		if(self::$token === '') {
370
-			self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
371
-		}
372
-		return self::$token;
373
-	}
374
-
375
-	/**
376
-	 * Used to sanitize HTML
377
-	 *
378
-	 * This function is used to sanitize HTML and should be applied on any
379
-	 * string or array of strings before displaying it on a web page.
380
-	 *
381
-	 * @param string|array $value
382
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
383
-	 * @since 4.5.0
384
-	 */
385
-	public static function sanitizeHTML($value) {
386
-		return \OC_Util::sanitizeHTML($value);
387
-	}
388
-
389
-	/**
390
-	 * Public function to encode url parameters
391
-	 *
392
-	 * This function is used to encode path to file before output.
393
-	 * Encoding is done according to RFC 3986 with one exception:
394
-	 * Character '/' is preserved as is.
395
-	 *
396
-	 * @param string $component part of URI to encode
397
-	 * @return string
398
-	 * @since 6.0.0
399
-	 */
400
-	public static function encodePath($component) {
401
-		return \OC_Util::encodePath($component);
402
-	}
403
-
404
-	/**
405
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
406
-	 *
407
-	 * @param array $input The array to work on
408
-	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
409
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
410
-	 * @return array
411
-	 * @since 4.5.0
412
-	 */
413
-	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
414
-		return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
415
-	}
416
-
417
-	/**
418
-	 * performs a search in a nested array
419
-	 *
420
-	 * @param array $haystack the array to be searched
421
-	 * @param string $needle the search string
422
-	 * @param mixed $index optional, only search this key name
423
-	 * @return mixed the key of the matching field, otherwise false
424
-	 * @since 4.5.0
425
-	 * @deprecated 15.0.0
426
-	 */
427
-	public static function recursiveArraySearch($haystack, $needle, $index = null) {
428
-		return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
429
-	}
430
-
431
-	/**
432
-	 * calculates the maximum upload size respecting system settings, free space and user quota
433
-	 *
434
-	 * @param string $dir the current folder where the user currently operates
435
-	 * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
436
-	 * @return int number of bytes representing
437
-	 * @since 5.0.0
438
-	 */
439
-	public static function maxUploadFilesize($dir, $free = null) {
440
-		return \OC_Helper::maxUploadFilesize($dir, $free);
441
-	}
442
-
443
-	/**
444
-	 * Calculate free space left within user quota
445
-	 * @param string $dir the current folder where the user currently operates
446
-	 * @return int number of bytes representing
447
-	 * @since 7.0.0
448
-	 */
449
-	public static function freeSpace($dir) {
450
-		return \OC_Helper::freeSpace($dir);
451
-	}
452
-
453
-	/**
454
-	 * Calculate PHP upload limit
455
-	 *
456
-	 * @return int number of bytes representing
457
-	 * @since 7.0.0
458
-	 */
459
-	public static function uploadLimit() {
460
-		return \OC_Helper::uploadLimit();
461
-	}
462
-
463
-	/**
464
-	 * Returns whether the given file name is valid
465
-	 * @param string $file file name to check
466
-	 * @return bool true if the file name is valid, false otherwise
467
-	 * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
468
-	 * @since 7.0.0
469
-	 * @suppress PhanDeprecatedFunction
470
-	 */
471
-	public static function isValidFileName($file) {
472
-		return \OC_Util::isValidFileName($file);
473
-	}
474
-
475
-	/**
476
-	 * Compare two strings to provide a natural sort
477
-	 * @param string $a first string to compare
478
-	 * @param string $b second string to compare
479
-	 * @return int -1 if $b comes before $a, 1 if $a comes before $b
480
-	 * or 0 if the strings are identical
481
-	 * @since 7.0.0
482
-	 */
483
-	public static function naturalSortCompare($a, $b) {
484
-		return \OC\NaturalSort::getInstance()->compare($a, $b);
485
-	}
486
-
487
-	/**
488
-	 * check if a password is required for each public link
489
-	 * @return boolean
490
-	 * @since 7.0.0
491
-	 */
492
-	public static function isPublicLinkPasswordRequired() {
493
-		return \OC_Util::isPublicLinkPasswordRequired();
494
-	}
495
-
496
-	/**
497
-	 * check if share API enforces a default expire date
498
-	 * @return boolean
499
-	 * @since 8.0.0
500
-	 */
501
-	public static function isDefaultExpireDateEnforced() {
502
-		return \OC_Util::isDefaultExpireDateEnforced();
503
-	}
504
-
505
-	protected static $needUpgradeCache = null;
506
-
507
-	/**
508
-	 * Checks whether the current version needs upgrade.
509
-	 *
510
-	 * @return bool true if upgrade is needed, false otherwise
511
-	 * @since 7.0.0
512
-	 */
513
-	public static function needUpgrade() {
514
-		if (!isset(self::$needUpgradeCache)) {
515
-			self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
516
-		}
517
-		return self::$needUpgradeCache;
518
-	}
519
-
520
-	/**
521
-	 * is this Internet explorer ?
522
-	 *
523
-	 * @return boolean
524
-	 * @since 14.0.0
525
-	 */
526
-	public static function isIe() {
527
-		return \OC_Util::isIe();
528
-	}
60
+    /**
61
+     * @deprecated 14.0.0 use \OCP\ILogger::DEBUG
62
+     */
63
+    const DEBUG=0;
64
+    /**
65
+     * @deprecated 14.0.0 use \OCP\ILogger::INFO
66
+     */
67
+    const INFO=1;
68
+    /**
69
+     * @deprecated 14.0.0 use \OCP\ILogger::WARN
70
+     */
71
+    const WARN=2;
72
+    /**
73
+     * @deprecated 14.0.0 use \OCP\ILogger::ERROR
74
+     */
75
+    const ERROR=3;
76
+    /**
77
+     * @deprecated 14.0.0 use \OCP\ILogger::FATAL
78
+     */
79
+    const FATAL=4;
80
+
81
+    /** \OCP\Share\IManager */
82
+    private static $shareManager;
83
+
84
+    /**
85
+     * get the current installed version of Nextcloud
86
+     * @return array
87
+     * @since 4.0.0
88
+     */
89
+    public static function getVersion() {
90
+        return \OC_Util::getVersion();
91
+    }
92
+
93
+    /**
94
+     * @since 17.0.0
95
+     */
96
+    public static function hasExtendedSupport(): bool {
97
+        try {
98
+            /** @var \OCP\Support\Subscription\IRegistry */
99
+            $subscriptionRegistry = \OC::$server->query(\OCP\Support\Subscription\IRegistry::class);
100
+            return $subscriptionRegistry->delegateHasExtendedSupport();
101
+        } catch (AppFramework\QueryException $e) {}
102
+        return \OC::$server->getConfig()->getSystemValueBool('extendedSupport', false);
103
+    }
104
+
105
+    /**
106
+     * Set current update channel
107
+     * @param string $channel
108
+     * @since 8.1.0
109
+     */
110
+    public static function setChannel($channel) {
111
+        \OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
112
+    }
113
+
114
+    /**
115
+     * Get current update channel
116
+     * @return string
117
+     * @since 8.1.0
118
+     */
119
+    public static function getChannel() {
120
+        return \OC_Util::getChannel();
121
+    }
122
+
123
+    /**
124
+     * write a message in the log
125
+     * @param string $app
126
+     * @param string $message
127
+     * @param int $level
128
+     * @since 4.0.0
129
+     * @deprecated 13.0.0 use log of \OCP\ILogger
130
+     */
131
+    public static function writeLog($app, $message, $level) {
132
+        $context = ['app' => $app];
133
+        \OC::$server->getLogger()->log($level, $message, $context);
134
+    }
135
+
136
+    /**
137
+     * check if sharing is disabled for the current user
138
+     *
139
+     * @return boolean
140
+     * @since 7.0.0
141
+     * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
142
+     */
143
+    public static function isSharingDisabledForUser() {
144
+        if (self::$shareManager === null) {
145
+            self::$shareManager = \OC::$server->getShareManager();
146
+        }
147
+
148
+        $user = \OC::$server->getUserSession()->getUser();
149
+        if ($user !== null) {
150
+            $user = $user->getUID();
151
+        }
152
+
153
+        return self::$shareManager->sharingDisabledForUser($user);
154
+    }
155
+
156
+    /**
157
+     * get l10n object
158
+     * @param string $application
159
+     * @param string|null $language
160
+     * @return \OCP\IL10N
161
+     * @since 6.0.0 - parameter $language was added in 8.0.0
162
+     */
163
+    public static function getL10N($application, $language = null) {
164
+        return \OC::$server->getL10N($application, $language);
165
+    }
166
+
167
+    /**
168
+     * add a css file
169
+     * @param string $application
170
+     * @param string $file
171
+     * @since 4.0.0
172
+     */
173
+    public static function addStyle($application, $file = null) {
174
+        \OC_Util::addStyle($application, $file);
175
+    }
176
+
177
+    /**
178
+     * add a javascript file
179
+     * @param string $application
180
+     * @param string $file
181
+     * @since 4.0.0
182
+     */
183
+    public static function addScript($application, $file = null) {
184
+        \OC_Util::addScript($application, $file);
185
+    }
186
+
187
+    /**
188
+     * Add a translation JS file
189
+     * @param string $application application id
190
+     * @param string $languageCode language code, defaults to the current locale
191
+     * @since 8.0.0
192
+     */
193
+    public static function addTranslations($application, $languageCode = null) {
194
+        \OC_Util::addTranslations($application, $languageCode);
195
+    }
196
+
197
+    /**
198
+     * Add a custom element to the header
199
+     * If $text is null then the element will be written as empty element.
200
+     * So use "" to get a closing tag.
201
+     * @param string $tag tag name of the element
202
+     * @param array $attributes array of attributes for the element
203
+     * @param string $text the text content for the element
204
+     * @since 4.0.0
205
+     */
206
+    public static function addHeader($tag, $attributes, $text=null) {
207
+        \OC_Util::addHeader($tag, $attributes, $text);
208
+    }
209
+
210
+    /**
211
+     * Creates an absolute url to the given app and file.
212
+     * @param string $app app
213
+     * @param string $file file
214
+     * @param array $args array with param=>value, will be appended to the returned url
215
+     * 	The value of $args will be urlencoded
216
+     * @return string the url
217
+     * @since 4.0.0 - parameter $args was added in 4.5.0
218
+     */
219
+    public static function linkToAbsolute($app, $file, $args = []) {
220
+        $urlGenerator = \OC::$server->getURLGenerator();
221
+        return $urlGenerator->getAbsoluteURL(
222
+            $urlGenerator->linkTo($app, $file, $args)
223
+        );
224
+    }
225
+
226
+    /**
227
+     * Creates an absolute url for remote use.
228
+     * @param string $service id
229
+     * @return string the url
230
+     * @since 4.0.0
231
+     */
232
+    public static function linkToRemote($service) {
233
+        $urlGenerator = \OC::$server->getURLGenerator();
234
+        $remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
235
+        return $urlGenerator->getAbsoluteURL(
236
+            $remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
237
+        );
238
+    }
239
+
240
+    /**
241
+     * Creates an absolute url for public use
242
+     * @param string $service id
243
+     * @return string the url
244
+     * @since 4.5.0
245
+     * @deprecated 15.0.0 - use OCP\IURLGenerator
246
+     */
247
+    public static function linkToPublic($service) {
248
+        $urlGenerator = \OC::$server->getURLGenerator();
249
+        if ($service === 'files') {
250
+            return $urlGenerator->getAbsoluteURL('/s');
251
+        }
252
+        return $urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'public.php').'?service='.$service);
253
+    }
254
+
255
+    /**
256
+     * Returns the server host name without an eventual port number
257
+     * @return string the server hostname
258
+     * @since 5.0.0
259
+     */
260
+    public static function getServerHostName() {
261
+        $host_name = \OC::$server->getRequest()->getServerHost();
262
+        // strip away port number (if existing)
263
+        $colon_pos = strpos($host_name, ':');
264
+        if ($colon_pos != false) {
265
+            $host_name = substr($host_name, 0, $colon_pos);
266
+        }
267
+        return $host_name;
268
+    }
269
+
270
+    /**
271
+     * Returns the default email address
272
+     * @param string $user_part the user part of the address
273
+     * @return string the default email address
274
+     *
275
+     * Assembles a default email address (using the server hostname
276
+     * and the given user part, and returns it
277
+     * Example: when given lostpassword-noreply as $user_part param,
278
+     *     and is currently accessed via http(s)://example.com/,
279
+     *     it would return '[email protected]'
280
+     *
281
+     * If the configuration value 'mail_from_address' is set in
282
+     * config.php, this value will override the $user_part that
283
+     * is passed to this function
284
+     * @since 5.0.0
285
+     */
286
+    public static function getDefaultEmailAddress($user_part) {
287
+        $config = \OC::$server->getConfig();
288
+        $user_part = $config->getSystemValue('mail_from_address', $user_part);
289
+        $host_name = self::getServerHostName();
290
+        $host_name = $config->getSystemValue('mail_domain', $host_name);
291
+        $defaultEmailAddress = $user_part.'@'.$host_name;
292
+
293
+        $mailer = \OC::$server->getMailer();
294
+        if ($mailer->validateMailAddress($defaultEmailAddress)) {
295
+            return $defaultEmailAddress;
296
+        }
297
+
298
+        // in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
299
+        return $user_part.'@localhost.localdomain';
300
+    }
301
+
302
+    /**
303
+     * Make a human file size (2048 to 2 kB)
304
+     * @param int $bytes file size in bytes
305
+     * @return string a human readable file size
306
+     * @since 4.0.0
307
+     */
308
+    public static function humanFileSize($bytes) {
309
+        return \OC_Helper::humanFileSize($bytes);
310
+    }
311
+
312
+    /**
313
+     * Make a computer file size (2 kB to 2048)
314
+     * @param string $str file size in a fancy format
315
+     * @return float a file size in bytes
316
+     *
317
+     * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
318
+     * @since 4.0.0
319
+     */
320
+    public static function computerFileSize($str) {
321
+        return \OC_Helper::computerFileSize($str);
322
+    }
323
+
324
+    /**
325
+     * connects a function to a hook
326
+     *
327
+     * @param string $signalClass class name of emitter
328
+     * @param string $signalName name of signal
329
+     * @param string|object $slotClass class name of slot
330
+     * @param string $slotName name of slot
331
+     * @return bool
332
+     *
333
+     * This function makes it very easy to connect to use hooks.
334
+     *
335
+     * TODO: write example
336
+     * @since 4.0.0
337
+     */
338
+    static public function connectHook($signalClass, $signalName, $slotClass, $slotName) {
339
+        return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
340
+    }
341
+
342
+    /**
343
+     * Emits a signal. To get data from the slot use references!
344
+     * @param string $signalclass class name of emitter
345
+     * @param string $signalname name of signal
346
+     * @param array $params default: array() array with additional data
347
+     * @return bool true if slots exists or false if not
348
+     *
349
+     * TODO: write example
350
+     * @since 4.0.0
351
+     */
352
+    static public function emitHook($signalclass, $signalname, $params = []) {
353
+        return \OC_Hook::emit($signalclass, $signalname, $params);
354
+    }
355
+
356
+    /**
357
+     * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
358
+     * multiple OC_Template elements which invoke `callRegister`. If the value
359
+     * would not be cached these unit-tests would fail.
360
+     * @var string
361
+     */
362
+    private static $token = '';
363
+
364
+    /**
365
+     * Register an get/post call. This is important to prevent CSRF attacks
366
+     * @since 4.5.0
367
+     */
368
+    public static function callRegister() {
369
+        if(self::$token === '') {
370
+            self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
371
+        }
372
+        return self::$token;
373
+    }
374
+
375
+    /**
376
+     * Used to sanitize HTML
377
+     *
378
+     * This function is used to sanitize HTML and should be applied on any
379
+     * string or array of strings before displaying it on a web page.
380
+     *
381
+     * @param string|array $value
382
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
383
+     * @since 4.5.0
384
+     */
385
+    public static function sanitizeHTML($value) {
386
+        return \OC_Util::sanitizeHTML($value);
387
+    }
388
+
389
+    /**
390
+     * Public function to encode url parameters
391
+     *
392
+     * This function is used to encode path to file before output.
393
+     * Encoding is done according to RFC 3986 with one exception:
394
+     * Character '/' is preserved as is.
395
+     *
396
+     * @param string $component part of URI to encode
397
+     * @return string
398
+     * @since 6.0.0
399
+     */
400
+    public static function encodePath($component) {
401
+        return \OC_Util::encodePath($component);
402
+    }
403
+
404
+    /**
405
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
406
+     *
407
+     * @param array $input The array to work on
408
+     * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
409
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
410
+     * @return array
411
+     * @since 4.5.0
412
+     */
413
+    public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
414
+        return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
415
+    }
416
+
417
+    /**
418
+     * performs a search in a nested array
419
+     *
420
+     * @param array $haystack the array to be searched
421
+     * @param string $needle the search string
422
+     * @param mixed $index optional, only search this key name
423
+     * @return mixed the key of the matching field, otherwise false
424
+     * @since 4.5.0
425
+     * @deprecated 15.0.0
426
+     */
427
+    public static function recursiveArraySearch($haystack, $needle, $index = null) {
428
+        return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
429
+    }
430
+
431
+    /**
432
+     * calculates the maximum upload size respecting system settings, free space and user quota
433
+     *
434
+     * @param string $dir the current folder where the user currently operates
435
+     * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
436
+     * @return int number of bytes representing
437
+     * @since 5.0.0
438
+     */
439
+    public static function maxUploadFilesize($dir, $free = null) {
440
+        return \OC_Helper::maxUploadFilesize($dir, $free);
441
+    }
442
+
443
+    /**
444
+     * Calculate free space left within user quota
445
+     * @param string $dir the current folder where the user currently operates
446
+     * @return int number of bytes representing
447
+     * @since 7.0.0
448
+     */
449
+    public static function freeSpace($dir) {
450
+        return \OC_Helper::freeSpace($dir);
451
+    }
452
+
453
+    /**
454
+     * Calculate PHP upload limit
455
+     *
456
+     * @return int number of bytes representing
457
+     * @since 7.0.0
458
+     */
459
+    public static function uploadLimit() {
460
+        return \OC_Helper::uploadLimit();
461
+    }
462
+
463
+    /**
464
+     * Returns whether the given file name is valid
465
+     * @param string $file file name to check
466
+     * @return bool true if the file name is valid, false otherwise
467
+     * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
468
+     * @since 7.0.0
469
+     * @suppress PhanDeprecatedFunction
470
+     */
471
+    public static function isValidFileName($file) {
472
+        return \OC_Util::isValidFileName($file);
473
+    }
474
+
475
+    /**
476
+     * Compare two strings to provide a natural sort
477
+     * @param string $a first string to compare
478
+     * @param string $b second string to compare
479
+     * @return int -1 if $b comes before $a, 1 if $a comes before $b
480
+     * or 0 if the strings are identical
481
+     * @since 7.0.0
482
+     */
483
+    public static function naturalSortCompare($a, $b) {
484
+        return \OC\NaturalSort::getInstance()->compare($a, $b);
485
+    }
486
+
487
+    /**
488
+     * check if a password is required for each public link
489
+     * @return boolean
490
+     * @since 7.0.0
491
+     */
492
+    public static function isPublicLinkPasswordRequired() {
493
+        return \OC_Util::isPublicLinkPasswordRequired();
494
+    }
495
+
496
+    /**
497
+     * check if share API enforces a default expire date
498
+     * @return boolean
499
+     * @since 8.0.0
500
+     */
501
+    public static function isDefaultExpireDateEnforced() {
502
+        return \OC_Util::isDefaultExpireDateEnforced();
503
+    }
504
+
505
+    protected static $needUpgradeCache = null;
506
+
507
+    /**
508
+     * Checks whether the current version needs upgrade.
509
+     *
510
+     * @return bool true if upgrade is needed, false otherwise
511
+     * @since 7.0.0
512
+     */
513
+    public static function needUpgrade() {
514
+        if (!isset(self::$needUpgradeCache)) {
515
+            self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
516
+        }
517
+        return self::$needUpgradeCache;
518
+    }
519
+
520
+    /**
521
+     * is this Internet explorer ?
522
+     *
523
+     * @return boolean
524
+     * @since 14.0.0
525
+     */
526
+    public static function isIe() {
527
+        return \OC_Util::isIe();
528
+    }
529 529
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -60,23 +60,23 @@  discard block
 block discarded – undo
60 60
 	/**
61 61
 	 * @deprecated 14.0.0 use \OCP\ILogger::DEBUG
62 62
 	 */
63
-	const DEBUG=0;
63
+	const DEBUG = 0;
64 64
 	/**
65 65
 	 * @deprecated 14.0.0 use \OCP\ILogger::INFO
66 66
 	 */
67
-	const INFO=1;
67
+	const INFO = 1;
68 68
 	/**
69 69
 	 * @deprecated 14.0.0 use \OCP\ILogger::WARN
70 70
 	 */
71
-	const WARN=2;
71
+	const WARN = 2;
72 72
 	/**
73 73
 	 * @deprecated 14.0.0 use \OCP\ILogger::ERROR
74 74
 	 */
75
-	const ERROR=3;
75
+	const ERROR = 3;
76 76
 	/**
77 77
 	 * @deprecated 14.0.0 use \OCP\ILogger::FATAL
78 78
 	 */
79
-	const FATAL=4;
79
+	const FATAL = 4;
80 80
 
81 81
 	/** \OCP\Share\IManager */
82 82
 	private static $shareManager;
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
 	 * @param string $text the text content for the element
204 204
 	 * @since 4.0.0
205 205
 	 */
206
-	public static function addHeader($tag, $attributes, $text=null) {
206
+	public static function addHeader($tag, $attributes, $text = null) {
207 207
 		\OC_Util::addHeader($tag, $attributes, $text);
208 208
 	}
209 209
 
@@ -231,9 +231,9 @@  discard block
 block discarded – undo
231 231
 	 */
232 232
 	public static function linkToRemote($service) {
233 233
 		$urlGenerator = \OC::$server->getURLGenerator();
234
-		$remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
234
+		$remoteBase = $urlGenerator->linkTo('', 'remote.php').'/'.$service;
235 235
 		return $urlGenerator->getAbsoluteURL(
236
-			$remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
236
+			$remoteBase.(($service[strlen($service) - 1] != '/') ? '/' : '')
237 237
 		);
238 238
 	}
239 239
 
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 	 * @since 4.5.0
367 367
 	 */
368 368
 	public static function callRegister() {
369
-		if(self::$token === '') {
369
+		if (self::$token === '') {
370 370
 			self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
371 371
 		}
372 372
 		return self::$token;
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
 	 */
513 513
 	public static function needUpgrade() {
514 514
 		if (!isset(self::$needUpgradeCache)) {
515
-			self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
515
+			self::$needUpgradeCache = \OC_Util::needUpgrade(\OC::$server->getSystemConfig());
516 516
 		}
517 517
 		return self::$needUpgradeCache;
518 518
 	}
Please login to merge, or discard this patch.
lib/public/App.php 2 patches
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -48,63 +48,63 @@
 block discarded – undo
48 48
 class App {
49 49
 
50 50
 
51
-	/**
52
-	 * Register a Configuration Screen that should appear in the personal settings section.
53
-	 * @param string $app appid
54
-	 * @param string $page page to be included
55
-	 * @return void
56
-	 * @since 4.0.0
57
-	 * @deprecated 14.0.0 Use settings section in appinfo.xml to register personal admin sections
58
-	 */
59
-	public static function registerPersonal($app, $page) {
60
-		\OC_App::registerPersonal($app, $page);
61
-	}
51
+    /**
52
+     * Register a Configuration Screen that should appear in the personal settings section.
53
+     * @param string $app appid
54
+     * @param string $page page to be included
55
+     * @return void
56
+     * @since 4.0.0
57
+     * @deprecated 14.0.0 Use settings section in appinfo.xml to register personal admin sections
58
+     */
59
+    public static function registerPersonal($app, $page) {
60
+        \OC_App::registerPersonal($app, $page);
61
+    }
62 62
 
63
-	/**
64
-	 * Register a Configuration Screen that should appear in the Admin section.
65
-	 * @param string $app string appid
66
-	 * @param string $page string page to be included
67
-	 * @return void
68
-	 * @since 4.0.0
69
-	 * @deprecated 14.0.0 Use settings section in appinfo.xml to register admin sections
70
-	 */
71
-	public static function registerAdmin($app, $page) {
72
-		\OC_App::registerAdmin($app, $page);
73
-	}
63
+    /**
64
+     * Register a Configuration Screen that should appear in the Admin section.
65
+     * @param string $app string appid
66
+     * @param string $page string page to be included
67
+     * @return void
68
+     * @since 4.0.0
69
+     * @deprecated 14.0.0 Use settings section in appinfo.xml to register admin sections
70
+     */
71
+    public static function registerAdmin($app, $page) {
72
+        \OC_App::registerAdmin($app, $page);
73
+    }
74 74
 
75
-	/**
76
-	 * Read app metadata from the info.xml file
77
-	 * @param string $app id of the app or the path of the info.xml file
78
-	 * @param boolean $path (optional)
79
-	 * @return array|null
80
-	 * @deprecated 14.0.0 ise \OC::$server->getAppManager()->getAppInfo($appId)
81
-	 * @since 4.0.0
82
-	 */
83
-	public static function getAppInfo($app, $path=false) {
84
-		return \OC_App::getAppInfo($app, $path);
85
-	}
75
+    /**
76
+     * Read app metadata from the info.xml file
77
+     * @param string $app id of the app or the path of the info.xml file
78
+     * @param boolean $path (optional)
79
+     * @return array|null
80
+     * @deprecated 14.0.0 ise \OC::$server->getAppManager()->getAppInfo($appId)
81
+     * @since 4.0.0
82
+     */
83
+    public static function getAppInfo($app, $path=false) {
84
+        return \OC_App::getAppInfo($app, $path);
85
+    }
86 86
 
87
-	/**
88
-	 * checks whether or not an app is enabled
89
-	 * @param string $app
90
-	 * @return boolean
91
-	 *
92
-	 * This function checks whether or not an app is enabled.
93
-	 * @since 4.0.0
94
-	 * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
95
-	 */
96
-	public static function isEnabled($app) {
97
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
98
-	}
87
+    /**
88
+     * checks whether or not an app is enabled
89
+     * @param string $app
90
+     * @return boolean
91
+     *
92
+     * This function checks whether or not an app is enabled.
93
+     * @since 4.0.0
94
+     * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
95
+     */
96
+    public static function isEnabled($app) {
97
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
98
+    }
99 99
 
100
-	/**
101
-	 * Get the last version of the app from appinfo/info.xml
102
-	 * @param string $app
103
-	 * @return string
104
-	 * @since 4.0.0
105
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion($appId)
106
-	 */
107
-	public static function getAppVersion($app) {
108
-		return \OC::$server->getAppManager()->getAppVersion($app);
109
-	}
100
+    /**
101
+     * Get the last version of the app from appinfo/info.xml
102
+     * @param string $app
103
+     * @return string
104
+     * @since 4.0.0
105
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion($appId)
106
+     */
107
+    public static function getAppVersion($app) {
108
+        return \OC::$server->getAppManager()->getAppVersion($app);
109
+    }
110 110
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@
 block discarded – undo
80 80
 	 * @deprecated 14.0.0 ise \OC::$server->getAppManager()->getAppInfo($appId)
81 81
 	 * @since 4.0.0
82 82
 	 */
83
-	public static function getAppInfo($app, $path=false) {
83
+	public static function getAppInfo($app, $path = false) {
84 84
 		return \OC_App::getAppInfo($app, $path);
85 85
 	}
86 86
 
Please login to merge, or discard this patch.
lib/base.php 2 patches
Indentation   +1015 added lines, -1015 removed lines patch added patch discarded remove patch
@@ -75,1021 +75,1021 @@
 block discarded – undo
75 75
  * OC_autoload!
76 76
  */
77 77
 class OC {
78
-	/**
79
-	 * Associative array for autoloading. classname => filename
80
-	 */
81
-	public static $CLASSPATH = [];
82
-	/**
83
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
84
-	 */
85
-	public static $SERVERROOT = '';
86
-	/**
87
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
88
-	 */
89
-	private static $SUBURI = '';
90
-	/**
91
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
92
-	 */
93
-	public static $WEBROOT = '';
94
-	/**
95
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
96
-	 * web path in 'url'
97
-	 */
98
-	public static $APPSROOTS = [];
99
-
100
-	/**
101
-	 * @var string
102
-	 */
103
-	public static $configDir;
104
-
105
-	/**
106
-	 * requested app
107
-	 */
108
-	public static $REQUESTEDAPP = '';
109
-
110
-	/**
111
-	 * check if Nextcloud runs in cli mode
112
-	 */
113
-	public static $CLI = false;
114
-
115
-	/**
116
-	 * @var \OC\Autoloader $loader
117
-	 */
118
-	public static $loader = null;
119
-
120
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
121
-	public static $composerAutoloader = null;
122
-
123
-	/**
124
-	 * @var \OC\Server
125
-	 */
126
-	public static $server = null;
127
-
128
-	/**
129
-	 * @var \OC\Config
130
-	 */
131
-	private static $config = null;
132
-
133
-	/**
134
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
135
-	 * the app path list is empty or contains an invalid path
136
-	 */
137
-	public static function initPaths() {
138
-		if(defined('PHPUNIT_CONFIG_DIR')) {
139
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
140
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
141
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
142
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
143
-			self::$configDir = rtrim($dir, '/') . '/';
144
-		} else {
145
-			self::$configDir = OC::$SERVERROOT . '/config/';
146
-		}
147
-		self::$config = new \OC\Config(self::$configDir);
148
-
149
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
150
-		/**
151
-		 * FIXME: The following lines are required because we can't yet instantiate
152
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
153
-		 */
154
-		$params = [
155
-			'server' => [
156
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
157
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
158
-			],
159
-		];
160
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
161
-		$scriptName = $fakeRequest->getScriptName();
162
-		if (substr($scriptName, -1) == '/') {
163
-			$scriptName .= 'index.php';
164
-			//make sure suburi follows the same rules as scriptName
165
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
166
-				if (substr(OC::$SUBURI, -1) != '/') {
167
-					OC::$SUBURI = OC::$SUBURI . '/';
168
-				}
169
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
170
-			}
171
-		}
172
-
173
-
174
-		if (OC::$CLI) {
175
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
176
-		} else {
177
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
178
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
179
-
180
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
181
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
182
-				}
183
-			} else {
184
-				// The scriptName is not ending with OC::$SUBURI
185
-				// This most likely means that we are calling from CLI.
186
-				// However some cron jobs still need to generate
187
-				// a web URL, so we use overwritewebroot as a fallback.
188
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
189
-			}
190
-
191
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
192
-			// slash which is required by URL generation.
193
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
194
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
195
-				header('Location: '.\OC::$WEBROOT.'/');
196
-				exit();
197
-			}
198
-		}
199
-
200
-		// search the apps folder
201
-		$config_paths = self::$config->getValue('apps_paths', []);
202
-		if (!empty($config_paths)) {
203
-			foreach ($config_paths as $paths) {
204
-				if (isset($paths['url']) && isset($paths['path'])) {
205
-					$paths['url'] = rtrim($paths['url'], '/');
206
-					$paths['path'] = rtrim($paths['path'], '/');
207
-					OC::$APPSROOTS[] = $paths;
208
-				}
209
-			}
210
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
211
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
212
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
213
-			OC::$APPSROOTS[] = [
214
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
215
-				'url' => '/apps',
216
-				'writable' => true
217
-			];
218
-		}
219
-
220
-		if (empty(OC::$APPSROOTS)) {
221
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
222
-				. ' or the folder above. You can also configure the location in the config.php file.');
223
-		}
224
-		$paths = [];
225
-		foreach (OC::$APPSROOTS as $path) {
226
-			$paths[] = $path['path'];
227
-			if (!is_dir($path['path'])) {
228
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
229
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
230
-					. ' config.php file.', $path['path']));
231
-			}
232
-		}
233
-
234
-		// set the right include path
235
-		set_include_path(
236
-			implode(PATH_SEPARATOR, $paths)
237
-		);
238
-	}
239
-
240
-	public static function checkConfig() {
241
-		$l = \OC::$server->getL10N('lib');
242
-
243
-		// Create config if it does not already exist
244
-		$configFilePath = self::$configDir .'/config.php';
245
-		if(!file_exists($configFilePath)) {
246
-			@touch($configFilePath);
247
-		}
248
-
249
-		// Check if config is writable
250
-		$configFileWritable = is_writable($configFilePath);
251
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
252
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
253
-
254
-			$urlGenerator = \OC::$server->getURLGenerator();
255
-
256
-			if (self::$CLI) {
257
-				echo $l->t('Cannot write into "config" directory!')."\n";
258
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
259
-				echo "\n";
260
-				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
261
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
262
-				exit;
263
-			} else {
264
-				OC_Template::printErrorPage(
265
-					$l->t('Cannot write into "config" directory!'),
266
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
267
-					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
268
-					[ $urlGenerator->linkToDocs('admin-config') ]),
269
-					503
270
-				);
271
-			}
272
-		}
273
-	}
274
-
275
-	public static function checkInstalled() {
276
-		if (defined('OC_CONSOLE')) {
277
-			return;
278
-		}
279
-		// Redirect to installer if not installed
280
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
281
-			if (OC::$CLI) {
282
-				throw new Exception('Not installed');
283
-			} else {
284
-				$url = OC::$WEBROOT . '/index.php';
285
-				header('Location: ' . $url);
286
-			}
287
-			exit();
288
-		}
289
-	}
290
-
291
-	public static function checkMaintenanceMode() {
292
-		// Allow ajax update script to execute without being stopped
293
-		if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
294
-			// send http status 503
295
-			http_response_code(503);
296
-			header('Retry-After: 120');
297
-
298
-			// render error page
299
-			$template = new OC_Template('', 'update.user', 'guest');
300
-			OC_Util::addScript('dist/maintenance');
301
-			OC_Util::addStyle('core', 'guest');
302
-			$template->printPage();
303
-			die();
304
-		}
305
-	}
306
-
307
-	/**
308
-	 * Prints the upgrade page
309
-	 *
310
-	 * @param \OC\SystemConfig $systemConfig
311
-	 */
312
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
313
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
314
-		$tooBig = false;
315
-		if (!$disableWebUpdater) {
316
-			$apps = \OC::$server->getAppManager();
317
-			if ($apps->isInstalled('user_ldap')) {
318
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
319
-
320
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
321
-					->from('ldap_user_mapping')
322
-					->execute();
323
-				$row = $result->fetch();
324
-				$result->closeCursor();
325
-
326
-				$tooBig = ($row['user_count'] > 50);
327
-			}
328
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
329
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
330
-
331
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
332
-					->from('user_saml_users')
333
-					->execute();
334
-				$row = $result->fetch();
335
-				$result->closeCursor();
336
-
337
-				$tooBig = ($row['user_count'] > 50);
338
-			}
339
-			if (!$tooBig) {
340
-				// count users
341
-				$stats = \OC::$server->getUserManager()->countUsers();
342
-				$totalUsers = array_sum($stats);
343
-				$tooBig = ($totalUsers > 50);
344
-			}
345
-		}
346
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
347
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
348
-
349
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
350
-			// send http status 503
351
-			http_response_code(503);
352
-			header('Retry-After: 120');
353
-
354
-			// render error page
355
-			$template = new OC_Template('', 'update.use-cli', 'guest');
356
-			$template->assign('productName', 'nextcloud'); // for now
357
-			$template->assign('version', OC_Util::getVersionString());
358
-			$template->assign('tooBig', $tooBig);
359
-
360
-			$template->printPage();
361
-			die();
362
-		}
363
-
364
-		// check whether this is a core update or apps update
365
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
366
-		$currentVersion = implode('.', \OCP\Util::getVersion());
367
-
368
-		// if not a core upgrade, then it's apps upgrade
369
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
370
-
371
-		$oldTheme = $systemConfig->getValue('theme');
372
-		$systemConfig->setValue('theme', '');
373
-		OC_Util::addScript('config'); // needed for web root
374
-		OC_Util::addScript('update');
375
-
376
-		/** @var \OC\App\AppManager $appManager */
377
-		$appManager = \OC::$server->getAppManager();
378
-
379
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
380
-		$tmpl->assign('version', OC_Util::getVersionString());
381
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
382
-
383
-		// get third party apps
384
-		$ocVersion = \OCP\Util::getVersion();
385
-		$ocVersion = implode('.', $ocVersion);
386
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
387
-		$incompatibleShippedApps = [];
388
-		foreach ($incompatibleApps as $appInfo) {
389
-			if ($appManager->isShipped($appInfo['id'])) {
390
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
391
-			}
392
-		}
393
-
394
-		if (!empty($incompatibleShippedApps)) {
395
-			$l = \OC::$server->getL10N('core');
396
-			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
397
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
398
-		}
399
-
400
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
401
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
402
-		$tmpl->assign('productName', 'Nextcloud'); // for now
403
-		$tmpl->assign('oldTheme', $oldTheme);
404
-		$tmpl->printPage();
405
-	}
406
-
407
-	public static function initSession() {
408
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
409
-			ini_set('session.cookie_secure', true);
410
-		}
411
-
412
-		// prevents javascript from accessing php session cookies
413
-		ini_set('session.cookie_httponly', 'true');
414
-
415
-		// set the cookie path to the Nextcloud directory
416
-		$cookie_path = OC::$WEBROOT ? : '/';
417
-		ini_set('session.cookie_path', $cookie_path);
418
-
419
-		// Let the session name be changed in the initSession Hook
420
-		$sessionName = OC_Util::getInstanceId();
421
-
422
-		try {
423
-			// Allow session apps to create a custom session object
424
-			$useCustomSession = false;
425
-			$session = self::$server->getSession();
426
-			OC_Hook::emit('OC', 'initSession', ['session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession]);
427
-			if (!$useCustomSession) {
428
-				// set the session name to the instance id - which is unique
429
-				$session = new \OC\Session\Internal($sessionName);
430
-			}
431
-
432
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
433
-			$session = $cryptoWrapper->wrapSession($session);
434
-			self::$server->setSession($session);
435
-
436
-			// if session can't be started break with http 500 error
437
-		} catch (Exception $e) {
438
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
439
-			//show the user a detailed error page
440
-			OC_Template::printExceptionErrorPage($e, 500);
441
-			die();
442
-		}
443
-
444
-		$sessionLifeTime = self::getSessionLifeTime();
445
-
446
-		// session timeout
447
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
448
-			if (isset($_COOKIE[session_name()])) {
449
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
450
-			}
451
-			\OC::$server->getUserSession()->logout();
452
-		}
453
-
454
-		$session->set('LAST_ACTIVITY', time());
455
-	}
456
-
457
-	/**
458
-	 * @return string
459
-	 */
460
-	private static function getSessionLifeTime() {
461
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
462
-	}
463
-
464
-	/**
465
-	 * Try to set some values to the required Nextcloud default
466
-	 */
467
-	public static function setRequiredIniValues() {
468
-		@ini_set('default_charset', 'UTF-8');
469
-		@ini_set('gd.jpeg_ignore_warning', '1');
470
-	}
471
-
472
-	/**
473
-	 * Send the same site cookies
474
-	 */
475
-	private static function sendSameSiteCookies() {
476
-		$cookieParams = session_get_cookie_params();
477
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
478
-		$policies = [
479
-			'lax',
480
-			'strict',
481
-		];
482
-
483
-		// Append __Host to the cookie if it meets the requirements
484
-		$cookiePrefix = '';
485
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
486
-			$cookiePrefix = '__Host-';
487
-		}
488
-
489
-		foreach($policies as $policy) {
490
-			header(
491
-				sprintf(
492
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
493
-					$cookiePrefix,
494
-					$policy,
495
-					$cookieParams['path'],
496
-					$policy
497
-				),
498
-				false
499
-			);
500
-		}
501
-	}
502
-
503
-	/**
504
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
505
-	 * be set in every request if cookies are sent to add a second level of
506
-	 * defense against CSRF.
507
-	 *
508
-	 * If the cookie is not sent this will set the cookie and reload the page.
509
-	 * We use an additional cookie since we want to protect logout CSRF and
510
-	 * also we can't directly interfere with PHP's session mechanism.
511
-	 */
512
-	private static function performSameSiteCookieProtection() {
513
-		$request = \OC::$server->getRequest();
514
-
515
-		// Some user agents are notorious and don't really properly follow HTTP
516
-		// specifications. For those, have an automated opt-out. Since the protection
517
-		// for remote.php is applied in base.php as starting point we need to opt out
518
-		// here.
519
-		$incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
520
-
521
-		// Fallback, if csrf.optout is unset
522
-		if (!is_array($incompatibleUserAgents)) {
523
-			$incompatibleUserAgents = [
524
-				// OS X Finder
525
-				'/^WebDAVFS/',
526
-				// Windows webdav drive
527
-				'/^Microsoft-WebDAV-MiniRedir/',
528
-			];
529
-		}
530
-
531
-		if($request->isUserAgent($incompatibleUserAgents)) {
532
-			return;
533
-		}
534
-
535
-		if(count($_COOKIE) > 0) {
536
-			$requestUri = $request->getScriptName();
537
-			$processingScript = explode('/', $requestUri);
538
-			$processingScript = $processingScript[count($processingScript)-1];
539
-
540
-			// index.php routes are handled in the middleware
541
-			if($processingScript === 'index.php') {
542
-				return;
543
-			}
544
-
545
-			// All other endpoints require the lax and the strict cookie
546
-			if(!$request->passesStrictCookieCheck()) {
547
-				self::sendSameSiteCookies();
548
-				// Debug mode gets access to the resources without strict cookie
549
-				// due to the fact that the SabreDAV browser also lives there.
550
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
551
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
552
-					exit();
553
-				}
554
-			}
555
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
556
-			self::sendSameSiteCookies();
557
-		}
558
-	}
559
-
560
-	public static function init() {
561
-		// calculate the root directories
562
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
563
-
564
-		// register autoloader
565
-		$loaderStart = microtime(true);
566
-		require_once __DIR__ . '/autoloader.php';
567
-		self::$loader = new \OC\Autoloader([
568
-			OC::$SERVERROOT . '/lib/private/legacy',
569
-		]);
570
-		if (defined('PHPUNIT_RUN')) {
571
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
572
-		}
573
-		spl_autoload_register([self::$loader, 'load']);
574
-		$loaderEnd = microtime(true);
575
-
576
-		self::$CLI = (php_sapi_name() == 'cli');
577
-
578
-		// Add default composer PSR-4 autoloader
579
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
580
-
581
-		try {
582
-			self::initPaths();
583
-			// setup 3rdparty autoloader
584
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
585
-			if (!file_exists($vendorAutoLoad)) {
586
-				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".');
587
-			}
588
-			require_once $vendorAutoLoad;
589
-
590
-		} catch (\RuntimeException $e) {
591
-			if (!self::$CLI) {
592
-				http_response_code(503);
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
-		// Override php.ini and log everything if we're troubleshooting
606
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
607
-			error_reporting(E_ALL);
608
-		}
609
-
610
-		// Don't display errors and log them
611
-		@ini_set('display_errors', '0');
612
-		@ini_set('log_errors', '1');
613
-
614
-		if(!date_default_timezone_set('UTC')) {
615
-			throw new \RuntimeException('Could not set timezone to UTC');
616
-		}
617
-
618
-		//try to configure php to enable big file uploads.
619
-		//this doesn´t work always depending on the webserver and php configuration.
620
-		//Let´s try to overwrite some defaults anyway
621
-
622
-		//try to set the maximum execution time to 60min
623
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
624
-			@set_time_limit(3600);
625
-		}
626
-		@ini_set('max_execution_time', '3600');
627
-		@ini_set('max_input_time', '3600');
628
-
629
-		//try to set the maximum filesize to 10G
630
-		@ini_set('upload_max_filesize', '10G');
631
-		@ini_set('post_max_size', '10G');
632
-		@ini_set('file_uploads', '50');
633
-
634
-		self::setRequiredIniValues();
635
-		self::handleAuthHeaders();
636
-		self::registerAutoloaderCache();
637
-
638
-		// initialize intl fallback is necessary
639
-		\Patchwork\Utf8\Bootup::initIntl();
640
-		OC_Util::isSetLocaleWorking();
641
-
642
-		if (!defined('PHPUNIT_RUN')) {
643
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
644
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
645
-			OC\Log\ErrorHandler::register($debug);
646
-		}
647
-
648
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
649
-		OC_App::loadApps(['session']);
650
-		if (!self::$CLI) {
651
-			self::initSession();
652
-		}
653
-		\OC::$server->getEventLogger()->end('init_session');
654
-		self::checkConfig();
655
-		self::checkInstalled();
656
-
657
-		OC_Response::addSecurityHeaders();
658
-
659
-		self::performSameSiteCookieProtection();
660
-
661
-		if (!defined('OC_CONSOLE')) {
662
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
663
-			if (count($errors) > 0) {
664
-				if (!self::$CLI) {
665
-					http_response_code(503);
666
-					OC_Util::addStyle('guest');
667
-					try {
668
-						OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
669
-						exit;
670
-					} catch (\Exception $e) {
671
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
672
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
673
-					}
674
-				}
675
-
676
-				// Convert l10n string into regular string for usage in database
677
-				$staticErrors = [];
678
-				foreach ($errors as $error) {
679
-					echo $error['error'] . "\n";
680
-					echo $error['hint'] . "\n\n";
681
-					$staticErrors[] = [
682
-						'error' => (string)$error['error'],
683
-						'hint' => (string)$error['hint'],
684
-					];
685
-				}
686
-
687
-				try {
688
-					\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
689
-				} catch (\Exception $e) {
690
-					echo('Writing to database failed');
691
-				}
692
-				exit(1);
693
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
694
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
695
-			}
696
-		}
697
-		//try to set the session lifetime
698
-		$sessionLifeTime = self::getSessionLifeTime();
699
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
700
-
701
-		$systemConfig = \OC::$server->getSystemConfig();
702
-
703
-		// User and Groups
704
-		if (!$systemConfig->getValue("installed", false)) {
705
-			self::$server->getSession()->set('user_id', '');
706
-		}
707
-
708
-		OC_User::useBackend(new \OC\User\Database());
709
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
710
-
711
-		// Subscribe to the hook
712
-		\OCP\Util::connectHook(
713
-			'\OCA\Files_Sharing\API\Server2Server',
714
-			'preLoginNameUsedAsUserName',
715
-			'\OC\User\Database',
716
-			'preLoginNameUsedAsUserName'
717
-		);
718
-
719
-		//setup extra user backends
720
-		if (!\OCP\Util::needUpgrade()) {
721
-			OC_User::setupBackends();
722
-		} else {
723
-			// Run upgrades in incognito mode
724
-			OC_User::setIncognitoMode(true);
725
-		}
726
-
727
-		self::registerCleanupHooks();
728
-		self::registerFilesystemHooks();
729
-		self::registerShareHooks();
730
-		self::registerEncryptionWrapper();
731
-		self::registerEncryptionHooks();
732
-		self::registerAccountHooks();
733
-		self::registerResourceCollectionHooks();
734
-		self::registerAppRestrictionsHooks();
735
-
736
-		// Make sure that the application class is not loaded before the database is setup
737
-		if ($systemConfig->getValue("installed", false)) {
738
-			OC_App::loadApp('settings');
739
-			$settings = \OC::$server->query(\OCA\Settings\AppInfo\Application::class);
740
-			$settings->register();
741
-		}
742
-
743
-		//make sure temporary files are cleaned up
744
-		$tmpManager = \OC::$server->getTempManager();
745
-		register_shutdown_function([$tmpManager, 'clean']);
746
-		$lockProvider = \OC::$server->getLockingProvider();
747
-		register_shutdown_function([$lockProvider, 'releaseAll']);
748
-
749
-		// Check whether the sample configuration has been copied
750
-		if($systemConfig->getValue('copied_sample_config', false)) {
751
-			$l = \OC::$server->getL10N('lib');
752
-			OC_Template::printErrorPage(
753
-				$l->t('Sample configuration detected'),
754
-				$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'),
755
-				503
756
-			);
757
-			return;
758
-		}
759
-
760
-		$request = \OC::$server->getRequest();
761
-		$host = $request->getInsecureServerHost();
762
-		/**
763
-		 * if the host passed in headers isn't trusted
764
-		 * FIXME: Should not be in here at all :see_no_evil:
765
-		 */
766
-		if (!OC::$CLI
767
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
768
-			&& self::$server->getConfig()->getSystemValue('installed', false)
769
-		) {
770
-			// Allow access to CSS resources
771
-			$isScssRequest = false;
772
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
773
-				$isScssRequest = true;
774
-			}
775
-
776
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
777
-				http_response_code(400);
778
-				header('Content-Type: application/json');
779
-				echo '{"error": "Trusted domain error.", "code": 15}';
780
-				exit();
781
-			}
782
-
783
-			if (!$isScssRequest) {
784
-				http_response_code(400);
785
-
786
-				\OC::$server->getLogger()->info(
787
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
788
-					[
789
-						'app' => 'core',
790
-						'remoteAddress' => $request->getRemoteAddress(),
791
-						'host' => $host,
792
-					]
793
-				);
794
-
795
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
796
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
797
-				$tmpl->printPage();
798
-
799
-				exit();
800
-			}
801
-		}
802
-		\OC::$server->getEventLogger()->end('boot');
803
-	}
804
-
805
-	/**
806
-	 * register hooks for the cleanup of cache and bruteforce protection
807
-	 */
808
-	public static function registerCleanupHooks() {
809
-		//don't try to do this before we are properly setup
810
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
811
-
812
-			// NOTE: This will be replaced to use OCP
813
-			$userSession = self::$server->getUserSession();
814
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
815
-				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
816
-					// reset brute force delay for this IP address and username
817
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
818
-					$request = \OC::$server->getRequest();
819
-					$throttler = \OC::$server->getBruteForceThrottler();
820
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
821
-				}
822
-
823
-				try {
824
-					$cache = new \OC\Cache\File();
825
-					$cache->gc();
826
-				} catch (\OC\ServerNotAvailableException $e) {
827
-					// not a GC exception, pass it on
828
-					throw $e;
829
-				} catch (\OC\ForbiddenException $e) {
830
-					// filesystem blocked for this request, ignore
831
-				} catch (\Exception $e) {
832
-					// a GC exception should not prevent users from using OC,
833
-					// so log the exception
834
-					\OC::$server->getLogger()->logException($e, [
835
-						'message' => 'Exception when running cache gc.',
836
-						'level' => ILogger::WARN,
837
-						'app' => 'core',
838
-					]);
839
-				}
840
-			});
841
-		}
842
-	}
843
-
844
-	private static function registerEncryptionWrapper() {
845
-		$manager = self::$server->getEncryptionManager();
846
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
847
-	}
848
-
849
-	private static function registerEncryptionHooks() {
850
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
851
-		if ($enabled) {
852
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
853
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
854
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
855
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
856
-		}
857
-	}
858
-
859
-	private static function registerAccountHooks() {
860
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
861
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
862
-	}
863
-
864
-	private static function registerAppRestrictionsHooks() {
865
-		$groupManager = self::$server->query(\OCP\IGroupManager::class);
866
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
867
-			$appManager = self::$server->getAppManager();
868
-			$apps = $appManager->getEnabledAppsForGroup($group);
869
-			foreach ($apps as $appId) {
870
-				$restrictions = $appManager->getAppRestriction($appId);
871
-				if (empty($restrictions)) {
872
-					continue;
873
-				}
874
-				$key = array_search($group->getGID(), $restrictions);
875
-				unset($restrictions[$key]);
876
-				$restrictions = array_values($restrictions);
877
-				if (empty($restrictions)) {
878
-					$appManager->disableApp($appId);
879
-				}
880
-				else{
881
-					$appManager->enableAppForGroups($appId, $restrictions);
882
-				}
883
-
884
-			}
885
-		});
886
-	}
887
-
888
-	private static function registerResourceCollectionHooks() {
889
-		\OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
890
-	}
891
-
892
-	/**
893
-	 * register hooks for the filesystem
894
-	 */
895
-	public static function registerFilesystemHooks() {
896
-		// Check for blacklisted files
897
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
898
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
899
-	}
900
-
901
-	/**
902
-	 * register hooks for sharing
903
-	 */
904
-	public static function registerShareHooks() {
905
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
906
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
907
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
908
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
909
-		}
910
-	}
911
-
912
-	protected static function registerAutoloaderCache() {
913
-		// The class loader takes an optional low-latency cache, which MUST be
914
-		// namespaced. The instanceid is used for namespacing, but might be
915
-		// unavailable at this point. Furthermore, it might not be possible to
916
-		// generate an instanceid via \OC_Util::getInstanceId() because the
917
-		// config file may not be writable. As such, we only register a class
918
-		// loader cache if instanceid is available without trying to create one.
919
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
920
-		if ($instanceId) {
921
-			try {
922
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
923
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
924
-			} catch (\Exception $ex) {
925
-			}
926
-		}
927
-	}
928
-
929
-	/**
930
-	 * Handle the request
931
-	 */
932
-	public static function handleRequest() {
933
-
934
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
935
-		$systemConfig = \OC::$server->getSystemConfig();
936
-
937
-		// Check if Nextcloud is installed or in maintenance (update) mode
938
-		if (!$systemConfig->getValue('installed', false)) {
939
-			\OC::$server->getSession()->clear();
940
-			$setupHelper = new OC\Setup(
941
-				$systemConfig,
942
-				\OC::$server->getIniWrapper(),
943
-				\OC::$server->getL10N('lib'),
944
-				\OC::$server->query(\OCP\Defaults::class),
945
-				\OC::$server->getLogger(),
946
-				\OC::$server->getSecureRandom(),
947
-				\OC::$server->query(\OC\Installer::class)
948
-			);
949
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
950
-			$controller->run($_POST);
951
-			exit();
952
-		}
953
-
954
-		$request = \OC::$server->getRequest();
955
-		$requestPath = $request->getRawPathInfo();
956
-		if ($requestPath === '/heartbeat') {
957
-			return;
958
-		}
959
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
960
-			self::checkMaintenanceMode();
961
-
962
-			if (\OCP\Util::needUpgrade()) {
963
-				if (function_exists('opcache_reset')) {
964
-					opcache_reset();
965
-				}
966
-				if (!((bool) $systemConfig->getValue('maintenance', false))) {
967
-					self::printUpgradePage($systemConfig);
968
-					exit();
969
-				}
970
-			}
971
-		}
972
-
973
-		// emergency app disabling
974
-		if ($requestPath === '/disableapp'
975
-			&& $request->getMethod() === 'POST'
976
-			&& ((array)$request->getParam('appid')) !== ''
977
-		) {
978
-			\OC_JSON::callCheck();
979
-			\OC_JSON::checkAdminUser();
980
-			$appIds = (array)$request->getParam('appid');
981
-			foreach($appIds as $appId) {
982
-				$appId = \OC_App::cleanAppId($appId);
983
-				\OC::$server->getAppManager()->disableApp($appId);
984
-			}
985
-			\OC_JSON::success();
986
-			exit();
987
-		}
988
-
989
-		// Always load authentication apps
990
-		OC_App::loadApps(['authentication']);
991
-
992
-		// Load minimum set of apps
993
-		if (!\OCP\Util::needUpgrade()
994
-			&& !((bool) $systemConfig->getValue('maintenance', false))) {
995
-			// For logged-in users: Load everything
996
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
997
-				OC_App::loadApps();
998
-			} else {
999
-				// For guests: Load only filesystem and logging
1000
-				OC_App::loadApps(['filesystem', 'logging']);
1001
-				self::handleLogin($request);
1002
-			}
1003
-		}
1004
-
1005
-		if (!self::$CLI) {
1006
-			try {
1007
-				if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1008
-					OC_App::loadApps(['filesystem', 'logging']);
1009
-					OC_App::loadApps();
1010
-				}
1011
-				OC_Util::setupFS();
1012
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1013
-				return;
1014
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1015
-				//header('HTTP/1.0 404 Not Found');
1016
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1017
-				http_response_code(405);
1018
-				return;
1019
-			}
1020
-		}
1021
-
1022
-		// Handle WebDAV
1023
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1024
-			// not allowed any more to prevent people
1025
-			// mounting this root directly.
1026
-			// Users need to mount remote.php/webdav instead.
1027
-			http_response_code(405);
1028
-			return;
1029
-		}
1030
-
1031
-		// Someone is logged in
1032
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1033
-			OC_App::loadApps();
1034
-			OC_User::setupBackends();
1035
-			OC_Util::setupFS();
1036
-			// FIXME
1037
-			// Redirect to default application
1038
-			OC_Util::redirectToDefaultPage();
1039
-		} else {
1040
-			// Not handled and not logged in
1041
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1042
-		}
1043
-	}
1044
-
1045
-	/**
1046
-	 * Check login: apache auth, auth token, basic auth
1047
-	 *
1048
-	 * @param OCP\IRequest $request
1049
-	 * @return boolean
1050
-	 */
1051
-	static function handleLogin(OCP\IRequest $request) {
1052
-		$userSession = self::$server->getUserSession();
1053
-		if (OC_User::handleApacheAuth()) {
1054
-			return true;
1055
-		}
1056
-		if ($userSession->tryTokenLogin($request)) {
1057
-			return true;
1058
-		}
1059
-		if (isset($_COOKIE['nc_username'])
1060
-			&& isset($_COOKIE['nc_token'])
1061
-			&& isset($_COOKIE['nc_session_id'])
1062
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1063
-			return true;
1064
-		}
1065
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1066
-			return true;
1067
-		}
1068
-		return false;
1069
-	}
1070
-
1071
-	protected static function handleAuthHeaders() {
1072
-		//copy http auth headers for apache+php-fcgid work around
1073
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1074
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1075
-		}
1076
-
1077
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1078
-		$vars = [
1079
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1080
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1081
-		];
1082
-		foreach ($vars as $var) {
1083
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1084
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1085
-				if (count($credentials) === 2) {
1086
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1087
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1088
-					break;
1089
-				}
1090
-			}
1091
-		}
1092
-	}
78
+    /**
79
+     * Associative array for autoloading. classname => filename
80
+     */
81
+    public static $CLASSPATH = [];
82
+    /**
83
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
84
+     */
85
+    public static $SERVERROOT = '';
86
+    /**
87
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
88
+     */
89
+    private static $SUBURI = '';
90
+    /**
91
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
92
+     */
93
+    public static $WEBROOT = '';
94
+    /**
95
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
96
+     * web path in 'url'
97
+     */
98
+    public static $APPSROOTS = [];
99
+
100
+    /**
101
+     * @var string
102
+     */
103
+    public static $configDir;
104
+
105
+    /**
106
+     * requested app
107
+     */
108
+    public static $REQUESTEDAPP = '';
109
+
110
+    /**
111
+     * check if Nextcloud runs in cli mode
112
+     */
113
+    public static $CLI = false;
114
+
115
+    /**
116
+     * @var \OC\Autoloader $loader
117
+     */
118
+    public static $loader = null;
119
+
120
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
121
+    public static $composerAutoloader = null;
122
+
123
+    /**
124
+     * @var \OC\Server
125
+     */
126
+    public static $server = null;
127
+
128
+    /**
129
+     * @var \OC\Config
130
+     */
131
+    private static $config = null;
132
+
133
+    /**
134
+     * @throws \RuntimeException when the 3rdparty directory is missing or
135
+     * the app path list is empty or contains an invalid path
136
+     */
137
+    public static function initPaths() {
138
+        if(defined('PHPUNIT_CONFIG_DIR')) {
139
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
140
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
141
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
142
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
143
+            self::$configDir = rtrim($dir, '/') . '/';
144
+        } else {
145
+            self::$configDir = OC::$SERVERROOT . '/config/';
146
+        }
147
+        self::$config = new \OC\Config(self::$configDir);
148
+
149
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
150
+        /**
151
+         * FIXME: The following lines are required because we can't yet instantiate
152
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
153
+         */
154
+        $params = [
155
+            'server' => [
156
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
157
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
158
+            ],
159
+        ];
160
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
161
+        $scriptName = $fakeRequest->getScriptName();
162
+        if (substr($scriptName, -1) == '/') {
163
+            $scriptName .= 'index.php';
164
+            //make sure suburi follows the same rules as scriptName
165
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
166
+                if (substr(OC::$SUBURI, -1) != '/') {
167
+                    OC::$SUBURI = OC::$SUBURI . '/';
168
+                }
169
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
170
+            }
171
+        }
172
+
173
+
174
+        if (OC::$CLI) {
175
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
176
+        } else {
177
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
178
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
179
+
180
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
181
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
182
+                }
183
+            } else {
184
+                // The scriptName is not ending with OC::$SUBURI
185
+                // This most likely means that we are calling from CLI.
186
+                // However some cron jobs still need to generate
187
+                // a web URL, so we use overwritewebroot as a fallback.
188
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
189
+            }
190
+
191
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
192
+            // slash which is required by URL generation.
193
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
194
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
195
+                header('Location: '.\OC::$WEBROOT.'/');
196
+                exit();
197
+            }
198
+        }
199
+
200
+        // search the apps folder
201
+        $config_paths = self::$config->getValue('apps_paths', []);
202
+        if (!empty($config_paths)) {
203
+            foreach ($config_paths as $paths) {
204
+                if (isset($paths['url']) && isset($paths['path'])) {
205
+                    $paths['url'] = rtrim($paths['url'], '/');
206
+                    $paths['path'] = rtrim($paths['path'], '/');
207
+                    OC::$APPSROOTS[] = $paths;
208
+                }
209
+            }
210
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
211
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
212
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
213
+            OC::$APPSROOTS[] = [
214
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
215
+                'url' => '/apps',
216
+                'writable' => true
217
+            ];
218
+        }
219
+
220
+        if (empty(OC::$APPSROOTS)) {
221
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
222
+                . ' or the folder above. You can also configure the location in the config.php file.');
223
+        }
224
+        $paths = [];
225
+        foreach (OC::$APPSROOTS as $path) {
226
+            $paths[] = $path['path'];
227
+            if (!is_dir($path['path'])) {
228
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
229
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
230
+                    . ' config.php file.', $path['path']));
231
+            }
232
+        }
233
+
234
+        // set the right include path
235
+        set_include_path(
236
+            implode(PATH_SEPARATOR, $paths)
237
+        );
238
+    }
239
+
240
+    public static function checkConfig() {
241
+        $l = \OC::$server->getL10N('lib');
242
+
243
+        // Create config if it does not already exist
244
+        $configFilePath = self::$configDir .'/config.php';
245
+        if(!file_exists($configFilePath)) {
246
+            @touch($configFilePath);
247
+        }
248
+
249
+        // Check if config is writable
250
+        $configFileWritable = is_writable($configFilePath);
251
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
252
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
253
+
254
+            $urlGenerator = \OC::$server->getURLGenerator();
255
+
256
+            if (self::$CLI) {
257
+                echo $l->t('Cannot write into "config" directory!')."\n";
258
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
259
+                echo "\n";
260
+                echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
261
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
262
+                exit;
263
+            } else {
264
+                OC_Template::printErrorPage(
265
+                    $l->t('Cannot write into "config" directory!'),
266
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
267
+                    . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
268
+                    [ $urlGenerator->linkToDocs('admin-config') ]),
269
+                    503
270
+                );
271
+            }
272
+        }
273
+    }
274
+
275
+    public static function checkInstalled() {
276
+        if (defined('OC_CONSOLE')) {
277
+            return;
278
+        }
279
+        // Redirect to installer if not installed
280
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
281
+            if (OC::$CLI) {
282
+                throw new Exception('Not installed');
283
+            } else {
284
+                $url = OC::$WEBROOT . '/index.php';
285
+                header('Location: ' . $url);
286
+            }
287
+            exit();
288
+        }
289
+    }
290
+
291
+    public static function checkMaintenanceMode() {
292
+        // Allow ajax update script to execute without being stopped
293
+        if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
294
+            // send http status 503
295
+            http_response_code(503);
296
+            header('Retry-After: 120');
297
+
298
+            // render error page
299
+            $template = new OC_Template('', 'update.user', 'guest');
300
+            OC_Util::addScript('dist/maintenance');
301
+            OC_Util::addStyle('core', 'guest');
302
+            $template->printPage();
303
+            die();
304
+        }
305
+    }
306
+
307
+    /**
308
+     * Prints the upgrade page
309
+     *
310
+     * @param \OC\SystemConfig $systemConfig
311
+     */
312
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
313
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
314
+        $tooBig = false;
315
+        if (!$disableWebUpdater) {
316
+            $apps = \OC::$server->getAppManager();
317
+            if ($apps->isInstalled('user_ldap')) {
318
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
319
+
320
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
321
+                    ->from('ldap_user_mapping')
322
+                    ->execute();
323
+                $row = $result->fetch();
324
+                $result->closeCursor();
325
+
326
+                $tooBig = ($row['user_count'] > 50);
327
+            }
328
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
329
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
330
+
331
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
332
+                    ->from('user_saml_users')
333
+                    ->execute();
334
+                $row = $result->fetch();
335
+                $result->closeCursor();
336
+
337
+                $tooBig = ($row['user_count'] > 50);
338
+            }
339
+            if (!$tooBig) {
340
+                // count users
341
+                $stats = \OC::$server->getUserManager()->countUsers();
342
+                $totalUsers = array_sum($stats);
343
+                $tooBig = ($totalUsers > 50);
344
+            }
345
+        }
346
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
347
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
348
+
349
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
350
+            // send http status 503
351
+            http_response_code(503);
352
+            header('Retry-After: 120');
353
+
354
+            // render error page
355
+            $template = new OC_Template('', 'update.use-cli', 'guest');
356
+            $template->assign('productName', 'nextcloud'); // for now
357
+            $template->assign('version', OC_Util::getVersionString());
358
+            $template->assign('tooBig', $tooBig);
359
+
360
+            $template->printPage();
361
+            die();
362
+        }
363
+
364
+        // check whether this is a core update or apps update
365
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
366
+        $currentVersion = implode('.', \OCP\Util::getVersion());
367
+
368
+        // if not a core upgrade, then it's apps upgrade
369
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
370
+
371
+        $oldTheme = $systemConfig->getValue('theme');
372
+        $systemConfig->setValue('theme', '');
373
+        OC_Util::addScript('config'); // needed for web root
374
+        OC_Util::addScript('update');
375
+
376
+        /** @var \OC\App\AppManager $appManager */
377
+        $appManager = \OC::$server->getAppManager();
378
+
379
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
380
+        $tmpl->assign('version', OC_Util::getVersionString());
381
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
382
+
383
+        // get third party apps
384
+        $ocVersion = \OCP\Util::getVersion();
385
+        $ocVersion = implode('.', $ocVersion);
386
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
387
+        $incompatibleShippedApps = [];
388
+        foreach ($incompatibleApps as $appInfo) {
389
+            if ($appManager->isShipped($appInfo['id'])) {
390
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
391
+            }
392
+        }
393
+
394
+        if (!empty($incompatibleShippedApps)) {
395
+            $l = \OC::$server->getL10N('core');
396
+            $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
397
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
398
+        }
399
+
400
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
401
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
402
+        $tmpl->assign('productName', 'Nextcloud'); // for now
403
+        $tmpl->assign('oldTheme', $oldTheme);
404
+        $tmpl->printPage();
405
+    }
406
+
407
+    public static function initSession() {
408
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
409
+            ini_set('session.cookie_secure', true);
410
+        }
411
+
412
+        // prevents javascript from accessing php session cookies
413
+        ini_set('session.cookie_httponly', 'true');
414
+
415
+        // set the cookie path to the Nextcloud directory
416
+        $cookie_path = OC::$WEBROOT ? : '/';
417
+        ini_set('session.cookie_path', $cookie_path);
418
+
419
+        // Let the session name be changed in the initSession Hook
420
+        $sessionName = OC_Util::getInstanceId();
421
+
422
+        try {
423
+            // Allow session apps to create a custom session object
424
+            $useCustomSession = false;
425
+            $session = self::$server->getSession();
426
+            OC_Hook::emit('OC', 'initSession', ['session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession]);
427
+            if (!$useCustomSession) {
428
+                // set the session name to the instance id - which is unique
429
+                $session = new \OC\Session\Internal($sessionName);
430
+            }
431
+
432
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
433
+            $session = $cryptoWrapper->wrapSession($session);
434
+            self::$server->setSession($session);
435
+
436
+            // if session can't be started break with http 500 error
437
+        } catch (Exception $e) {
438
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
439
+            //show the user a detailed error page
440
+            OC_Template::printExceptionErrorPage($e, 500);
441
+            die();
442
+        }
443
+
444
+        $sessionLifeTime = self::getSessionLifeTime();
445
+
446
+        // session timeout
447
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
448
+            if (isset($_COOKIE[session_name()])) {
449
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
450
+            }
451
+            \OC::$server->getUserSession()->logout();
452
+        }
453
+
454
+        $session->set('LAST_ACTIVITY', time());
455
+    }
456
+
457
+    /**
458
+     * @return string
459
+     */
460
+    private static function getSessionLifeTime() {
461
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
462
+    }
463
+
464
+    /**
465
+     * Try to set some values to the required Nextcloud default
466
+     */
467
+    public static function setRequiredIniValues() {
468
+        @ini_set('default_charset', 'UTF-8');
469
+        @ini_set('gd.jpeg_ignore_warning', '1');
470
+    }
471
+
472
+    /**
473
+     * Send the same site cookies
474
+     */
475
+    private static function sendSameSiteCookies() {
476
+        $cookieParams = session_get_cookie_params();
477
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
478
+        $policies = [
479
+            'lax',
480
+            'strict',
481
+        ];
482
+
483
+        // Append __Host to the cookie if it meets the requirements
484
+        $cookiePrefix = '';
485
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
486
+            $cookiePrefix = '__Host-';
487
+        }
488
+
489
+        foreach($policies as $policy) {
490
+            header(
491
+                sprintf(
492
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
493
+                    $cookiePrefix,
494
+                    $policy,
495
+                    $cookieParams['path'],
496
+                    $policy
497
+                ),
498
+                false
499
+            );
500
+        }
501
+    }
502
+
503
+    /**
504
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
505
+     * be set in every request if cookies are sent to add a second level of
506
+     * defense against CSRF.
507
+     *
508
+     * If the cookie is not sent this will set the cookie and reload the page.
509
+     * We use an additional cookie since we want to protect logout CSRF and
510
+     * also we can't directly interfere with PHP's session mechanism.
511
+     */
512
+    private static function performSameSiteCookieProtection() {
513
+        $request = \OC::$server->getRequest();
514
+
515
+        // Some user agents are notorious and don't really properly follow HTTP
516
+        // specifications. For those, have an automated opt-out. Since the protection
517
+        // for remote.php is applied in base.php as starting point we need to opt out
518
+        // here.
519
+        $incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
520
+
521
+        // Fallback, if csrf.optout is unset
522
+        if (!is_array($incompatibleUserAgents)) {
523
+            $incompatibleUserAgents = [
524
+                // OS X Finder
525
+                '/^WebDAVFS/',
526
+                // Windows webdav drive
527
+                '/^Microsoft-WebDAV-MiniRedir/',
528
+            ];
529
+        }
530
+
531
+        if($request->isUserAgent($incompatibleUserAgents)) {
532
+            return;
533
+        }
534
+
535
+        if(count($_COOKIE) > 0) {
536
+            $requestUri = $request->getScriptName();
537
+            $processingScript = explode('/', $requestUri);
538
+            $processingScript = $processingScript[count($processingScript)-1];
539
+
540
+            // index.php routes are handled in the middleware
541
+            if($processingScript === 'index.php') {
542
+                return;
543
+            }
544
+
545
+            // All other endpoints require the lax and the strict cookie
546
+            if(!$request->passesStrictCookieCheck()) {
547
+                self::sendSameSiteCookies();
548
+                // Debug mode gets access to the resources without strict cookie
549
+                // due to the fact that the SabreDAV browser also lives there.
550
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
551
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
552
+                    exit();
553
+                }
554
+            }
555
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
556
+            self::sendSameSiteCookies();
557
+        }
558
+    }
559
+
560
+    public static function init() {
561
+        // calculate the root directories
562
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
563
+
564
+        // register autoloader
565
+        $loaderStart = microtime(true);
566
+        require_once __DIR__ . '/autoloader.php';
567
+        self::$loader = new \OC\Autoloader([
568
+            OC::$SERVERROOT . '/lib/private/legacy',
569
+        ]);
570
+        if (defined('PHPUNIT_RUN')) {
571
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
572
+        }
573
+        spl_autoload_register([self::$loader, 'load']);
574
+        $loaderEnd = microtime(true);
575
+
576
+        self::$CLI = (php_sapi_name() == 'cli');
577
+
578
+        // Add default composer PSR-4 autoloader
579
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
580
+
581
+        try {
582
+            self::initPaths();
583
+            // setup 3rdparty autoloader
584
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
585
+            if (!file_exists($vendorAutoLoad)) {
586
+                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".');
587
+            }
588
+            require_once $vendorAutoLoad;
589
+
590
+        } catch (\RuntimeException $e) {
591
+            if (!self::$CLI) {
592
+                http_response_code(503);
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
+        // Override php.ini and log everything if we're troubleshooting
606
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
607
+            error_reporting(E_ALL);
608
+        }
609
+
610
+        // Don't display errors and log them
611
+        @ini_set('display_errors', '0');
612
+        @ini_set('log_errors', '1');
613
+
614
+        if(!date_default_timezone_set('UTC')) {
615
+            throw new \RuntimeException('Could not set timezone to UTC');
616
+        }
617
+
618
+        //try to configure php to enable big file uploads.
619
+        //this doesn´t work always depending on the webserver and php configuration.
620
+        //Let´s try to overwrite some defaults anyway
621
+
622
+        //try to set the maximum execution time to 60min
623
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
624
+            @set_time_limit(3600);
625
+        }
626
+        @ini_set('max_execution_time', '3600');
627
+        @ini_set('max_input_time', '3600');
628
+
629
+        //try to set the maximum filesize to 10G
630
+        @ini_set('upload_max_filesize', '10G');
631
+        @ini_set('post_max_size', '10G');
632
+        @ini_set('file_uploads', '50');
633
+
634
+        self::setRequiredIniValues();
635
+        self::handleAuthHeaders();
636
+        self::registerAutoloaderCache();
637
+
638
+        // initialize intl fallback is necessary
639
+        \Patchwork\Utf8\Bootup::initIntl();
640
+        OC_Util::isSetLocaleWorking();
641
+
642
+        if (!defined('PHPUNIT_RUN')) {
643
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
644
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
645
+            OC\Log\ErrorHandler::register($debug);
646
+        }
647
+
648
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
649
+        OC_App::loadApps(['session']);
650
+        if (!self::$CLI) {
651
+            self::initSession();
652
+        }
653
+        \OC::$server->getEventLogger()->end('init_session');
654
+        self::checkConfig();
655
+        self::checkInstalled();
656
+
657
+        OC_Response::addSecurityHeaders();
658
+
659
+        self::performSameSiteCookieProtection();
660
+
661
+        if (!defined('OC_CONSOLE')) {
662
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
663
+            if (count($errors) > 0) {
664
+                if (!self::$CLI) {
665
+                    http_response_code(503);
666
+                    OC_Util::addStyle('guest');
667
+                    try {
668
+                        OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
669
+                        exit;
670
+                    } catch (\Exception $e) {
671
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
672
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
673
+                    }
674
+                }
675
+
676
+                // Convert l10n string into regular string for usage in database
677
+                $staticErrors = [];
678
+                foreach ($errors as $error) {
679
+                    echo $error['error'] . "\n";
680
+                    echo $error['hint'] . "\n\n";
681
+                    $staticErrors[] = [
682
+                        'error' => (string)$error['error'],
683
+                        'hint' => (string)$error['hint'],
684
+                    ];
685
+                }
686
+
687
+                try {
688
+                    \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
689
+                } catch (\Exception $e) {
690
+                    echo('Writing to database failed');
691
+                }
692
+                exit(1);
693
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
694
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
695
+            }
696
+        }
697
+        //try to set the session lifetime
698
+        $sessionLifeTime = self::getSessionLifeTime();
699
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
700
+
701
+        $systemConfig = \OC::$server->getSystemConfig();
702
+
703
+        // User and Groups
704
+        if (!$systemConfig->getValue("installed", false)) {
705
+            self::$server->getSession()->set('user_id', '');
706
+        }
707
+
708
+        OC_User::useBackend(new \OC\User\Database());
709
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
710
+
711
+        // Subscribe to the hook
712
+        \OCP\Util::connectHook(
713
+            '\OCA\Files_Sharing\API\Server2Server',
714
+            'preLoginNameUsedAsUserName',
715
+            '\OC\User\Database',
716
+            'preLoginNameUsedAsUserName'
717
+        );
718
+
719
+        //setup extra user backends
720
+        if (!\OCP\Util::needUpgrade()) {
721
+            OC_User::setupBackends();
722
+        } else {
723
+            // Run upgrades in incognito mode
724
+            OC_User::setIncognitoMode(true);
725
+        }
726
+
727
+        self::registerCleanupHooks();
728
+        self::registerFilesystemHooks();
729
+        self::registerShareHooks();
730
+        self::registerEncryptionWrapper();
731
+        self::registerEncryptionHooks();
732
+        self::registerAccountHooks();
733
+        self::registerResourceCollectionHooks();
734
+        self::registerAppRestrictionsHooks();
735
+
736
+        // Make sure that the application class is not loaded before the database is setup
737
+        if ($systemConfig->getValue("installed", false)) {
738
+            OC_App::loadApp('settings');
739
+            $settings = \OC::$server->query(\OCA\Settings\AppInfo\Application::class);
740
+            $settings->register();
741
+        }
742
+
743
+        //make sure temporary files are cleaned up
744
+        $tmpManager = \OC::$server->getTempManager();
745
+        register_shutdown_function([$tmpManager, 'clean']);
746
+        $lockProvider = \OC::$server->getLockingProvider();
747
+        register_shutdown_function([$lockProvider, 'releaseAll']);
748
+
749
+        // Check whether the sample configuration has been copied
750
+        if($systemConfig->getValue('copied_sample_config', false)) {
751
+            $l = \OC::$server->getL10N('lib');
752
+            OC_Template::printErrorPage(
753
+                $l->t('Sample configuration detected'),
754
+                $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'),
755
+                503
756
+            );
757
+            return;
758
+        }
759
+
760
+        $request = \OC::$server->getRequest();
761
+        $host = $request->getInsecureServerHost();
762
+        /**
763
+         * if the host passed in headers isn't trusted
764
+         * FIXME: Should not be in here at all :see_no_evil:
765
+         */
766
+        if (!OC::$CLI
767
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
768
+            && self::$server->getConfig()->getSystemValue('installed', false)
769
+        ) {
770
+            // Allow access to CSS resources
771
+            $isScssRequest = false;
772
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
773
+                $isScssRequest = true;
774
+            }
775
+
776
+            if(substr($request->getRequestUri(), -11) === '/status.php') {
777
+                http_response_code(400);
778
+                header('Content-Type: application/json');
779
+                echo '{"error": "Trusted domain error.", "code": 15}';
780
+                exit();
781
+            }
782
+
783
+            if (!$isScssRequest) {
784
+                http_response_code(400);
785
+
786
+                \OC::$server->getLogger()->info(
787
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
788
+                    [
789
+                        'app' => 'core',
790
+                        'remoteAddress' => $request->getRemoteAddress(),
791
+                        'host' => $host,
792
+                    ]
793
+                );
794
+
795
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
796
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
797
+                $tmpl->printPage();
798
+
799
+                exit();
800
+            }
801
+        }
802
+        \OC::$server->getEventLogger()->end('boot');
803
+    }
804
+
805
+    /**
806
+     * register hooks for the cleanup of cache and bruteforce protection
807
+     */
808
+    public static function registerCleanupHooks() {
809
+        //don't try to do this before we are properly setup
810
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
811
+
812
+            // NOTE: This will be replaced to use OCP
813
+            $userSession = self::$server->getUserSession();
814
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
815
+                if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
816
+                    // reset brute force delay for this IP address and username
817
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
818
+                    $request = \OC::$server->getRequest();
819
+                    $throttler = \OC::$server->getBruteForceThrottler();
820
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
821
+                }
822
+
823
+                try {
824
+                    $cache = new \OC\Cache\File();
825
+                    $cache->gc();
826
+                } catch (\OC\ServerNotAvailableException $e) {
827
+                    // not a GC exception, pass it on
828
+                    throw $e;
829
+                } catch (\OC\ForbiddenException $e) {
830
+                    // filesystem blocked for this request, ignore
831
+                } catch (\Exception $e) {
832
+                    // a GC exception should not prevent users from using OC,
833
+                    // so log the exception
834
+                    \OC::$server->getLogger()->logException($e, [
835
+                        'message' => 'Exception when running cache gc.',
836
+                        'level' => ILogger::WARN,
837
+                        'app' => 'core',
838
+                    ]);
839
+                }
840
+            });
841
+        }
842
+    }
843
+
844
+    private static function registerEncryptionWrapper() {
845
+        $manager = self::$server->getEncryptionManager();
846
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
847
+    }
848
+
849
+    private static function registerEncryptionHooks() {
850
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
851
+        if ($enabled) {
852
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
853
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
854
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
855
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
856
+        }
857
+    }
858
+
859
+    private static function registerAccountHooks() {
860
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
861
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
862
+    }
863
+
864
+    private static function registerAppRestrictionsHooks() {
865
+        $groupManager = self::$server->query(\OCP\IGroupManager::class);
866
+        $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
867
+            $appManager = self::$server->getAppManager();
868
+            $apps = $appManager->getEnabledAppsForGroup($group);
869
+            foreach ($apps as $appId) {
870
+                $restrictions = $appManager->getAppRestriction($appId);
871
+                if (empty($restrictions)) {
872
+                    continue;
873
+                }
874
+                $key = array_search($group->getGID(), $restrictions);
875
+                unset($restrictions[$key]);
876
+                $restrictions = array_values($restrictions);
877
+                if (empty($restrictions)) {
878
+                    $appManager->disableApp($appId);
879
+                }
880
+                else{
881
+                    $appManager->enableAppForGroups($appId, $restrictions);
882
+                }
883
+
884
+            }
885
+        });
886
+    }
887
+
888
+    private static function registerResourceCollectionHooks() {
889
+        \OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
890
+    }
891
+
892
+    /**
893
+     * register hooks for the filesystem
894
+     */
895
+    public static function registerFilesystemHooks() {
896
+        // Check for blacklisted files
897
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
898
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
899
+    }
900
+
901
+    /**
902
+     * register hooks for sharing
903
+     */
904
+    public static function registerShareHooks() {
905
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
906
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
907
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
908
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
909
+        }
910
+    }
911
+
912
+    protected static function registerAutoloaderCache() {
913
+        // The class loader takes an optional low-latency cache, which MUST be
914
+        // namespaced. The instanceid is used for namespacing, but might be
915
+        // unavailable at this point. Furthermore, it might not be possible to
916
+        // generate an instanceid via \OC_Util::getInstanceId() because the
917
+        // config file may not be writable. As such, we only register a class
918
+        // loader cache if instanceid is available without trying to create one.
919
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
920
+        if ($instanceId) {
921
+            try {
922
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
923
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
924
+            } catch (\Exception $ex) {
925
+            }
926
+        }
927
+    }
928
+
929
+    /**
930
+     * Handle the request
931
+     */
932
+    public static function handleRequest() {
933
+
934
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
935
+        $systemConfig = \OC::$server->getSystemConfig();
936
+
937
+        // Check if Nextcloud is installed or in maintenance (update) mode
938
+        if (!$systemConfig->getValue('installed', false)) {
939
+            \OC::$server->getSession()->clear();
940
+            $setupHelper = new OC\Setup(
941
+                $systemConfig,
942
+                \OC::$server->getIniWrapper(),
943
+                \OC::$server->getL10N('lib'),
944
+                \OC::$server->query(\OCP\Defaults::class),
945
+                \OC::$server->getLogger(),
946
+                \OC::$server->getSecureRandom(),
947
+                \OC::$server->query(\OC\Installer::class)
948
+            );
949
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
950
+            $controller->run($_POST);
951
+            exit();
952
+        }
953
+
954
+        $request = \OC::$server->getRequest();
955
+        $requestPath = $request->getRawPathInfo();
956
+        if ($requestPath === '/heartbeat') {
957
+            return;
958
+        }
959
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
960
+            self::checkMaintenanceMode();
961
+
962
+            if (\OCP\Util::needUpgrade()) {
963
+                if (function_exists('opcache_reset')) {
964
+                    opcache_reset();
965
+                }
966
+                if (!((bool) $systemConfig->getValue('maintenance', false))) {
967
+                    self::printUpgradePage($systemConfig);
968
+                    exit();
969
+                }
970
+            }
971
+        }
972
+
973
+        // emergency app disabling
974
+        if ($requestPath === '/disableapp'
975
+            && $request->getMethod() === 'POST'
976
+            && ((array)$request->getParam('appid')) !== ''
977
+        ) {
978
+            \OC_JSON::callCheck();
979
+            \OC_JSON::checkAdminUser();
980
+            $appIds = (array)$request->getParam('appid');
981
+            foreach($appIds as $appId) {
982
+                $appId = \OC_App::cleanAppId($appId);
983
+                \OC::$server->getAppManager()->disableApp($appId);
984
+            }
985
+            \OC_JSON::success();
986
+            exit();
987
+        }
988
+
989
+        // Always load authentication apps
990
+        OC_App::loadApps(['authentication']);
991
+
992
+        // Load minimum set of apps
993
+        if (!\OCP\Util::needUpgrade()
994
+            && !((bool) $systemConfig->getValue('maintenance', false))) {
995
+            // For logged-in users: Load everything
996
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
997
+                OC_App::loadApps();
998
+            } else {
999
+                // For guests: Load only filesystem and logging
1000
+                OC_App::loadApps(['filesystem', 'logging']);
1001
+                self::handleLogin($request);
1002
+            }
1003
+        }
1004
+
1005
+        if (!self::$CLI) {
1006
+            try {
1007
+                if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1008
+                    OC_App::loadApps(['filesystem', 'logging']);
1009
+                    OC_App::loadApps();
1010
+                }
1011
+                OC_Util::setupFS();
1012
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1013
+                return;
1014
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1015
+                //header('HTTP/1.0 404 Not Found');
1016
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1017
+                http_response_code(405);
1018
+                return;
1019
+            }
1020
+        }
1021
+
1022
+        // Handle WebDAV
1023
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1024
+            // not allowed any more to prevent people
1025
+            // mounting this root directly.
1026
+            // Users need to mount remote.php/webdav instead.
1027
+            http_response_code(405);
1028
+            return;
1029
+        }
1030
+
1031
+        // Someone is logged in
1032
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1033
+            OC_App::loadApps();
1034
+            OC_User::setupBackends();
1035
+            OC_Util::setupFS();
1036
+            // FIXME
1037
+            // Redirect to default application
1038
+            OC_Util::redirectToDefaultPage();
1039
+        } else {
1040
+            // Not handled and not logged in
1041
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1042
+        }
1043
+    }
1044
+
1045
+    /**
1046
+     * Check login: apache auth, auth token, basic auth
1047
+     *
1048
+     * @param OCP\IRequest $request
1049
+     * @return boolean
1050
+     */
1051
+    static function handleLogin(OCP\IRequest $request) {
1052
+        $userSession = self::$server->getUserSession();
1053
+        if (OC_User::handleApacheAuth()) {
1054
+            return true;
1055
+        }
1056
+        if ($userSession->tryTokenLogin($request)) {
1057
+            return true;
1058
+        }
1059
+        if (isset($_COOKIE['nc_username'])
1060
+            && isset($_COOKIE['nc_token'])
1061
+            && isset($_COOKIE['nc_session_id'])
1062
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1063
+            return true;
1064
+        }
1065
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1066
+            return true;
1067
+        }
1068
+        return false;
1069
+    }
1070
+
1071
+    protected static function handleAuthHeaders() {
1072
+        //copy http auth headers for apache+php-fcgid work around
1073
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1074
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1075
+        }
1076
+
1077
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1078
+        $vars = [
1079
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1080
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1081
+        ];
1082
+        foreach ($vars as $var) {
1083
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1084
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1085
+                if (count($credentials) === 2) {
1086
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1087
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1088
+                    break;
1089
+                }
1090
+            }
1091
+        }
1092
+    }
1093 1093
 }
1094 1094
 
1095 1095
 OC::init();
Please login to merge, or discard this patch.
Spacing   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -135,14 +135,14 @@  discard block
 block discarded – undo
135 135
 	 * the app path list is empty or contains an invalid path
136 136
 	 */
137 137
 	public static function initPaths() {
138
-		if(defined('PHPUNIT_CONFIG_DIR')) {
139
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
140
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
141
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
142
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
143
-			self::$configDir = rtrim($dir, '/') . '/';
138
+		if (defined('PHPUNIT_CONFIG_DIR')) {
139
+			self::$configDir = OC::$SERVERROOT.'/'.PHPUNIT_CONFIG_DIR.'/';
140
+		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT.'/tests/config/')) {
141
+			self::$configDir = OC::$SERVERROOT.'/tests/config/';
142
+		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
143
+			self::$configDir = rtrim($dir, '/').'/';
144 144
 		} else {
145
-			self::$configDir = OC::$SERVERROOT . '/config/';
145
+			self::$configDir = OC::$SERVERROOT.'/config/';
146 146
 		}
147 147
 		self::$config = new \OC\Config(self::$configDir);
148 148
 
@@ -164,9 +164,9 @@  discard block
 block discarded – undo
164 164
 			//make sure suburi follows the same rules as scriptName
165 165
 			if (substr(OC::$SUBURI, -9) != 'index.php') {
166 166
 				if (substr(OC::$SUBURI, -1) != '/') {
167
-					OC::$SUBURI = OC::$SUBURI . '/';
167
+					OC::$SUBURI = OC::$SUBURI.'/';
168 168
 				}
169
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
169
+				OC::$SUBURI = OC::$SUBURI.'index.php';
170 170
 			}
171 171
 		}
172 172
 
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
179 179
 
180 180
 				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
181
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
181
+					OC::$WEBROOT = '/'.OC::$WEBROOT;
182 182
 				}
183 183
 			} else {
184 184
 				// The scriptName is not ending with OC::$SUBURI
@@ -207,11 +207,11 @@  discard block
 block discarded – undo
207 207
 					OC::$APPSROOTS[] = $paths;
208 208
 				}
209 209
 			}
210
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
211
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
212
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
210
+		} elseif (file_exists(OC::$SERVERROOT.'/apps')) {
211
+			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT.'/apps', 'url' => '/apps', 'writable' => true];
212
+		} elseif (file_exists(OC::$SERVERROOT.'/../apps')) {
213 213
 			OC::$APPSROOTS[] = [
214
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
214
+				'path' => rtrim(dirname(OC::$SERVERROOT), '/').'/apps',
215 215
 				'url' => '/apps',
216 216
 				'writable' => true
217 217
 			];
@@ -241,8 +241,8 @@  discard block
 block discarded – undo
241 241
 		$l = \OC::$server->getL10N('lib');
242 242
 
243 243
 		// Create config if it does not already exist
244
-		$configFilePath = self::$configDir .'/config.php';
245
-		if(!file_exists($configFilePath)) {
244
+		$configFilePath = self::$configDir.'/config.php';
245
+		if (!file_exists($configFilePath)) {
246 246
 			@touch($configFilePath);
247 247
 		}
248 248
 
@@ -258,14 +258,14 @@  discard block
 block discarded – undo
258 258
 				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
259 259
 				echo "\n";
260 260
 				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
261
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
261
+				echo $l->t('See %s', [$urlGenerator->linkToDocs('admin-config')])."\n";
262 262
 				exit;
263 263
 			} else {
264 264
 				OC_Template::printErrorPage(
265 265
 					$l->t('Cannot write into "config" directory!'),
266
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
266
+					$l->t('This can usually be fixed by giving the webserver write access to the config directory.').'. '
267 267
 					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
268
-					[ $urlGenerator->linkToDocs('admin-config') ]),
268
+					[$urlGenerator->linkToDocs('admin-config')]),
269 269
 					503
270 270
 				);
271 271
 			}
@@ -281,8 +281,8 @@  discard block
 block discarded – undo
281 281
 			if (OC::$CLI) {
282 282
 				throw new Exception('Not installed');
283 283
 			} else {
284
-				$url = OC::$WEBROOT . '/index.php';
285
-				header('Location: ' . $url);
284
+				$url = OC::$WEBROOT.'/index.php';
285
+				header('Location: '.$url);
286 286
 			}
287 287
 			exit();
288 288
 		}
@@ -387,14 +387,14 @@  discard block
 block discarded – undo
387 387
 		$incompatibleShippedApps = [];
388 388
 		foreach ($incompatibleApps as $appInfo) {
389 389
 			if ($appManager->isShipped($appInfo['id'])) {
390
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
390
+				$incompatibleShippedApps[] = $appInfo['name'].' ('.$appInfo['id'].')';
391 391
 			}
392 392
 		}
393 393
 
394 394
 		if (!empty($incompatibleShippedApps)) {
395 395
 			$l = \OC::$server->getL10N('core');
396 396
 			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
397
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
397
+			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);
398 398
 		}
399 399
 
400 400
 		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 	}
406 406
 
407 407
 	public static function initSession() {
408
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
408
+		if (self::$server->getRequest()->getServerProtocol() === 'https') {
409 409
 			ini_set('session.cookie_secure', true);
410 410
 		}
411 411
 
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 		ini_set('session.cookie_httponly', 'true');
414 414
 
415 415
 		// set the cookie path to the Nextcloud directory
416
-		$cookie_path = OC::$WEBROOT ? : '/';
416
+		$cookie_path = OC::$WEBROOT ?: '/';
417 417
 		ini_set('session.cookie_path', $cookie_path);
418 418
 
419 419
 		// Let the session name be changed in the initSession Hook
@@ -446,7 +446,7 @@  discard block
 block discarded – undo
446 446
 		// session timeout
447 447
 		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
448 448
 			if (isset($_COOKIE[session_name()])) {
449
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
449
+				setcookie(session_name(), '', -1, self::$WEBROOT ?: '/');
450 450
 			}
451 451
 			\OC::$server->getUserSession()->logout();
452 452
 		}
@@ -482,14 +482,14 @@  discard block
 block discarded – undo
482 482
 
483 483
 		// Append __Host to the cookie if it meets the requirements
484 484
 		$cookiePrefix = '';
485
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
485
+		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
486 486
 			$cookiePrefix = '__Host-';
487 487
 		}
488 488
 
489
-		foreach($policies as $policy) {
489
+		foreach ($policies as $policy) {
490 490
 			header(
491 491
 				sprintf(
492
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
492
+					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;'.$secureCookie.'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
493 493
 					$cookiePrefix,
494 494
 					$policy,
495 495
 					$cookieParams['path'],
@@ -528,31 +528,31 @@  discard block
 block discarded – undo
528 528
 			];
529 529
 		}
530 530
 
531
-		if($request->isUserAgent($incompatibleUserAgents)) {
531
+		if ($request->isUserAgent($incompatibleUserAgents)) {
532 532
 			return;
533 533
 		}
534 534
 
535
-		if(count($_COOKIE) > 0) {
535
+		if (count($_COOKIE) > 0) {
536 536
 			$requestUri = $request->getScriptName();
537 537
 			$processingScript = explode('/', $requestUri);
538
-			$processingScript = $processingScript[count($processingScript)-1];
538
+			$processingScript = $processingScript[count($processingScript) - 1];
539 539
 
540 540
 			// index.php routes are handled in the middleware
541
-			if($processingScript === 'index.php') {
541
+			if ($processingScript === 'index.php') {
542 542
 				return;
543 543
 			}
544 544
 
545 545
 			// All other endpoints require the lax and the strict cookie
546
-			if(!$request->passesStrictCookieCheck()) {
546
+			if (!$request->passesStrictCookieCheck()) {
547 547
 				self::sendSameSiteCookies();
548 548
 				// Debug mode gets access to the resources without strict cookie
549 549
 				// due to the fact that the SabreDAV browser also lives there.
550
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
550
+				if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
551 551
 					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
552 552
 					exit();
553 553
 				}
554 554
 			}
555
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
555
+		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
556 556
 			self::sendSameSiteCookies();
557 557
 		}
558 558
 	}
@@ -563,12 +563,12 @@  discard block
 block discarded – undo
563 563
 
564 564
 		// register autoloader
565 565
 		$loaderStart = microtime(true);
566
-		require_once __DIR__ . '/autoloader.php';
566
+		require_once __DIR__.'/autoloader.php';
567 567
 		self::$loader = new \OC\Autoloader([
568
-			OC::$SERVERROOT . '/lib/private/legacy',
568
+			OC::$SERVERROOT.'/lib/private/legacy',
569 569
 		]);
570 570
 		if (defined('PHPUNIT_RUN')) {
571
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
571
+			self::$loader->addValidRoot(OC::$SERVERROOT.'/tests');
572 572
 		}
573 573
 		spl_autoload_register([self::$loader, 'load']);
574 574
 		$loaderEnd = microtime(true);
@@ -576,12 +576,12 @@  discard block
 block discarded – undo
576 576
 		self::$CLI = (php_sapi_name() == 'cli');
577 577
 
578 578
 		// Add default composer PSR-4 autoloader
579
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
579
+		self::$composerAutoloader = require_once OC::$SERVERROOT.'/lib/composer/autoload.php';
580 580
 
581 581
 		try {
582 582
 			self::initPaths();
583 583
 			// setup 3rdparty autoloader
584
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
584
+			$vendorAutoLoad = OC::$SERVERROOT.'/3rdparty/autoload.php';
585 585
 			if (!file_exists($vendorAutoLoad)) {
586 586
 				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".');
587 587
 			}
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
 		@ini_set('display_errors', '0');
612 612
 		@ini_set('log_errors', '1');
613 613
 
614
-		if(!date_default_timezone_set('UTC')) {
614
+		if (!date_default_timezone_set('UTC')) {
615 615
 			throw new \RuntimeException('Could not set timezone to UTC');
616 616
 		}
617 617
 
@@ -676,11 +676,11 @@  discard block
 block discarded – undo
676 676
 				// Convert l10n string into regular string for usage in database
677 677
 				$staticErrors = [];
678 678
 				foreach ($errors as $error) {
679
-					echo $error['error'] . "\n";
680
-					echo $error['hint'] . "\n\n";
679
+					echo $error['error']."\n";
680
+					echo $error['hint']."\n\n";
681 681
 					$staticErrors[] = [
682
-						'error' => (string)$error['error'],
683
-						'hint' => (string)$error['hint'],
682
+						'error' => (string) $error['error'],
683
+						'hint' => (string) $error['hint'],
684 684
 					];
685 685
 				}
686 686
 
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
 		}
697 697
 		//try to set the session lifetime
698 698
 		$sessionLifeTime = self::getSessionLifeTime();
699
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
699
+		@ini_set('gc_maxlifetime', (string) $sessionLifeTime);
700 700
 
701 701
 		$systemConfig = \OC::$server->getSystemConfig();
702 702
 
@@ -747,7 +747,7 @@  discard block
 block discarded – undo
747 747
 		register_shutdown_function([$lockProvider, 'releaseAll']);
748 748
 
749 749
 		// Check whether the sample configuration has been copied
750
-		if($systemConfig->getValue('copied_sample_config', false)) {
750
+		if ($systemConfig->getValue('copied_sample_config', false)) {
751 751
 			$l = \OC::$server->getL10N('lib');
752 752
 			OC_Template::printErrorPage(
753 753
 				$l->t('Sample configuration detected'),
@@ -769,11 +769,11 @@  discard block
 block discarded – undo
769 769
 		) {
770 770
 			// Allow access to CSS resources
771 771
 			$isScssRequest = false;
772
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
772
+			if (strpos($request->getPathInfo(), '/css/') === 0) {
773 773
 				$isScssRequest = true;
774 774
 			}
775 775
 
776
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
776
+			if (substr($request->getRequestUri(), -11) === '/status.php') {
777 777
 				http_response_code(400);
778 778
 				header('Content-Type: application/json');
779 779
 				echo '{"error": "Trusted domain error.", "code": 15}';
@@ -811,7 +811,7 @@  discard block
 block discarded – undo
811 811
 
812 812
 			// NOTE: This will be replaced to use OCP
813 813
 			$userSession = self::$server->getUserSession();
814
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
814
+			$userSession->listen('\OC\User', 'postLogin', function() use ($userSession) {
815 815
 				if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
816 816
 					// reset brute force delay for this IP address and username
817 817
 					$uid = \OC::$server->getUserSession()->getUser()->getUID();
@@ -863,7 +863,7 @@  discard block
 block discarded – undo
863 863
 
864 864
 	private static function registerAppRestrictionsHooks() {
865 865
 		$groupManager = self::$server->query(\OCP\IGroupManager::class);
866
-		$groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
866
+		$groupManager->listen('\OC\Group', 'postDelete', function(\OCP\IGroup $group) {
867 867
 			$appManager = self::$server->getAppManager();
868 868
 			$apps = $appManager->getEnabledAppsForGroup($group);
869 869
 			foreach ($apps as $appId) {
@@ -877,7 +877,7 @@  discard block
 block discarded – undo
877 877
 				if (empty($restrictions)) {
878 878
 					$appManager->disableApp($appId);
879 879
 				}
880
-				else{
880
+				else {
881 881
 					$appManager->enableAppForGroups($appId, $restrictions);
882 882
 				}
883 883
 
@@ -973,12 +973,12 @@  discard block
 block discarded – undo
973 973
 		// emergency app disabling
974 974
 		if ($requestPath === '/disableapp'
975 975
 			&& $request->getMethod() === 'POST'
976
-			&& ((array)$request->getParam('appid')) !== ''
976
+			&& ((array) $request->getParam('appid')) !== ''
977 977
 		) {
978 978
 			\OC_JSON::callCheck();
979 979
 			\OC_JSON::checkAdminUser();
980
-			$appIds = (array)$request->getParam('appid');
981
-			foreach($appIds as $appId) {
980
+			$appIds = (array) $request->getParam('appid');
981
+			foreach ($appIds as $appId) {
982 982
 				$appId = \OC_App::cleanAppId($appId);
983 983
 				\OC::$server->getAppManager()->disableApp($appId);
984 984
 			}
@@ -993,7 +993,7 @@  discard block
 block discarded – undo
993 993
 		if (!\OCP\Util::needUpgrade()
994 994
 			&& !((bool) $systemConfig->getValue('maintenance', false))) {
995 995
 			// For logged-in users: Load everything
996
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
996
+			if (\OC::$server->getUserSession()->isLoggedIn()) {
997 997
 				OC_App::loadApps();
998 998
 			} else {
999 999
 				// For guests: Load only filesystem and logging
Please login to merge, or discard this patch.
lib/private/Search/Result/File.php 1 patch
Indentation   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -33,85 +33,85 @@
 block discarded – undo
33 33
  */
34 34
 class File extends \OCP\Search\Result {
35 35
 
36
-	/**
37
-	 * Type name; translated in templates
38
-	 * @var string
39
-	 */
40
-	public $type = 'file';
36
+    /**
37
+     * Type name; translated in templates
38
+     * @var string
39
+     */
40
+    public $type = 'file';
41 41
 
42
-	/**
43
-	 * Path to file
44
-	 * @var string
45
-	 */
46
-	public $path;
42
+    /**
43
+     * Path to file
44
+     * @var string
45
+     */
46
+    public $path;
47 47
 
48
-	/**
49
-	 * Size, in bytes
50
-	 * @var int
51
-	 */
52
-	public $size;
48
+    /**
49
+     * Size, in bytes
50
+     * @var int
51
+     */
52
+    public $size;
53 53
 
54
-	/**
55
-	 * Date modified, in human readable form
56
-	 * @var string
57
-	 */
58
-	public $modified;
54
+    /**
55
+     * Date modified, in human readable form
56
+     * @var string
57
+     */
58
+    public $modified;
59 59
 
60
-	/**
61
-	 * File mime type
62
-	 * @var string
63
-	 */
64
-	public $mime_type;
60
+    /**
61
+     * File mime type
62
+     * @var string
63
+     */
64
+    public $mime_type;
65 65
 
66
-	/**
67
-	 * File permissions:
68
-	 *
69
-	 * @var string
70
-	 */
71
-	public $permissions;
66
+    /**
67
+     * File permissions:
68
+     *
69
+     * @var string
70
+     */
71
+    public $permissions;
72 72
 
73
-	/**
74
-	 * Create a new file search result
75
-	 * @param FileInfo $data file data given by provider
76
-	 */
77
-	public function __construct(FileInfo $data) {
73
+    /**
74
+     * Create a new file search result
75
+     * @param FileInfo $data file data given by provider
76
+     */
77
+    public function __construct(FileInfo $data) {
78 78
 
79
-		$path = $this->getRelativePath($data->getPath());
79
+        $path = $this->getRelativePath($data->getPath());
80 80
 
81
-		$info = pathinfo($path);
82
-		$this->id = $data->getId();
83
-		$this->name = $info['basename'];
84
-		$this->link = \OC::$server->getURLGenerator()->linkToRoute(
85
-			'files.view.index',
86
-			[
87
-				'dir' => $info['dirname'],
88
-				'scrollto' => $info['basename'],
89
-			]
90
-		);
91
-		$this->permissions = $data->getPermissions();
92
-		$this->path = $path;
93
-		$this->size = $data->getSize();
94
-		$this->modified = $data->getMtime();
95
-		$this->mime_type = $data->getMimetype();
96
-	}
81
+        $info = pathinfo($path);
82
+        $this->id = $data->getId();
83
+        $this->name = $info['basename'];
84
+        $this->link = \OC::$server->getURLGenerator()->linkToRoute(
85
+            'files.view.index',
86
+            [
87
+                'dir' => $info['dirname'],
88
+                'scrollto' => $info['basename'],
89
+            ]
90
+        );
91
+        $this->permissions = $data->getPermissions();
92
+        $this->path = $path;
93
+        $this->size = $data->getSize();
94
+        $this->modified = $data->getMtime();
95
+        $this->mime_type = $data->getMimetype();
96
+    }
97 97
 
98
-	/**
99
-	 * @var Folder $userFolderCache
100
-	 */
101
-	static protected $userFolderCache = null;
98
+    /**
99
+     * @var Folder $userFolderCache
100
+     */
101
+    static protected $userFolderCache = null;
102 102
 
103
-	/**
104
-	 * converts a path relative to the users files folder
105
-	 * eg /user/files/foo.txt -> /foo.txt
106
-	 * @param string $path
107
-	 * @return string relative path
108
-	 */
109
-	protected function getRelativePath($path) {
110
-		if (!isset(self::$userFolderCache)) {
111
-			$user = \OC::$server->getUserSession()->getUser()->getUID();
112
-			self::$userFolderCache = \OC::$server->getUserFolder($user);
113
-		}
114
-		return self::$userFolderCache->getRelativePath($path);
115
-	}
103
+    /**
104
+     * converts a path relative to the users files folder
105
+     * eg /user/files/foo.txt -> /foo.txt
106
+     * @param string $path
107
+     * @return string relative path
108
+     */
109
+    protected function getRelativePath($path) {
110
+        if (!isset(self::$userFolderCache)) {
111
+            $user = \OC::$server->getUserSession()->getUser()->getUID();
112
+            self::$userFolderCache = \OC::$server->getUserFolder($user);
113
+        }
114
+        return self::$userFolderCache->getRelativePath($path);
115
+    }
116 116
 
117 117
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Http/Request.php 2 patches
Indentation   +868 added lines, -868 removed lines patch added patch discarded remove patch
@@ -65,872 +65,872 @@
 block discarded – undo
65 65
  */
66 66
 class Request implements \ArrayAccess, \Countable, IRequest {
67 67
 
68
-	const USER_AGENT_IE = '/(MSIE)|(Trident)/';
69
-	// Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
70
-	const USER_AGENT_MS_EDGE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+ Edge\/[0-9.]+$/';
71
-	// Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
72
-	const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
73
-	// Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
74
-	const USER_AGENT_CHROME = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)( Ubuntu Chromium\/[0-9.]+|) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+( (Vivaldi|Brave|OPR)\/[0-9.]+|)$/';
75
-	// Safari User Agent from http://www.useragentstring.com/pages/Safari/
76
-	const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
77
-	// Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
78
-	const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
79
-	const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
80
-	const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|::1)$/';
81
-
82
-	/**
83
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_IOS instead
84
-	 */
85
-	const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
86
-	/**
87
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_ANDROID instead
88
-	 */
89
-	const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/';
90
-	/**
91
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_DESKTOP instead
92
-	 */
93
-	const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
94
-
95
-	protected $inputStream;
96
-	protected $content;
97
-	protected $items = [];
98
-	protected $allowedKeys = [
99
-		'get',
100
-		'post',
101
-		'files',
102
-		'server',
103
-		'env',
104
-		'cookies',
105
-		'urlParams',
106
-		'parameters',
107
-		'method',
108
-		'requesttoken',
109
-	];
110
-	/** @var ISecureRandom */
111
-	protected $secureRandom;
112
-	/** @var IConfig */
113
-	protected $config;
114
-	/** @var string */
115
-	protected $requestId = '';
116
-	/** @var ICrypto */
117
-	protected $crypto;
118
-	/** @var CsrfTokenManager|null */
119
-	protected $csrfTokenManager;
120
-
121
-	/** @var bool */
122
-	protected $contentDecoded = false;
123
-
124
-	/**
125
-	 * @param array $vars An associative array with the following optional values:
126
-	 *        - array 'urlParams' the parameters which were matched from the URL
127
-	 *        - array 'get' the $_GET array
128
-	 *        - array|string 'post' the $_POST array or JSON string
129
-	 *        - array 'files' the $_FILES array
130
-	 *        - array 'server' the $_SERVER array
131
-	 *        - array 'env' the $_ENV array
132
-	 *        - array 'cookies' the $_COOKIE array
133
-	 *        - string 'method' the request method (GET, POST etc)
134
-	 *        - string|false 'requesttoken' the requesttoken or false when not available
135
-	 * @param ISecureRandom $secureRandom
136
-	 * @param IConfig $config
137
-	 * @param CsrfTokenManager|null $csrfTokenManager
138
-	 * @param string $stream
139
-	 * @see http://www.php.net/manual/en/reserved.variables.php
140
-	 */
141
-	public function __construct(array $vars= [],
142
-								ISecureRandom $secureRandom = null,
143
-								IConfig $config,
144
-								CsrfTokenManager $csrfTokenManager = null,
145
-								string $stream = 'php://input') {
146
-		$this->inputStream = $stream;
147
-		$this->items['params'] = [];
148
-		$this->secureRandom = $secureRandom;
149
-		$this->config = $config;
150
-		$this->csrfTokenManager = $csrfTokenManager;
151
-
152
-		if(!array_key_exists('method', $vars)) {
153
-			$vars['method'] = 'GET';
154
-		}
155
-
156
-		foreach($this->allowedKeys as $name) {
157
-			$this->items[$name] = isset($vars[$name])
158
-				? $vars[$name]
159
-				: [];
160
-		}
161
-
162
-		$this->items['parameters'] = array_merge(
163
-			$this->items['get'],
164
-			$this->items['post'],
165
-			$this->items['urlParams'],
166
-			$this->items['params']
167
-		);
168
-
169
-	}
170
-	/**
171
-	 * @param array $parameters
172
-	 */
173
-	public function setUrlParameters(array $parameters) {
174
-		$this->items['urlParams'] = $parameters;
175
-		$this->items['parameters'] = array_merge(
176
-			$this->items['parameters'],
177
-			$this->items['urlParams']
178
-		);
179
-	}
180
-
181
-	/**
182
-	 * Countable method
183
-	 * @return int
184
-	 */
185
-	public function count(): int {
186
-		return \count($this->items['parameters']);
187
-	}
188
-
189
-	/**
190
-	 * ArrayAccess methods
191
-	 *
192
-	 * Gives access to the combined GET, POST and urlParams arrays
193
-	 *
194
-	 * Examples:
195
-	 *
196
-	 * $var = $request['myvar'];
197
-	 *
198
-	 * or
199
-	 *
200
-	 * if(!isset($request['myvar']) {
201
-	 * 	// Do something
202
-	 * }
203
-	 *
204
-	 * $request['myvar'] = 'something'; // This throws an exception.
205
-	 *
206
-	 * @param string $offset The key to lookup
207
-	 * @return boolean
208
-	 */
209
-	public function offsetExists($offset): bool {
210
-		return isset($this->items['parameters'][$offset]);
211
-	}
212
-
213
-	/**
214
-	 * @see offsetExists
215
-	 * @param string $offset
216
-	 * @return mixed
217
-	 */
218
-	public function offsetGet($offset) {
219
-		return isset($this->items['parameters'][$offset])
220
-			? $this->items['parameters'][$offset]
221
-			: null;
222
-	}
223
-
224
-	/**
225
-	 * @see offsetExists
226
-	 * @param string $offset
227
-	 * @param mixed $value
228
-	 */
229
-	public function offsetSet($offset, $value) {
230
-		throw new \RuntimeException('You cannot change the contents of the request object');
231
-	}
232
-
233
-	/**
234
-	 * @see offsetExists
235
-	 * @param string $offset
236
-	 */
237
-	public function offsetUnset($offset) {
238
-		throw new \RuntimeException('You cannot change the contents of the request object');
239
-	}
240
-
241
-	/**
242
-	 * Magic property accessors
243
-	 * @param string $name
244
-	 * @param mixed $value
245
-	 */
246
-	public function __set($name, $value) {
247
-		throw new \RuntimeException('You cannot change the contents of the request object');
248
-	}
249
-
250
-	/**
251
-	 * Access request variables by method and name.
252
-	 * Examples:
253
-	 *
254
-	 * $request->post['myvar']; // Only look for POST variables
255
-	 * $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
256
-	 * Looks in the combined GET, POST and urlParams array.
257
-	 *
258
-	 * If you access e.g. ->post but the current HTTP request method
259
-	 * is GET a \LogicException will be thrown.
260
-	 *
261
-	 * @param string $name The key to look for.
262
-	 * @throws \LogicException
263
-	 * @return mixed|null
264
-	 */
265
-	public function __get($name) {
266
-		switch($name) {
267
-			case 'put':
268
-			case 'patch':
269
-			case 'get':
270
-			case 'post':
271
-				if($this->method !== strtoupper($name)) {
272
-					throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
273
-				}
274
-				return $this->getContent();
275
-			case 'files':
276
-			case 'server':
277
-			case 'env':
278
-			case 'cookies':
279
-			case 'urlParams':
280
-			case 'method':
281
-				return isset($this->items[$name])
282
-					? $this->items[$name]
283
-					: null;
284
-			case 'parameters':
285
-			case 'params':
286
-				return $this->getContent();
287
-			default;
288
-				return isset($this[$name])
289
-					? $this[$name]
290
-					: null;
291
-		}
292
-	}
293
-
294
-	/**
295
-	 * @param string $name
296
-	 * @return bool
297
-	 */
298
-	public function __isset($name) {
299
-		if (\in_array($name, $this->allowedKeys, true)) {
300
-			return true;
301
-		}
302
-		return isset($this->items['parameters'][$name]);
303
-	}
304
-
305
-	/**
306
-	 * @param string $id
307
-	 */
308
-	public function __unset($id) {
309
-		throw new \RuntimeException('You cannot change the contents of the request object');
310
-	}
311
-
312
-	/**
313
-	 * Returns the value for a specific http header.
314
-	 *
315
-	 * This method returns null if the header did not exist.
316
-	 *
317
-	 * @param string $name
318
-	 * @return string
319
-	 */
320
-	public function getHeader(string $name): string {
321
-
322
-		$name = strtoupper(str_replace('-', '_',$name));
323
-		if (isset($this->server['HTTP_' . $name])) {
324
-			return $this->server['HTTP_' . $name];
325
-		}
326
-
327
-		// There's a few headers that seem to end up in the top-level
328
-		// server array.
329
-		switch ($name) {
330
-			case 'CONTENT_TYPE':
331
-			case 'CONTENT_LENGTH':
332
-			case 'REMOTE_ADDR':
333
-				if (isset($this->server[$name])) {
334
-					return $this->server[$name];
335
-				}
336
-				break;
337
-		}
338
-
339
-		return '';
340
-	}
341
-
342
-	/**
343
-	 * Lets you access post and get parameters by the index
344
-	 * In case of json requests the encoded json body is accessed
345
-	 *
346
-	 * @param string $key the key which you want to access in the URL Parameter
347
-	 *                     placeholder, $_POST or $_GET array.
348
-	 *                     The priority how they're returned is the following:
349
-	 *                     1. URL parameters
350
-	 *                     2. POST parameters
351
-	 *                     3. GET parameters
352
-	 * @param mixed $default If the key is not found, this value will be returned
353
-	 * @return mixed the content of the array
354
-	 */
355
-	public function getParam(string $key, $default = null) {
356
-		return isset($this->parameters[$key])
357
-			? $this->parameters[$key]
358
-			: $default;
359
-	}
360
-
361
-	/**
362
-	 * Returns all params that were received, be it from the request
363
-	 * (as GET or POST) or throuh the URL by the route
364
-	 * @return array the array with all parameters
365
-	 */
366
-	public function getParams(): array {
367
-		return is_array($this->parameters) ? $this->parameters : [];
368
-	}
369
-
370
-	/**
371
-	 * Returns the method of the request
372
-	 * @return string the method of the request (POST, GET, etc)
373
-	 */
374
-	public function getMethod(): string {
375
-		return $this->method;
376
-	}
377
-
378
-	/**
379
-	 * Shortcut for accessing an uploaded file through the $_FILES array
380
-	 * @param string $key the key that will be taken from the $_FILES array
381
-	 * @return array the file in the $_FILES element
382
-	 */
383
-	public function getUploadedFile(string $key) {
384
-		return isset($this->files[$key]) ? $this->files[$key] : null;
385
-	}
386
-
387
-	/**
388
-	 * Shortcut for getting env variables
389
-	 * @param string $key the key that will be taken from the $_ENV array
390
-	 * @return array the value in the $_ENV element
391
-	 */
392
-	public function getEnv(string $key) {
393
-		return isset($this->env[$key]) ? $this->env[$key] : null;
394
-	}
395
-
396
-	/**
397
-	 * Shortcut for getting cookie variables
398
-	 * @param string $key the key that will be taken from the $_COOKIE array
399
-	 * @return string the value in the $_COOKIE element
400
-	 */
401
-	public function getCookie(string $key) {
402
-		return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
403
-	}
404
-
405
-	/**
406
-	 * Returns the request body content.
407
-	 *
408
-	 * If the HTTP request method is PUT and the body
409
-	 * not application/x-www-form-urlencoded or application/json a stream
410
-	 * resource is returned, otherwise an array.
411
-	 *
412
-	 * @return array|string|resource The request body content or a resource to read the body stream.
413
-	 *
414
-	 * @throws \LogicException
415
-	 */
416
-	protected function getContent() {
417
-		// If the content can't be parsed into an array then return a stream resource.
418
-		if ($this->method === 'PUT'
419
-			&& $this->getHeader('Content-Length') !== '0'
420
-			&& $this->getHeader('Content-Length') !== ''
421
-			&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
422
-			&& strpos($this->getHeader('Content-Type'), 'application/json') === false
423
-		) {
424
-			if ($this->content === false) {
425
-				throw new \LogicException(
426
-					'"put" can only be accessed once if not '
427
-					. 'application/x-www-form-urlencoded or application/json.'
428
-				);
429
-			}
430
-			$this->content = false;
431
-			return fopen($this->inputStream, 'rb');
432
-		} else {
433
-			$this->decodeContent();
434
-			return $this->items['parameters'];
435
-		}
436
-	}
437
-
438
-	/**
439
-	 * Attempt to decode the content and populate parameters
440
-	 */
441
-	protected function decodeContent() {
442
-		if ($this->contentDecoded) {
443
-			return;
444
-		}
445
-		$params = [];
446
-
447
-		// 'application/json' must be decoded manually.
448
-		if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
449
-			$params = json_decode(file_get_contents($this->inputStream), true);
450
-			if($params !== null && \count($params) > 0) {
451
-				$this->items['params'] = $params;
452
-				if($this->method === 'POST') {
453
-					$this->items['post'] = $params;
454
-				}
455
-			}
456
-
457
-		// Handle application/x-www-form-urlencoded for methods other than GET
458
-		// or post correctly
459
-		} elseif($this->method !== 'GET'
460
-				&& $this->method !== 'POST'
461
-				&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
462
-
463
-			parse_str(file_get_contents($this->inputStream), $params);
464
-			if(\is_array($params)) {
465
-				$this->items['params'] = $params;
466
-			}
467
-		}
468
-
469
-		if (\is_array($params)) {
470
-			$this->items['parameters'] = array_merge($this->items['parameters'], $params);
471
-		}
472
-		$this->contentDecoded = true;
473
-	}
474
-
475
-
476
-	/**
477
-	 * Checks if the CSRF check was correct
478
-	 * @return bool true if CSRF check passed
479
-	 */
480
-	public function passesCSRFCheck(): bool {
481
-		if($this->csrfTokenManager === null) {
482
-			return false;
483
-		}
484
-
485
-		if(!$this->passesStrictCookieCheck()) {
486
-			return false;
487
-		}
488
-
489
-		if (isset($this->items['get']['requesttoken'])) {
490
-			$token = $this->items['get']['requesttoken'];
491
-		} elseif (isset($this->items['post']['requesttoken'])) {
492
-			$token = $this->items['post']['requesttoken'];
493
-		} elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
494
-			$token = $this->items['server']['HTTP_REQUESTTOKEN'];
495
-		} else {
496
-			//no token found.
497
-			return false;
498
-		}
499
-		$token = new CsrfToken($token);
500
-
501
-		return $this->csrfTokenManager->isTokenValid($token);
502
-	}
503
-
504
-	/**
505
-	 * Whether the cookie checks are required
506
-	 *
507
-	 * @return bool
508
-	 */
509
-	private function cookieCheckRequired(): bool {
510
-		if ($this->getHeader('OCS-APIREQUEST')) {
511
-			return false;
512
-		}
513
-		if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
514
-			return false;
515
-		}
516
-
517
-		return true;
518
-	}
519
-
520
-	/**
521
-	 * Wrapper around session_get_cookie_params
522
-	 *
523
-	 * @return array
524
-	 */
525
-	public function getCookieParams(): array {
526
-		return session_get_cookie_params();
527
-	}
528
-
529
-	/**
530
-	 * Appends the __Host- prefix to the cookie if applicable
531
-	 *
532
-	 * @param string $name
533
-	 * @return string
534
-	 */
535
-	protected function getProtectedCookieName(string $name): string {
536
-		$cookieParams = $this->getCookieParams();
537
-		$prefix = '';
538
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
539
-			$prefix = '__Host-';
540
-		}
541
-
542
-		return $prefix.$name;
543
-	}
544
-
545
-	/**
546
-	 * Checks if the strict cookie has been sent with the request if the request
547
-	 * is including any cookies.
548
-	 *
549
-	 * @return bool
550
-	 * @since 9.1.0
551
-	 */
552
-	public function passesStrictCookieCheck(): bool {
553
-		if(!$this->cookieCheckRequired()) {
554
-			return true;
555
-		}
556
-
557
-		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
558
-		if($this->getCookie($cookieName) === 'true'
559
-			&& $this->passesLaxCookieCheck()) {
560
-			return true;
561
-		}
562
-		return false;
563
-	}
564
-
565
-	/**
566
-	 * Checks if the lax cookie has been sent with the request if the request
567
-	 * is including any cookies.
568
-	 *
569
-	 * @return bool
570
-	 * @since 9.1.0
571
-	 */
572
-	public function passesLaxCookieCheck(): bool {
573
-		if(!$this->cookieCheckRequired()) {
574
-			return true;
575
-		}
576
-
577
-		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
578
-		if($this->getCookie($cookieName) === 'true') {
579
-			return true;
580
-		}
581
-		return false;
582
-	}
583
-
584
-
585
-	/**
586
-	 * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
587
-	 * If `mod_unique_id` is installed this value will be taken.
588
-	 * @return string
589
-	 */
590
-	public function getId(): string {
591
-		if(isset($this->server['UNIQUE_ID'])) {
592
-			return $this->server['UNIQUE_ID'];
593
-		}
594
-
595
-		if(empty($this->requestId)) {
596
-			$validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
597
-			$this->requestId = $this->secureRandom->generate(20, $validChars);
598
-		}
599
-
600
-		return $this->requestId;
601
-	}
602
-
603
-	/**
604
-	 * Checks if given $remoteAddress matches given $trustedProxy.
605
-	 * If $trustedProxy is an IPv4 IP range given in CIDR notation, true will be returned if
606
-	 * $remoteAddress is an IPv4 address within that IP range.
607
-	 * Otherwise $remoteAddress will be compared to $trustedProxy literally and the result
608
-	 * will be returned.
609
-	 * @return boolean true if $remoteAddress matches $trustedProxy, false otherwise
610
-	 */
611
-	protected function matchesTrustedProxy($trustedProxy, $remoteAddress) {
612
-		$cidrre = '/^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\/([0-9]{1,2})$/';
613
-
614
-		if (preg_match($cidrre, $trustedProxy, $match)) {
615
-			$net = $match[1];
616
-			$shiftbits = min(32, max(0, 32 - intval($match[2])));
617
-			$netnum = ip2long($net) >> $shiftbits;
618
-			$ipnum = ip2long($remoteAddress) >> $shiftbits;
619
-
620
-			return $ipnum === $netnum;
621
-		}
622
-
623
-		return $trustedProxy === $remoteAddress;
624
-	}
625
-
626
-	/**
627
-	 * Checks if given $remoteAddress matches any entry in the given array $trustedProxies.
628
-	 * For details regarding what "match" means, refer to `matchesTrustedProxy`.
629
-	 * @return boolean true if $remoteAddress matches any entry in $trustedProxies, false otherwise
630
-	 */
631
-	protected function isTrustedProxy($trustedProxies, $remoteAddress) {
632
-		foreach ($trustedProxies as $tp) {
633
-			if ($this->matchesTrustedProxy($tp, $remoteAddress)) {
634
-				return true;
635
-			}
636
-		}
637
-
638
-		return false;
639
-	}
640
-
641
-	/**
642
-	 * Returns the remote address, if the connection came from a trusted proxy
643
-	 * and `forwarded_for_headers` has been configured then the IP address
644
-	 * specified in this header will be returned instead.
645
-	 * Do always use this instead of $_SERVER['REMOTE_ADDR']
646
-	 * @return string IP address
647
-	 */
648
-	public function getRemoteAddress(): string {
649
-		$remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
650
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
651
-
652
-		if(\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) {
653
-			$forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
654
-				'HTTP_X_FORWARDED_FOR'
655
-				// only have one default, so we cannot ship an insecure product out of the box
656
-			]);
657
-
658
-			foreach($forwardedForHeaders as $header) {
659
-				if(isset($this->server[$header])) {
660
-					foreach(explode(',', $this->server[$header]) as $IP) {
661
-						$IP = trim($IP);
662
-						if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
663
-							return $IP;
664
-						}
665
-					}
666
-				}
667
-			}
668
-		}
669
-
670
-		return $remoteAddress;
671
-	}
672
-
673
-	/**
674
-	 * Check overwrite condition
675
-	 * @param string $type
676
-	 * @return bool
677
-	 */
678
-	private function isOverwriteCondition(string $type = ''): bool {
679
-		$regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
680
-		$remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
681
-		return $regex === '//' || preg_match($regex, $remoteAddr) === 1
682
-		|| $type !== 'protocol';
683
-	}
684
-
685
-	/**
686
-	 * Returns the server protocol. It respects one or more reverse proxies servers
687
-	 * and load balancers
688
-	 * @return string Server protocol (http or https)
689
-	 */
690
-	public function getServerProtocol(): string {
691
-		if($this->config->getSystemValue('overwriteprotocol') !== ''
692
-			&& $this->isOverwriteCondition('protocol')) {
693
-			return $this->config->getSystemValue('overwriteprotocol');
694
-		}
695
-
696
-		if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
697
-			if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
698
-				$parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
699
-				$proto = strtolower(trim($parts[0]));
700
-			} else {
701
-				$proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
702
-			}
703
-
704
-			// Verify that the protocol is always HTTP or HTTPS
705
-			// default to http if an invalid value is provided
706
-			return $proto === 'https' ? 'https' : 'http';
707
-		}
708
-
709
-		if (isset($this->server['HTTPS'])
710
-			&& $this->server['HTTPS'] !== null
711
-			&& $this->server['HTTPS'] !== 'off'
712
-			&& $this->server['HTTPS'] !== '') {
713
-			return 'https';
714
-		}
715
-
716
-		return 'http';
717
-	}
718
-
719
-	/**
720
-	 * Returns the used HTTP protocol.
721
-	 *
722
-	 * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
723
-	 */
724
-	public function getHttpProtocol(): string {
725
-		$claimedProtocol = $this->server['SERVER_PROTOCOL'];
726
-
727
-		if (\is_string($claimedProtocol)) {
728
-			$claimedProtocol = strtoupper($claimedProtocol);
729
-		}
730
-
731
-		$validProtocols = [
732
-			'HTTP/1.0',
733
-			'HTTP/1.1',
734
-			'HTTP/2',
735
-		];
736
-
737
-		if(\in_array($claimedProtocol, $validProtocols, true)) {
738
-			return $claimedProtocol;
739
-		}
740
-
741
-		return 'HTTP/1.1';
742
-	}
743
-
744
-	/**
745
-	 * Returns the request uri, even if the website uses one or more
746
-	 * reverse proxies
747
-	 * @return string
748
-	 */
749
-	public function getRequestUri(): string {
750
-		$uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
751
-		if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
752
-			$uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
753
-		}
754
-		return $uri;
755
-	}
756
-
757
-	/**
758
-	 * Get raw PathInfo from request (not urldecoded)
759
-	 * @throws \Exception
760
-	 * @return string Path info
761
-	 */
762
-	public function getRawPathInfo(): string {
763
-		$requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
764
-		// remove too many slashes - can be caused by reverse proxy configuration
765
-		$requestUri = preg_replace('%/{2,}%', '/', $requestUri);
766
-
767
-		// Remove the query string from REQUEST_URI
768
-		if ($pos = strpos($requestUri, '?')) {
769
-			$requestUri = substr($requestUri, 0, $pos);
770
-		}
771
-
772
-		$scriptName = $this->server['SCRIPT_NAME'];
773
-		$pathInfo = $requestUri;
774
-
775
-		// strip off the script name's dir and file name
776
-		// FIXME: Sabre does not really belong here
777
-		list($path, $name) = \Sabre\Uri\split($scriptName);
778
-		if (!empty($path)) {
779
-			if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
780
-				$pathInfo = substr($pathInfo, \strlen($path));
781
-			} else {
782
-				throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
783
-			}
784
-		}
785
-		if ($name === null) {
786
-			$name = '';
787
-		}
788
-
789
-		if (strpos($pathInfo, '/'.$name) === 0) {
790
-			$pathInfo = substr($pathInfo, \strlen($name) + 1);
791
-		}
792
-		if ($name !== '' && strpos($pathInfo, $name) === 0) {
793
-			$pathInfo = substr($pathInfo, \strlen($name));
794
-		}
795
-		if($pathInfo === false || $pathInfo === '/'){
796
-			return '';
797
-		} else {
798
-			return $pathInfo;
799
-		}
800
-	}
801
-
802
-	/**
803
-	 * Get PathInfo from request
804
-	 * @throws \Exception
805
-	 * @return string|false Path info or false when not found
806
-	 */
807
-	public function getPathInfo() {
808
-		$pathInfo = $this->getRawPathInfo();
809
-		// following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
810
-		$pathInfo = rawurldecode($pathInfo);
811
-		$encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
812
-
813
-		switch($encoding) {
814
-			case 'ISO-8859-1':
815
-				$pathInfo = utf8_encode($pathInfo);
816
-		}
817
-		// end copy
818
-
819
-		return $pathInfo;
820
-	}
821
-
822
-	/**
823
-	 * Returns the script name, even if the website uses one or more
824
-	 * reverse proxies
825
-	 * @return string the script name
826
-	 */
827
-	public function getScriptName(): string {
828
-		$name = $this->server['SCRIPT_NAME'];
829
-		$overwriteWebRoot =  $this->config->getSystemValue('overwritewebroot');
830
-		if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
831
-			// FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
832
-			$serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
833
-			$suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
834
-			$name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
835
-		}
836
-		return $name;
837
-	}
838
-
839
-	/**
840
-	 * Checks whether the user agent matches a given regex
841
-	 * @param array $agent array of agent names
842
-	 * @return bool true if at least one of the given agent matches, false otherwise
843
-	 */
844
-	public function isUserAgent(array $agent): bool {
845
-		if (!isset($this->server['HTTP_USER_AGENT'])) {
846
-			return false;
847
-		}
848
-		foreach ($agent as $regex) {
849
-			if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
850
-				return true;
851
-			}
852
-		}
853
-		return false;
854
-	}
855
-
856
-	/**
857
-	 * Returns the unverified server host from the headers without checking
858
-	 * whether it is a trusted domain
859
-	 * @return string Server host
860
-	 */
861
-	public function getInsecureServerHost(): string {
862
-		if ($this->fromTrustedProxy() && $this->getOverwriteHost() !== null) {
863
-			return $this->getOverwriteHost();
864
-		}
865
-
866
-		$host = 'localhost';
867
-		if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_HOST'])) {
868
-			if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
869
-				$parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
870
-				$host = trim(current($parts));
871
-			} else {
872
-				$host = $this->server['HTTP_X_FORWARDED_HOST'];
873
-			}
874
-		} else {
875
-			if (isset($this->server['HTTP_HOST'])) {
876
-				$host = $this->server['HTTP_HOST'];
877
-			} else if (isset($this->server['SERVER_NAME'])) {
878
-				$host = $this->server['SERVER_NAME'];
879
-			}
880
-		}
881
-
882
-		return $host;
883
-	}
884
-
885
-
886
-	/**
887
-	 * Returns the server host from the headers, or the first configured
888
-	 * trusted domain if the host isn't in the trusted list
889
-	 * @return string Server host
890
-	 */
891
-	public function getServerHost(): string {
892
-		// overwritehost is always trusted
893
-		$host = $this->getOverwriteHost();
894
-		if ($host !== null) {
895
-			return $host;
896
-		}
897
-
898
-		// get the host from the headers
899
-		$host = $this->getInsecureServerHost();
900
-
901
-		// Verify that the host is a trusted domain if the trusted domains
902
-		// are defined
903
-		// If no trusted domain is provided the first trusted domain is returned
904
-		$trustedDomainHelper = new TrustedDomainHelper($this->config);
905
-		if ($trustedDomainHelper->isTrustedDomain($host)) {
906
-			return $host;
907
-		}
908
-
909
-		$trustedList = (array)$this->config->getSystemValue('trusted_domains', []);
910
-		if (count($trustedList) > 0) {
911
-			return reset($trustedList);
912
-		}
913
-
914
-		return '';
915
-	}
916
-
917
-	/**
918
-	 * Returns the overwritehost setting from the config if set and
919
-	 * if the overwrite condition is met
920
-	 * @return string|null overwritehost value or null if not defined or the defined condition
921
-	 * isn't met
922
-	 */
923
-	private function getOverwriteHost() {
924
-		if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
925
-			return $this->config->getSystemValue('overwritehost');
926
-		}
927
-		return null;
928
-	}
929
-
930
-	private function fromTrustedProxy(): bool {
931
-		$remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
932
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
933
-
934
-		return \is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress);
935
-	}
68
+    const USER_AGENT_IE = '/(MSIE)|(Trident)/';
69
+    // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
70
+    const USER_AGENT_MS_EDGE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+ Edge\/[0-9.]+$/';
71
+    // Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
72
+    const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
73
+    // Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
74
+    const USER_AGENT_CHROME = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)( Ubuntu Chromium\/[0-9.]+|) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+( (Vivaldi|Brave|OPR)\/[0-9.]+|)$/';
75
+    // Safari User Agent from http://www.useragentstring.com/pages/Safari/
76
+    const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
77
+    // Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
78
+    const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
79
+    const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
80
+    const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|::1)$/';
81
+
82
+    /**
83
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_IOS instead
84
+     */
85
+    const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
86
+    /**
87
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_ANDROID instead
88
+     */
89
+    const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/';
90
+    /**
91
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_DESKTOP instead
92
+     */
93
+    const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
94
+
95
+    protected $inputStream;
96
+    protected $content;
97
+    protected $items = [];
98
+    protected $allowedKeys = [
99
+        'get',
100
+        'post',
101
+        'files',
102
+        'server',
103
+        'env',
104
+        'cookies',
105
+        'urlParams',
106
+        'parameters',
107
+        'method',
108
+        'requesttoken',
109
+    ];
110
+    /** @var ISecureRandom */
111
+    protected $secureRandom;
112
+    /** @var IConfig */
113
+    protected $config;
114
+    /** @var string */
115
+    protected $requestId = '';
116
+    /** @var ICrypto */
117
+    protected $crypto;
118
+    /** @var CsrfTokenManager|null */
119
+    protected $csrfTokenManager;
120
+
121
+    /** @var bool */
122
+    protected $contentDecoded = false;
123
+
124
+    /**
125
+     * @param array $vars An associative array with the following optional values:
126
+     *        - array 'urlParams' the parameters which were matched from the URL
127
+     *        - array 'get' the $_GET array
128
+     *        - array|string 'post' the $_POST array or JSON string
129
+     *        - array 'files' the $_FILES array
130
+     *        - array 'server' the $_SERVER array
131
+     *        - array 'env' the $_ENV array
132
+     *        - array 'cookies' the $_COOKIE array
133
+     *        - string 'method' the request method (GET, POST etc)
134
+     *        - string|false 'requesttoken' the requesttoken or false when not available
135
+     * @param ISecureRandom $secureRandom
136
+     * @param IConfig $config
137
+     * @param CsrfTokenManager|null $csrfTokenManager
138
+     * @param string $stream
139
+     * @see http://www.php.net/manual/en/reserved.variables.php
140
+     */
141
+    public function __construct(array $vars= [],
142
+                                ISecureRandom $secureRandom = null,
143
+                                IConfig $config,
144
+                                CsrfTokenManager $csrfTokenManager = null,
145
+                                string $stream = 'php://input') {
146
+        $this->inputStream = $stream;
147
+        $this->items['params'] = [];
148
+        $this->secureRandom = $secureRandom;
149
+        $this->config = $config;
150
+        $this->csrfTokenManager = $csrfTokenManager;
151
+
152
+        if(!array_key_exists('method', $vars)) {
153
+            $vars['method'] = 'GET';
154
+        }
155
+
156
+        foreach($this->allowedKeys as $name) {
157
+            $this->items[$name] = isset($vars[$name])
158
+                ? $vars[$name]
159
+                : [];
160
+        }
161
+
162
+        $this->items['parameters'] = array_merge(
163
+            $this->items['get'],
164
+            $this->items['post'],
165
+            $this->items['urlParams'],
166
+            $this->items['params']
167
+        );
168
+
169
+    }
170
+    /**
171
+     * @param array $parameters
172
+     */
173
+    public function setUrlParameters(array $parameters) {
174
+        $this->items['urlParams'] = $parameters;
175
+        $this->items['parameters'] = array_merge(
176
+            $this->items['parameters'],
177
+            $this->items['urlParams']
178
+        );
179
+    }
180
+
181
+    /**
182
+     * Countable method
183
+     * @return int
184
+     */
185
+    public function count(): int {
186
+        return \count($this->items['parameters']);
187
+    }
188
+
189
+    /**
190
+     * ArrayAccess methods
191
+     *
192
+     * Gives access to the combined GET, POST and urlParams arrays
193
+     *
194
+     * Examples:
195
+     *
196
+     * $var = $request['myvar'];
197
+     *
198
+     * or
199
+     *
200
+     * if(!isset($request['myvar']) {
201
+     * 	// Do something
202
+     * }
203
+     *
204
+     * $request['myvar'] = 'something'; // This throws an exception.
205
+     *
206
+     * @param string $offset The key to lookup
207
+     * @return boolean
208
+     */
209
+    public function offsetExists($offset): bool {
210
+        return isset($this->items['parameters'][$offset]);
211
+    }
212
+
213
+    /**
214
+     * @see offsetExists
215
+     * @param string $offset
216
+     * @return mixed
217
+     */
218
+    public function offsetGet($offset) {
219
+        return isset($this->items['parameters'][$offset])
220
+            ? $this->items['parameters'][$offset]
221
+            : null;
222
+    }
223
+
224
+    /**
225
+     * @see offsetExists
226
+     * @param string $offset
227
+     * @param mixed $value
228
+     */
229
+    public function offsetSet($offset, $value) {
230
+        throw new \RuntimeException('You cannot change the contents of the request object');
231
+    }
232
+
233
+    /**
234
+     * @see offsetExists
235
+     * @param string $offset
236
+     */
237
+    public function offsetUnset($offset) {
238
+        throw new \RuntimeException('You cannot change the contents of the request object');
239
+    }
240
+
241
+    /**
242
+     * Magic property accessors
243
+     * @param string $name
244
+     * @param mixed $value
245
+     */
246
+    public function __set($name, $value) {
247
+        throw new \RuntimeException('You cannot change the contents of the request object');
248
+    }
249
+
250
+    /**
251
+     * Access request variables by method and name.
252
+     * Examples:
253
+     *
254
+     * $request->post['myvar']; // Only look for POST variables
255
+     * $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
256
+     * Looks in the combined GET, POST and urlParams array.
257
+     *
258
+     * If you access e.g. ->post but the current HTTP request method
259
+     * is GET a \LogicException will be thrown.
260
+     *
261
+     * @param string $name The key to look for.
262
+     * @throws \LogicException
263
+     * @return mixed|null
264
+     */
265
+    public function __get($name) {
266
+        switch($name) {
267
+            case 'put':
268
+            case 'patch':
269
+            case 'get':
270
+            case 'post':
271
+                if($this->method !== strtoupper($name)) {
272
+                    throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
273
+                }
274
+                return $this->getContent();
275
+            case 'files':
276
+            case 'server':
277
+            case 'env':
278
+            case 'cookies':
279
+            case 'urlParams':
280
+            case 'method':
281
+                return isset($this->items[$name])
282
+                    ? $this->items[$name]
283
+                    : null;
284
+            case 'parameters':
285
+            case 'params':
286
+                return $this->getContent();
287
+            default;
288
+                return isset($this[$name])
289
+                    ? $this[$name]
290
+                    : null;
291
+        }
292
+    }
293
+
294
+    /**
295
+     * @param string $name
296
+     * @return bool
297
+     */
298
+    public function __isset($name) {
299
+        if (\in_array($name, $this->allowedKeys, true)) {
300
+            return true;
301
+        }
302
+        return isset($this->items['parameters'][$name]);
303
+    }
304
+
305
+    /**
306
+     * @param string $id
307
+     */
308
+    public function __unset($id) {
309
+        throw new \RuntimeException('You cannot change the contents of the request object');
310
+    }
311
+
312
+    /**
313
+     * Returns the value for a specific http header.
314
+     *
315
+     * This method returns null if the header did not exist.
316
+     *
317
+     * @param string $name
318
+     * @return string
319
+     */
320
+    public function getHeader(string $name): string {
321
+
322
+        $name = strtoupper(str_replace('-', '_',$name));
323
+        if (isset($this->server['HTTP_' . $name])) {
324
+            return $this->server['HTTP_' . $name];
325
+        }
326
+
327
+        // There's a few headers that seem to end up in the top-level
328
+        // server array.
329
+        switch ($name) {
330
+            case 'CONTENT_TYPE':
331
+            case 'CONTENT_LENGTH':
332
+            case 'REMOTE_ADDR':
333
+                if (isset($this->server[$name])) {
334
+                    return $this->server[$name];
335
+                }
336
+                break;
337
+        }
338
+
339
+        return '';
340
+    }
341
+
342
+    /**
343
+     * Lets you access post and get parameters by the index
344
+     * In case of json requests the encoded json body is accessed
345
+     *
346
+     * @param string $key the key which you want to access in the URL Parameter
347
+     *                     placeholder, $_POST or $_GET array.
348
+     *                     The priority how they're returned is the following:
349
+     *                     1. URL parameters
350
+     *                     2. POST parameters
351
+     *                     3. GET parameters
352
+     * @param mixed $default If the key is not found, this value will be returned
353
+     * @return mixed the content of the array
354
+     */
355
+    public function getParam(string $key, $default = null) {
356
+        return isset($this->parameters[$key])
357
+            ? $this->parameters[$key]
358
+            : $default;
359
+    }
360
+
361
+    /**
362
+     * Returns all params that were received, be it from the request
363
+     * (as GET or POST) or throuh the URL by the route
364
+     * @return array the array with all parameters
365
+     */
366
+    public function getParams(): array {
367
+        return is_array($this->parameters) ? $this->parameters : [];
368
+    }
369
+
370
+    /**
371
+     * Returns the method of the request
372
+     * @return string the method of the request (POST, GET, etc)
373
+     */
374
+    public function getMethod(): string {
375
+        return $this->method;
376
+    }
377
+
378
+    /**
379
+     * Shortcut for accessing an uploaded file through the $_FILES array
380
+     * @param string $key the key that will be taken from the $_FILES array
381
+     * @return array the file in the $_FILES element
382
+     */
383
+    public function getUploadedFile(string $key) {
384
+        return isset($this->files[$key]) ? $this->files[$key] : null;
385
+    }
386
+
387
+    /**
388
+     * Shortcut for getting env variables
389
+     * @param string $key the key that will be taken from the $_ENV array
390
+     * @return array the value in the $_ENV element
391
+     */
392
+    public function getEnv(string $key) {
393
+        return isset($this->env[$key]) ? $this->env[$key] : null;
394
+    }
395
+
396
+    /**
397
+     * Shortcut for getting cookie variables
398
+     * @param string $key the key that will be taken from the $_COOKIE array
399
+     * @return string the value in the $_COOKIE element
400
+     */
401
+    public function getCookie(string $key) {
402
+        return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
403
+    }
404
+
405
+    /**
406
+     * Returns the request body content.
407
+     *
408
+     * If the HTTP request method is PUT and the body
409
+     * not application/x-www-form-urlencoded or application/json a stream
410
+     * resource is returned, otherwise an array.
411
+     *
412
+     * @return array|string|resource The request body content or a resource to read the body stream.
413
+     *
414
+     * @throws \LogicException
415
+     */
416
+    protected function getContent() {
417
+        // If the content can't be parsed into an array then return a stream resource.
418
+        if ($this->method === 'PUT'
419
+            && $this->getHeader('Content-Length') !== '0'
420
+            && $this->getHeader('Content-Length') !== ''
421
+            && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
422
+            && strpos($this->getHeader('Content-Type'), 'application/json') === false
423
+        ) {
424
+            if ($this->content === false) {
425
+                throw new \LogicException(
426
+                    '"put" can only be accessed once if not '
427
+                    . 'application/x-www-form-urlencoded or application/json.'
428
+                );
429
+            }
430
+            $this->content = false;
431
+            return fopen($this->inputStream, 'rb');
432
+        } else {
433
+            $this->decodeContent();
434
+            return $this->items['parameters'];
435
+        }
436
+    }
437
+
438
+    /**
439
+     * Attempt to decode the content and populate parameters
440
+     */
441
+    protected function decodeContent() {
442
+        if ($this->contentDecoded) {
443
+            return;
444
+        }
445
+        $params = [];
446
+
447
+        // 'application/json' must be decoded manually.
448
+        if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
449
+            $params = json_decode(file_get_contents($this->inputStream), true);
450
+            if($params !== null && \count($params) > 0) {
451
+                $this->items['params'] = $params;
452
+                if($this->method === 'POST') {
453
+                    $this->items['post'] = $params;
454
+                }
455
+            }
456
+
457
+        // Handle application/x-www-form-urlencoded for methods other than GET
458
+        // or post correctly
459
+        } elseif($this->method !== 'GET'
460
+                && $this->method !== 'POST'
461
+                && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
462
+
463
+            parse_str(file_get_contents($this->inputStream), $params);
464
+            if(\is_array($params)) {
465
+                $this->items['params'] = $params;
466
+            }
467
+        }
468
+
469
+        if (\is_array($params)) {
470
+            $this->items['parameters'] = array_merge($this->items['parameters'], $params);
471
+        }
472
+        $this->contentDecoded = true;
473
+    }
474
+
475
+
476
+    /**
477
+     * Checks if the CSRF check was correct
478
+     * @return bool true if CSRF check passed
479
+     */
480
+    public function passesCSRFCheck(): bool {
481
+        if($this->csrfTokenManager === null) {
482
+            return false;
483
+        }
484
+
485
+        if(!$this->passesStrictCookieCheck()) {
486
+            return false;
487
+        }
488
+
489
+        if (isset($this->items['get']['requesttoken'])) {
490
+            $token = $this->items['get']['requesttoken'];
491
+        } elseif (isset($this->items['post']['requesttoken'])) {
492
+            $token = $this->items['post']['requesttoken'];
493
+        } elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
494
+            $token = $this->items['server']['HTTP_REQUESTTOKEN'];
495
+        } else {
496
+            //no token found.
497
+            return false;
498
+        }
499
+        $token = new CsrfToken($token);
500
+
501
+        return $this->csrfTokenManager->isTokenValid($token);
502
+    }
503
+
504
+    /**
505
+     * Whether the cookie checks are required
506
+     *
507
+     * @return bool
508
+     */
509
+    private function cookieCheckRequired(): bool {
510
+        if ($this->getHeader('OCS-APIREQUEST')) {
511
+            return false;
512
+        }
513
+        if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
514
+            return false;
515
+        }
516
+
517
+        return true;
518
+    }
519
+
520
+    /**
521
+     * Wrapper around session_get_cookie_params
522
+     *
523
+     * @return array
524
+     */
525
+    public function getCookieParams(): array {
526
+        return session_get_cookie_params();
527
+    }
528
+
529
+    /**
530
+     * Appends the __Host- prefix to the cookie if applicable
531
+     *
532
+     * @param string $name
533
+     * @return string
534
+     */
535
+    protected function getProtectedCookieName(string $name): string {
536
+        $cookieParams = $this->getCookieParams();
537
+        $prefix = '';
538
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
539
+            $prefix = '__Host-';
540
+        }
541
+
542
+        return $prefix.$name;
543
+    }
544
+
545
+    /**
546
+     * Checks if the strict cookie has been sent with the request if the request
547
+     * is including any cookies.
548
+     *
549
+     * @return bool
550
+     * @since 9.1.0
551
+     */
552
+    public function passesStrictCookieCheck(): bool {
553
+        if(!$this->cookieCheckRequired()) {
554
+            return true;
555
+        }
556
+
557
+        $cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
558
+        if($this->getCookie($cookieName) === 'true'
559
+            && $this->passesLaxCookieCheck()) {
560
+            return true;
561
+        }
562
+        return false;
563
+    }
564
+
565
+    /**
566
+     * Checks if the lax cookie has been sent with the request if the request
567
+     * is including any cookies.
568
+     *
569
+     * @return bool
570
+     * @since 9.1.0
571
+     */
572
+    public function passesLaxCookieCheck(): bool {
573
+        if(!$this->cookieCheckRequired()) {
574
+            return true;
575
+        }
576
+
577
+        $cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
578
+        if($this->getCookie($cookieName) === 'true') {
579
+            return true;
580
+        }
581
+        return false;
582
+    }
583
+
584
+
585
+    /**
586
+     * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
587
+     * If `mod_unique_id` is installed this value will be taken.
588
+     * @return string
589
+     */
590
+    public function getId(): string {
591
+        if(isset($this->server['UNIQUE_ID'])) {
592
+            return $this->server['UNIQUE_ID'];
593
+        }
594
+
595
+        if(empty($this->requestId)) {
596
+            $validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
597
+            $this->requestId = $this->secureRandom->generate(20, $validChars);
598
+        }
599
+
600
+        return $this->requestId;
601
+    }
602
+
603
+    /**
604
+     * Checks if given $remoteAddress matches given $trustedProxy.
605
+     * If $trustedProxy is an IPv4 IP range given in CIDR notation, true will be returned if
606
+     * $remoteAddress is an IPv4 address within that IP range.
607
+     * Otherwise $remoteAddress will be compared to $trustedProxy literally and the result
608
+     * will be returned.
609
+     * @return boolean true if $remoteAddress matches $trustedProxy, false otherwise
610
+     */
611
+    protected function matchesTrustedProxy($trustedProxy, $remoteAddress) {
612
+        $cidrre = '/^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\/([0-9]{1,2})$/';
613
+
614
+        if (preg_match($cidrre, $trustedProxy, $match)) {
615
+            $net = $match[1];
616
+            $shiftbits = min(32, max(0, 32 - intval($match[2])));
617
+            $netnum = ip2long($net) >> $shiftbits;
618
+            $ipnum = ip2long($remoteAddress) >> $shiftbits;
619
+
620
+            return $ipnum === $netnum;
621
+        }
622
+
623
+        return $trustedProxy === $remoteAddress;
624
+    }
625
+
626
+    /**
627
+     * Checks if given $remoteAddress matches any entry in the given array $trustedProxies.
628
+     * For details regarding what "match" means, refer to `matchesTrustedProxy`.
629
+     * @return boolean true if $remoteAddress matches any entry in $trustedProxies, false otherwise
630
+     */
631
+    protected function isTrustedProxy($trustedProxies, $remoteAddress) {
632
+        foreach ($trustedProxies as $tp) {
633
+            if ($this->matchesTrustedProxy($tp, $remoteAddress)) {
634
+                return true;
635
+            }
636
+        }
637
+
638
+        return false;
639
+    }
640
+
641
+    /**
642
+     * Returns the remote address, if the connection came from a trusted proxy
643
+     * and `forwarded_for_headers` has been configured then the IP address
644
+     * specified in this header will be returned instead.
645
+     * Do always use this instead of $_SERVER['REMOTE_ADDR']
646
+     * @return string IP address
647
+     */
648
+    public function getRemoteAddress(): string {
649
+        $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
650
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
651
+
652
+        if(\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) {
653
+            $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
654
+                'HTTP_X_FORWARDED_FOR'
655
+                // only have one default, so we cannot ship an insecure product out of the box
656
+            ]);
657
+
658
+            foreach($forwardedForHeaders as $header) {
659
+                if(isset($this->server[$header])) {
660
+                    foreach(explode(',', $this->server[$header]) as $IP) {
661
+                        $IP = trim($IP);
662
+                        if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
663
+                            return $IP;
664
+                        }
665
+                    }
666
+                }
667
+            }
668
+        }
669
+
670
+        return $remoteAddress;
671
+    }
672
+
673
+    /**
674
+     * Check overwrite condition
675
+     * @param string $type
676
+     * @return bool
677
+     */
678
+    private function isOverwriteCondition(string $type = ''): bool {
679
+        $regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
680
+        $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
681
+        return $regex === '//' || preg_match($regex, $remoteAddr) === 1
682
+        || $type !== 'protocol';
683
+    }
684
+
685
+    /**
686
+     * Returns the server protocol. It respects one or more reverse proxies servers
687
+     * and load balancers
688
+     * @return string Server protocol (http or https)
689
+     */
690
+    public function getServerProtocol(): string {
691
+        if($this->config->getSystemValue('overwriteprotocol') !== ''
692
+            && $this->isOverwriteCondition('protocol')) {
693
+            return $this->config->getSystemValue('overwriteprotocol');
694
+        }
695
+
696
+        if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
697
+            if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
698
+                $parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
699
+                $proto = strtolower(trim($parts[0]));
700
+            } else {
701
+                $proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
702
+            }
703
+
704
+            // Verify that the protocol is always HTTP or HTTPS
705
+            // default to http if an invalid value is provided
706
+            return $proto === 'https' ? 'https' : 'http';
707
+        }
708
+
709
+        if (isset($this->server['HTTPS'])
710
+            && $this->server['HTTPS'] !== null
711
+            && $this->server['HTTPS'] !== 'off'
712
+            && $this->server['HTTPS'] !== '') {
713
+            return 'https';
714
+        }
715
+
716
+        return 'http';
717
+    }
718
+
719
+    /**
720
+     * Returns the used HTTP protocol.
721
+     *
722
+     * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
723
+     */
724
+    public function getHttpProtocol(): string {
725
+        $claimedProtocol = $this->server['SERVER_PROTOCOL'];
726
+
727
+        if (\is_string($claimedProtocol)) {
728
+            $claimedProtocol = strtoupper($claimedProtocol);
729
+        }
730
+
731
+        $validProtocols = [
732
+            'HTTP/1.0',
733
+            'HTTP/1.1',
734
+            'HTTP/2',
735
+        ];
736
+
737
+        if(\in_array($claimedProtocol, $validProtocols, true)) {
738
+            return $claimedProtocol;
739
+        }
740
+
741
+        return 'HTTP/1.1';
742
+    }
743
+
744
+    /**
745
+     * Returns the request uri, even if the website uses one or more
746
+     * reverse proxies
747
+     * @return string
748
+     */
749
+    public function getRequestUri(): string {
750
+        $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
751
+        if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
752
+            $uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
753
+        }
754
+        return $uri;
755
+    }
756
+
757
+    /**
758
+     * Get raw PathInfo from request (not urldecoded)
759
+     * @throws \Exception
760
+     * @return string Path info
761
+     */
762
+    public function getRawPathInfo(): string {
763
+        $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
764
+        // remove too many slashes - can be caused by reverse proxy configuration
765
+        $requestUri = preg_replace('%/{2,}%', '/', $requestUri);
766
+
767
+        // Remove the query string from REQUEST_URI
768
+        if ($pos = strpos($requestUri, '?')) {
769
+            $requestUri = substr($requestUri, 0, $pos);
770
+        }
771
+
772
+        $scriptName = $this->server['SCRIPT_NAME'];
773
+        $pathInfo = $requestUri;
774
+
775
+        // strip off the script name's dir and file name
776
+        // FIXME: Sabre does not really belong here
777
+        list($path, $name) = \Sabre\Uri\split($scriptName);
778
+        if (!empty($path)) {
779
+            if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
780
+                $pathInfo = substr($pathInfo, \strlen($path));
781
+            } else {
782
+                throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
783
+            }
784
+        }
785
+        if ($name === null) {
786
+            $name = '';
787
+        }
788
+
789
+        if (strpos($pathInfo, '/'.$name) === 0) {
790
+            $pathInfo = substr($pathInfo, \strlen($name) + 1);
791
+        }
792
+        if ($name !== '' && strpos($pathInfo, $name) === 0) {
793
+            $pathInfo = substr($pathInfo, \strlen($name));
794
+        }
795
+        if($pathInfo === false || $pathInfo === '/'){
796
+            return '';
797
+        } else {
798
+            return $pathInfo;
799
+        }
800
+    }
801
+
802
+    /**
803
+     * Get PathInfo from request
804
+     * @throws \Exception
805
+     * @return string|false Path info or false when not found
806
+     */
807
+    public function getPathInfo() {
808
+        $pathInfo = $this->getRawPathInfo();
809
+        // following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
810
+        $pathInfo = rawurldecode($pathInfo);
811
+        $encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
812
+
813
+        switch($encoding) {
814
+            case 'ISO-8859-1':
815
+                $pathInfo = utf8_encode($pathInfo);
816
+        }
817
+        // end copy
818
+
819
+        return $pathInfo;
820
+    }
821
+
822
+    /**
823
+     * Returns the script name, even if the website uses one or more
824
+     * reverse proxies
825
+     * @return string the script name
826
+     */
827
+    public function getScriptName(): string {
828
+        $name = $this->server['SCRIPT_NAME'];
829
+        $overwriteWebRoot =  $this->config->getSystemValue('overwritewebroot');
830
+        if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
831
+            // FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
832
+            $serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
833
+            $suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
834
+            $name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
835
+        }
836
+        return $name;
837
+    }
838
+
839
+    /**
840
+     * Checks whether the user agent matches a given regex
841
+     * @param array $agent array of agent names
842
+     * @return bool true if at least one of the given agent matches, false otherwise
843
+     */
844
+    public function isUserAgent(array $agent): bool {
845
+        if (!isset($this->server['HTTP_USER_AGENT'])) {
846
+            return false;
847
+        }
848
+        foreach ($agent as $regex) {
849
+            if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
850
+                return true;
851
+            }
852
+        }
853
+        return false;
854
+    }
855
+
856
+    /**
857
+     * Returns the unverified server host from the headers without checking
858
+     * whether it is a trusted domain
859
+     * @return string Server host
860
+     */
861
+    public function getInsecureServerHost(): string {
862
+        if ($this->fromTrustedProxy() && $this->getOverwriteHost() !== null) {
863
+            return $this->getOverwriteHost();
864
+        }
865
+
866
+        $host = 'localhost';
867
+        if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_HOST'])) {
868
+            if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
869
+                $parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
870
+                $host = trim(current($parts));
871
+            } else {
872
+                $host = $this->server['HTTP_X_FORWARDED_HOST'];
873
+            }
874
+        } else {
875
+            if (isset($this->server['HTTP_HOST'])) {
876
+                $host = $this->server['HTTP_HOST'];
877
+            } else if (isset($this->server['SERVER_NAME'])) {
878
+                $host = $this->server['SERVER_NAME'];
879
+            }
880
+        }
881
+
882
+        return $host;
883
+    }
884
+
885
+
886
+    /**
887
+     * Returns the server host from the headers, or the first configured
888
+     * trusted domain if the host isn't in the trusted list
889
+     * @return string Server host
890
+     */
891
+    public function getServerHost(): string {
892
+        // overwritehost is always trusted
893
+        $host = $this->getOverwriteHost();
894
+        if ($host !== null) {
895
+            return $host;
896
+        }
897
+
898
+        // get the host from the headers
899
+        $host = $this->getInsecureServerHost();
900
+
901
+        // Verify that the host is a trusted domain if the trusted domains
902
+        // are defined
903
+        // If no trusted domain is provided the first trusted domain is returned
904
+        $trustedDomainHelper = new TrustedDomainHelper($this->config);
905
+        if ($trustedDomainHelper->isTrustedDomain($host)) {
906
+            return $host;
907
+        }
908
+
909
+        $trustedList = (array)$this->config->getSystemValue('trusted_domains', []);
910
+        if (count($trustedList) > 0) {
911
+            return reset($trustedList);
912
+        }
913
+
914
+        return '';
915
+    }
916
+
917
+    /**
918
+     * Returns the overwritehost setting from the config if set and
919
+     * if the overwrite condition is met
920
+     * @return string|null overwritehost value or null if not defined or the defined condition
921
+     * isn't met
922
+     */
923
+    private function getOverwriteHost() {
924
+        if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
925
+            return $this->config->getSystemValue('overwritehost');
926
+        }
927
+        return null;
928
+    }
929
+
930
+    private function fromTrustedProxy(): bool {
931
+        $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
932
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
933
+
934
+        return \is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress);
935
+    }
936 936
 }
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
 	 * @param string $stream
139 139
 	 * @see http://www.php.net/manual/en/reserved.variables.php
140 140
 	 */
141
-	public function __construct(array $vars= [],
141
+	public function __construct(array $vars = [],
142 142
 								ISecureRandom $secureRandom = null,
143 143
 								IConfig $config,
144 144
 								CsrfTokenManager $csrfTokenManager = null,
@@ -149,11 +149,11 @@  discard block
 block discarded – undo
149 149
 		$this->config = $config;
150 150
 		$this->csrfTokenManager = $csrfTokenManager;
151 151
 
152
-		if(!array_key_exists('method', $vars)) {
152
+		if (!array_key_exists('method', $vars)) {
153 153
 			$vars['method'] = 'GET';
154 154
 		}
155 155
 
156
-		foreach($this->allowedKeys as $name) {
156
+		foreach ($this->allowedKeys as $name) {
157 157
 			$this->items[$name] = isset($vars[$name])
158 158
 				? $vars[$name]
159 159
 				: [];
@@ -263,12 +263,12 @@  discard block
 block discarded – undo
263 263
 	 * @return mixed|null
264 264
 	 */
265 265
 	public function __get($name) {
266
-		switch($name) {
266
+		switch ($name) {
267 267
 			case 'put':
268 268
 			case 'patch':
269 269
 			case 'get':
270 270
 			case 'post':
271
-				if($this->method !== strtoupper($name)) {
271
+				if ($this->method !== strtoupper($name)) {
272 272
 					throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
273 273
 				}
274 274
 				return $this->getContent();
@@ -319,9 +319,9 @@  discard block
 block discarded – undo
319 319
 	 */
320 320
 	public function getHeader(string $name): string {
321 321
 
322
-		$name = strtoupper(str_replace('-', '_',$name));
323
-		if (isset($this->server['HTTP_' . $name])) {
324
-			return $this->server['HTTP_' . $name];
322
+		$name = strtoupper(str_replace('-', '_', $name));
323
+		if (isset($this->server['HTTP_'.$name])) {
324
+			return $this->server['HTTP_'.$name];
325 325
 		}
326 326
 
327 327
 		// There's a few headers that seem to end up in the top-level
@@ -447,21 +447,21 @@  discard block
 block discarded – undo
447 447
 		// 'application/json' must be decoded manually.
448 448
 		if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
449 449
 			$params = json_decode(file_get_contents($this->inputStream), true);
450
-			if($params !== null && \count($params) > 0) {
450
+			if ($params !== null && \count($params) > 0) {
451 451
 				$this->items['params'] = $params;
452
-				if($this->method === 'POST') {
452
+				if ($this->method === 'POST') {
453 453
 					$this->items['post'] = $params;
454 454
 				}
455 455
 			}
456 456
 
457 457
 		// Handle application/x-www-form-urlencoded for methods other than GET
458 458
 		// or post correctly
459
-		} elseif($this->method !== 'GET'
459
+		} elseif ($this->method !== 'GET'
460 460
 				&& $this->method !== 'POST'
461 461
 				&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
462 462
 
463 463
 			parse_str(file_get_contents($this->inputStream), $params);
464
-			if(\is_array($params)) {
464
+			if (\is_array($params)) {
465 465
 				$this->items['params'] = $params;
466 466
 			}
467 467
 		}
@@ -478,11 +478,11 @@  discard block
 block discarded – undo
478 478
 	 * @return bool true if CSRF check passed
479 479
 	 */
480 480
 	public function passesCSRFCheck(): bool {
481
-		if($this->csrfTokenManager === null) {
481
+		if ($this->csrfTokenManager === null) {
482 482
 			return false;
483 483
 		}
484 484
 
485
-		if(!$this->passesStrictCookieCheck()) {
485
+		if (!$this->passesStrictCookieCheck()) {
486 486
 			return false;
487 487
 		}
488 488
 
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
 		if ($this->getHeader('OCS-APIREQUEST')) {
511 511
 			return false;
512 512
 		}
513
-		if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
513
+		if ($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
514 514
 			return false;
515 515
 		}
516 516
 
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
 	protected function getProtectedCookieName(string $name): string {
536 536
 		$cookieParams = $this->getCookieParams();
537 537
 		$prefix = '';
538
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
538
+		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
539 539
 			$prefix = '__Host-';
540 540
 		}
541 541
 
@@ -550,12 +550,12 @@  discard block
 block discarded – undo
550 550
 	 * @since 9.1.0
551 551
 	 */
552 552
 	public function passesStrictCookieCheck(): bool {
553
-		if(!$this->cookieCheckRequired()) {
553
+		if (!$this->cookieCheckRequired()) {
554 554
 			return true;
555 555
 		}
556 556
 
557 557
 		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
558
-		if($this->getCookie($cookieName) === 'true'
558
+		if ($this->getCookie($cookieName) === 'true'
559 559
 			&& $this->passesLaxCookieCheck()) {
560 560
 			return true;
561 561
 		}
@@ -570,12 +570,12 @@  discard block
 block discarded – undo
570 570
 	 * @since 9.1.0
571 571
 	 */
572 572
 	public function passesLaxCookieCheck(): bool {
573
-		if(!$this->cookieCheckRequired()) {
573
+		if (!$this->cookieCheckRequired()) {
574 574
 			return true;
575 575
 		}
576 576
 
577 577
 		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
578
-		if($this->getCookie($cookieName) === 'true') {
578
+		if ($this->getCookie($cookieName) === 'true') {
579 579
 			return true;
580 580
 		}
581 581
 		return false;
@@ -588,12 +588,12 @@  discard block
 block discarded – undo
588 588
 	 * @return string
589 589
 	 */
590 590
 	public function getId(): string {
591
-		if(isset($this->server['UNIQUE_ID'])) {
591
+		if (isset($this->server['UNIQUE_ID'])) {
592 592
 			return $this->server['UNIQUE_ID'];
593 593
 		}
594 594
 
595
-		if(empty($this->requestId)) {
596
-			$validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
595
+		if (empty($this->requestId)) {
596
+			$validChars = ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS;
597 597
 			$this->requestId = $this->secureRandom->generate(20, $validChars);
598 598
 		}
599 599
 
@@ -649,15 +649,15 @@  discard block
 block discarded – undo
649 649
 		$remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
650 650
 		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
651 651
 
652
-		if(\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) {
652
+		if (\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) {
653 653
 			$forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
654 654
 				'HTTP_X_FORWARDED_FOR'
655 655
 				// only have one default, so we cannot ship an insecure product out of the box
656 656
 			]);
657 657
 
658
-			foreach($forwardedForHeaders as $header) {
659
-				if(isset($this->server[$header])) {
660
-					foreach(explode(',', $this->server[$header]) as $IP) {
658
+			foreach ($forwardedForHeaders as $header) {
659
+				if (isset($this->server[$header])) {
660
+					foreach (explode(',', $this->server[$header]) as $IP) {
661 661
 						$IP = trim($IP);
662 662
 						if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
663 663
 							return $IP;
@@ -676,7 +676,7 @@  discard block
 block discarded – undo
676 676
 	 * @return bool
677 677
 	 */
678 678
 	private function isOverwriteCondition(string $type = ''): bool {
679
-		$regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
679
+		$regex = '/'.$this->config->getSystemValue('overwritecondaddr', '').'/';
680 680
 		$remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
681 681
 		return $regex === '//' || preg_match($regex, $remoteAddr) === 1
682 682
 		|| $type !== 'protocol';
@@ -688,7 +688,7 @@  discard block
 block discarded – undo
688 688
 	 * @return string Server protocol (http or https)
689 689
 	 */
690 690
 	public function getServerProtocol(): string {
691
-		if($this->config->getSystemValue('overwriteprotocol') !== ''
691
+		if ($this->config->getSystemValue('overwriteprotocol') !== ''
692 692
 			&& $this->isOverwriteCondition('protocol')) {
693 693
 			return $this->config->getSystemValue('overwriteprotocol');
694 694
 		}
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
 			'HTTP/2',
735 735
 		];
736 736
 
737
-		if(\in_array($claimedProtocol, $validProtocols, true)) {
737
+		if (\in_array($claimedProtocol, $validProtocols, true)) {
738 738
 			return $claimedProtocol;
739 739
 		}
740 740
 
@@ -748,8 +748,8 @@  discard block
 block discarded – undo
748 748
 	 */
749 749
 	public function getRequestUri(): string {
750 750
 		$uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
751
-		if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
752
-			$uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
751
+		if ($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
752
+			$uri = $this->getScriptName().substr($uri, \strlen($this->server['SCRIPT_NAME']));
753 753
 		}
754 754
 		return $uri;
755 755
 	}
@@ -776,7 +776,7 @@  discard block
 block discarded – undo
776 776
 		// FIXME: Sabre does not really belong here
777 777
 		list($path, $name) = \Sabre\Uri\split($scriptName);
778 778
 		if (!empty($path)) {
779
-			if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
779
+			if ($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
780 780
 				$pathInfo = substr($pathInfo, \strlen($path));
781 781
 			} else {
782 782
 				throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
@@ -792,7 +792,7 @@  discard block
 block discarded – undo
792 792
 		if ($name !== '' && strpos($pathInfo, $name) === 0) {
793 793
 			$pathInfo = substr($pathInfo, \strlen($name));
794 794
 		}
795
-		if($pathInfo === false || $pathInfo === '/'){
795
+		if ($pathInfo === false || $pathInfo === '/') {
796 796
 			return '';
797 797
 		} else {
798 798
 			return $pathInfo;
@@ -810,7 +810,7 @@  discard block
 block discarded – undo
810 810
 		$pathInfo = rawurldecode($pathInfo);
811 811
 		$encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
812 812
 
813
-		switch($encoding) {
813
+		switch ($encoding) {
814 814
 			case 'ISO-8859-1':
815 815
 				$pathInfo = utf8_encode($pathInfo);
816 816
 		}
@@ -826,12 +826,12 @@  discard block
 block discarded – undo
826 826
 	 */
827 827
 	public function getScriptName(): string {
828 828
 		$name = $this->server['SCRIPT_NAME'];
829
-		$overwriteWebRoot =  $this->config->getSystemValue('overwritewebroot');
829
+		$overwriteWebRoot = $this->config->getSystemValue('overwritewebroot');
830 830
 		if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
831 831
 			// FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
832 832
 			$serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
833 833
 			$suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
834
-			$name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
834
+			$name = '/'.ltrim($overwriteWebRoot.$suburi, '/');
835 835
 		}
836 836
 		return $name;
837 837
 	}
@@ -906,7 +906,7 @@  discard block
 block discarded – undo
906 906
 			return $host;
907 907
 		}
908 908
 
909
-		$trustedList = (array)$this->config->getSystemValue('trusted_domains', []);
909
+		$trustedList = (array) $this->config->getSystemValue('trusted_domains', []);
910 910
 		if (count($trustedList) > 0) {
911 911
 			return reset($trustedList);
912 912
 		}
@@ -921,7 +921,7 @@  discard block
 block discarded – undo
921 921
 	 * isn't met
922 922
 	 */
923 923
 	private function getOverwriteHost() {
924
-		if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
924
+		if ($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
925 925
 			return $this->config->getSystemValue('overwritehost');
926 926
 		}
927 927
 		return null;
Please login to merge, or discard this patch.