Completed
Pull Request — master (#3838)
by Vars
12:18
created
apps/user_ldap/lib/Access.php 3 patches
Doc Comments   +8 added lines, -6 removed lines patch added patch discarded remove patch
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
 
362 362
 	/**
363 363
 	 * returns the internal ownCloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
364
-	 * @param string $dn the dn of the user object
364
+	 * @param string $fdn the dn of the user object
365 365
 	 * @param string $ldapName optional, the display name of the object
366 366
 	 * @return string|false with with the name to use in ownCloud
367 367
 	 */
@@ -378,7 +378,7 @@  discard block
 block discarded – undo
378 378
 
379 379
 	/**
380 380
 	 * returns an internal ownCloud name for the given LDAP DN, false on DN outside of search DN
381
-	 * @param string $dn the dn of the user object
381
+	 * @param string $fdn the dn of the user object
382 382
 	 * @param string $ldapName optional, the display name of the object
383 383
 	 * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
384 384
 	 * @return string|false with with the name to use in ownCloud
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
 	 * the login filter.
639 639
 	 *
640 640
 	 * @param string $loginName
641
-	 * @param array $attributes optional, list of attributes to read
641
+	 * @param string[] $attributes optional, list of attributes to read
642 642
 	 * @return array
643 643
 	 */
644 644
 	public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
@@ -711,7 +711,7 @@  discard block
 block discarded – undo
711 711
 
712 712
 	/**
713 713
 	 * @param string $filter
714
-	 * @param string|string[] $attr
714
+	 * @param string[] $attr
715 715
 	 * @param int $limit
716 716
 	 * @param int $offset
717 717
 	 * @return array
@@ -759,7 +759,7 @@  discard block
 block discarded – undo
759 759
 
760 760
 	/**
761 761
 	 * @param string $filter
762
-	 * @param string|string[] $attr
762
+	 * @param string[] $attr
763 763
 	 * @param int $limit
764 764
 	 * @param int $offset
765 765
 	 * @return false|int
@@ -809,6 +809,7 @@  discard block
 block discarded – undo
809 809
 	 * retrieved. Results will according to the order in the array.
810 810
 	 * @param int $limit optional, maximum results to be counted
811 811
 	 * @param int $offset optional, a starting point
812
+	 * @param string $filter
812 813
 	 * @return array|false array with the search result as first value and pagedSearchOK as
813 814
 	 * second | false if not successful
814 815
 	 */
@@ -1063,7 +1064,7 @@  discard block
 block discarded – undo
1063 1064
 
1064 1065
 	/**
1065 1066
 	 * @param string $name
1066
-	 * @return bool|mixed|string
1067
+	 * @return string
1067 1068
 	 */
1068 1069
 	public function sanitizeUsername($name) {
1069 1070
 		if($this->connection->ldapIgnoreNamingRules) {
@@ -1087,6 +1088,7 @@  discard block
 block discarded – undo
1087 1088
 	* escapes (user provided) parts for LDAP filter
1088 1089
 	* @param string $input, the provided value
1089 1090
 	* @param bool $allowAsterisk whether in * at the beginning should be preserved
1091
+	* @param string $input
1090 1092
 	* @return string the escaped string
1091 1093
 	*/
1092 1094
 	public function escapeFilterPart($input, $allowAsterisk = false) {
Please login to merge, or discard this patch.
Indentation   +1768 added lines, -1768 removed lines patch added patch discarded remove patch
@@ -52,1527 +52,1527 @@  discard block
 block discarded – undo
52 52
  * @package OCA\User_LDAP
53 53
  */
54 54
 class Access extends LDAPUtility implements IUserTools {
55
-	/**
56
-	 * @var \OCA\User_LDAP\Connection
57
-	 */
58
-	public $connection;
59
-	/** @var Manager */
60
-	public $userManager;
61
-	//never ever check this var directly, always use getPagedSearchResultState
62
-	protected $pagedSearchedSuccessful;
63
-
64
-	/**
65
-	 * @var string[] $cookies an array of returned Paged Result cookies
66
-	 */
67
-	protected $cookies = array();
68
-
69
-	/**
70
-	 * @var string $lastCookie the last cookie returned from a Paged Results
71
-	 * operation, defaults to an empty string
72
-	 */
73
-	protected $lastCookie = '';
74
-
75
-	/**
76
-	 * @var AbstractMapping $userMapper
77
-	 */
78
-	protected $userMapper;
79
-
80
-	/**
81
-	* @var AbstractMapping $userMapper
82
-	*/
83
-	protected $groupMapper;
55
+    /**
56
+     * @var \OCA\User_LDAP\Connection
57
+     */
58
+    public $connection;
59
+    /** @var Manager */
60
+    public $userManager;
61
+    //never ever check this var directly, always use getPagedSearchResultState
62
+    protected $pagedSearchedSuccessful;
63
+
64
+    /**
65
+     * @var string[] $cookies an array of returned Paged Result cookies
66
+     */
67
+    protected $cookies = array();
68
+
69
+    /**
70
+     * @var string $lastCookie the last cookie returned from a Paged Results
71
+     * operation, defaults to an empty string
72
+     */
73
+    protected $lastCookie = '';
74
+
75
+    /**
76
+     * @var AbstractMapping $userMapper
77
+     */
78
+    protected $userMapper;
79
+
80
+    /**
81
+     * @var AbstractMapping $userMapper
82
+     */
83
+    protected $groupMapper;
84 84
 	
85
-	/**
86
-	 * @var \OCA\User_LDAP\Helper
87
-	 */
88
-	private $helper;
89
-
90
-	public function __construct(Connection $connection, ILDAPWrapper $ldap,
91
-		Manager $userManager, Helper $helper) {
92
-		parent::__construct($ldap);
93
-		$this->connection = $connection;
94
-		$this->userManager = $userManager;
95
-		$this->userManager->setLdapAccess($this);
96
-		$this->helper = $helper;
97
-	}
98
-
99
-	/**
100
-	 * sets the User Mapper
101
-	 * @param AbstractMapping $mapper
102
-	 */
103
-	public function setUserMapper(AbstractMapping $mapper) {
104
-		$this->userMapper = $mapper;
105
-	}
106
-
107
-	/**
108
-	 * returns the User Mapper
109
-	 * @throws \Exception
110
-	 * @return AbstractMapping
111
-	 */
112
-	public function getUserMapper() {
113
-		if(is_null($this->userMapper)) {
114
-			throw new \Exception('UserMapper was not assigned to this Access instance.');
115
-		}
116
-		return $this->userMapper;
117
-	}
118
-
119
-	/**
120
-	 * sets the Group Mapper
121
-	 * @param AbstractMapping $mapper
122
-	 */
123
-	public function setGroupMapper(AbstractMapping $mapper) {
124
-		$this->groupMapper = $mapper;
125
-	}
126
-
127
-	/**
128
-	 * returns the Group Mapper
129
-	 * @throws \Exception
130
-	 * @return AbstractMapping
131
-	 */
132
-	public function getGroupMapper() {
133
-		if(is_null($this->groupMapper)) {
134
-			throw new \Exception('GroupMapper was not assigned to this Access instance.');
135
-		}
136
-		return $this->groupMapper;
137
-	}
138
-
139
-	/**
140
-	 * @return bool
141
-	 */
142
-	private function checkConnection() {
143
-		return ($this->connection instanceof Connection);
144
-	}
145
-
146
-	/**
147
-	 * returns the Connection instance
148
-	 * @return \OCA\User_LDAP\Connection
149
-	 */
150
-	public function getConnection() {
151
-		return $this->connection;
152
-	}
153
-
154
-	/**
155
-	 * reads a given attribute for an LDAP record identified by a DN
156
-	 * @param string $dn the record in question
157
-	 * @param string $attr the attribute that shall be retrieved
158
-	 *        if empty, just check the record's existence
159
-	 * @param string $filter
160
-	 * @return array|false an array of values on success or an empty
161
-	 *          array if $attr is empty, false otherwise
162
-	 */
163
-	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
164
-		if(!$this->checkConnection()) {
165
-			\OCP\Util::writeLog('user_ldap',
166
-				'No LDAP Connector assigned, access impossible for readAttribute.',
167
-				\OCP\Util::WARN);
168
-			return false;
169
-		}
170
-		$cr = $this->connection->getConnectionResource();
171
-		if(!$this->ldap->isResource($cr)) {
172
-			//LDAP not available
173
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
174
-			return false;
175
-		}
176
-		//Cancel possibly running Paged Results operation, otherwise we run in
177
-		//LDAP protocol errors
178
-		$this->abandonPagedSearch();
179
-		// openLDAP requires that we init a new Paged Search. Not needed by AD,
180
-		// but does not hurt either.
181
-		$pagingSize = intval($this->connection->ldapPagingSize);
182
-		// 0 won't result in replies, small numbers may leave out groups
183
-		// (cf. #12306), 500 is default for paging and should work everywhere.
184
-		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
185
-		$attr = mb_strtolower($attr, 'UTF-8');
186
-		// the actual read attribute later may contain parameters on a ranged
187
-		// request, e.g. member;range=99-199. Depends on server reply.
188
-		$attrToRead = $attr;
189
-
190
-		$values = [];
191
-		$isRangeRequest = false;
192
-		do {
193
-			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
194
-			if(is_bool($result)) {
195
-				// when an exists request was run and it was successful, an empty
196
-				// array must be returned
197
-				return $result ? [] : false;
198
-			}
199
-
200
-			if (!$isRangeRequest) {
201
-				$values = $this->extractAttributeValuesFromResult($result, $attr);
202
-				if (!empty($values)) {
203
-					return $values;
204
-				}
205
-			}
206
-
207
-			$isRangeRequest = false;
208
-			$result = $this->extractRangeData($result, $attr);
209
-			if (!empty($result)) {
210
-				$normalizedResult = $this->extractAttributeValuesFromResult(
211
-					[ $attr => $result['values'] ],
212
-					$attr
213
-				);
214
-				$values = array_merge($values, $normalizedResult);
215
-
216
-				if($result['rangeHigh'] === '*') {
217
-					// when server replies with * as high range value, there are
218
-					// no more results left
219
-					return $values;
220
-				} else {
221
-					$low  = $result['rangeHigh'] + 1;
222
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
223
-					$isRangeRequest = true;
224
-				}
225
-			}
226
-		} while($isRangeRequest);
227
-
228
-		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
229
-		return false;
230
-	}
231
-
232
-	/**
233
-	 * Runs an read operation against LDAP
234
-	 *
235
-	 * @param resource $cr the LDAP connection
236
-	 * @param string $dn
237
-	 * @param string $attribute
238
-	 * @param string $filter
239
-	 * @param int $maxResults
240
-	 * @return array|bool false if there was any error, true if an exists check
241
-	 *                    was performed and the requested DN found, array with the
242
-	 *                    returned data on a successful usual operation
243
-	 */
244
-	public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
245
-		$this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0);
246
-		$dn = $this->helper->DNasBaseParameter($dn);
247
-		$rr = @$this->ldap->read($cr, $dn, $filter, array($attribute));
248
-		if (!$this->ldap->isResource($rr)) {
249
-			if ($attribute !== '') {
250
-				//do not throw this message on userExists check, irritates
251
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
252
-			}
253
-			//in case an error occurs , e.g. object does not exist
254
-			return false;
255
-		}
256
-		if ($attribute === '' && ($filter === 'objectclass=*' || $this->ldap->countEntries($cr, $rr) === 1)) {
257
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
258
-			return true;
259
-		}
260
-		$er = $this->ldap->firstEntry($cr, $rr);
261
-		if (!$this->ldap->isResource($er)) {
262
-			//did not match the filter, return false
263
-			return false;
264
-		}
265
-		//LDAP attributes are not case sensitive
266
-		$result = \OCP\Util::mb_array_change_key_case(
267
-			$this->ldap->getAttributes($cr, $er), MB_CASE_LOWER, 'UTF-8');
268
-
269
-		return $result;
270
-	}
271
-
272
-	/**
273
-	 * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
274
-	 * data if present.
275
-	 *
276
-	 * @param array $result from ILDAPWrapper::getAttributes()
277
-	 * @param string $attribute the attribute name that was read
278
-	 * @return string[]
279
-	 */
280
-	public function extractAttributeValuesFromResult($result, $attribute) {
281
-		$values = [];
282
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
283
-			$lowercaseAttribute = strtolower($attribute);
284
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
285
-				if($this->resemblesDN($attribute)) {
286
-					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
287
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
288
-					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
289
-				} else {
290
-					$values[] = $result[$attribute][$i];
291
-				}
292
-			}
293
-		}
294
-		return $values;
295
-	}
296
-
297
-	/**
298
-	 * Attempts to find ranged data in a getAttribute results and extracts the
299
-	 * returned values as well as information on the range and full attribute
300
-	 * name for further processing.
301
-	 *
302
-	 * @param array $result from ILDAPWrapper::getAttributes()
303
-	 * @param string $attribute the attribute name that was read. Without ";range=…"
304
-	 * @return array If a range was detected with keys 'values', 'attributeName',
305
-	 *               'attributeFull' and 'rangeHigh', otherwise empty.
306
-	 */
307
-	public function extractRangeData($result, $attribute) {
308
-		$keys = array_keys($result);
309
-		foreach($keys as $key) {
310
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
311
-				$queryData = explode(';', $key);
312
-				if(strpos($queryData[1], 'range=') === 0) {
313
-					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
314
-					$data = [
315
-						'values' => $result[$key],
316
-						'attributeName' => $queryData[0],
317
-						'attributeFull' => $key,
318
-						'rangeHigh' => $high,
319
-					];
320
-					return $data;
321
-				}
322
-			}
323
-		}
324
-		return [];
325
-	}
85
+    /**
86
+     * @var \OCA\User_LDAP\Helper
87
+     */
88
+    private $helper;
89
+
90
+    public function __construct(Connection $connection, ILDAPWrapper $ldap,
91
+        Manager $userManager, Helper $helper) {
92
+        parent::__construct($ldap);
93
+        $this->connection = $connection;
94
+        $this->userManager = $userManager;
95
+        $this->userManager->setLdapAccess($this);
96
+        $this->helper = $helper;
97
+    }
98
+
99
+    /**
100
+     * sets the User Mapper
101
+     * @param AbstractMapping $mapper
102
+     */
103
+    public function setUserMapper(AbstractMapping $mapper) {
104
+        $this->userMapper = $mapper;
105
+    }
106
+
107
+    /**
108
+     * returns the User Mapper
109
+     * @throws \Exception
110
+     * @return AbstractMapping
111
+     */
112
+    public function getUserMapper() {
113
+        if(is_null($this->userMapper)) {
114
+            throw new \Exception('UserMapper was not assigned to this Access instance.');
115
+        }
116
+        return $this->userMapper;
117
+    }
118
+
119
+    /**
120
+     * sets the Group Mapper
121
+     * @param AbstractMapping $mapper
122
+     */
123
+    public function setGroupMapper(AbstractMapping $mapper) {
124
+        $this->groupMapper = $mapper;
125
+    }
126
+
127
+    /**
128
+     * returns the Group Mapper
129
+     * @throws \Exception
130
+     * @return AbstractMapping
131
+     */
132
+    public function getGroupMapper() {
133
+        if(is_null($this->groupMapper)) {
134
+            throw new \Exception('GroupMapper was not assigned to this Access instance.');
135
+        }
136
+        return $this->groupMapper;
137
+    }
138
+
139
+    /**
140
+     * @return bool
141
+     */
142
+    private function checkConnection() {
143
+        return ($this->connection instanceof Connection);
144
+    }
145
+
146
+    /**
147
+     * returns the Connection instance
148
+     * @return \OCA\User_LDAP\Connection
149
+     */
150
+    public function getConnection() {
151
+        return $this->connection;
152
+    }
153
+
154
+    /**
155
+     * reads a given attribute for an LDAP record identified by a DN
156
+     * @param string $dn the record in question
157
+     * @param string $attr the attribute that shall be retrieved
158
+     *        if empty, just check the record's existence
159
+     * @param string $filter
160
+     * @return array|false an array of values on success or an empty
161
+     *          array if $attr is empty, false otherwise
162
+     */
163
+    public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
164
+        if(!$this->checkConnection()) {
165
+            \OCP\Util::writeLog('user_ldap',
166
+                'No LDAP Connector assigned, access impossible for readAttribute.',
167
+                \OCP\Util::WARN);
168
+            return false;
169
+        }
170
+        $cr = $this->connection->getConnectionResource();
171
+        if(!$this->ldap->isResource($cr)) {
172
+            //LDAP not available
173
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
174
+            return false;
175
+        }
176
+        //Cancel possibly running Paged Results operation, otherwise we run in
177
+        //LDAP protocol errors
178
+        $this->abandonPagedSearch();
179
+        // openLDAP requires that we init a new Paged Search. Not needed by AD,
180
+        // but does not hurt either.
181
+        $pagingSize = intval($this->connection->ldapPagingSize);
182
+        // 0 won't result in replies, small numbers may leave out groups
183
+        // (cf. #12306), 500 is default for paging and should work everywhere.
184
+        $maxResults = $pagingSize > 20 ? $pagingSize : 500;
185
+        $attr = mb_strtolower($attr, 'UTF-8');
186
+        // the actual read attribute later may contain parameters on a ranged
187
+        // request, e.g. member;range=99-199. Depends on server reply.
188
+        $attrToRead = $attr;
189
+
190
+        $values = [];
191
+        $isRangeRequest = false;
192
+        do {
193
+            $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
194
+            if(is_bool($result)) {
195
+                // when an exists request was run and it was successful, an empty
196
+                // array must be returned
197
+                return $result ? [] : false;
198
+            }
199
+
200
+            if (!$isRangeRequest) {
201
+                $values = $this->extractAttributeValuesFromResult($result, $attr);
202
+                if (!empty($values)) {
203
+                    return $values;
204
+                }
205
+            }
206
+
207
+            $isRangeRequest = false;
208
+            $result = $this->extractRangeData($result, $attr);
209
+            if (!empty($result)) {
210
+                $normalizedResult = $this->extractAttributeValuesFromResult(
211
+                    [ $attr => $result['values'] ],
212
+                    $attr
213
+                );
214
+                $values = array_merge($values, $normalizedResult);
215
+
216
+                if($result['rangeHigh'] === '*') {
217
+                    // when server replies with * as high range value, there are
218
+                    // no more results left
219
+                    return $values;
220
+                } else {
221
+                    $low  = $result['rangeHigh'] + 1;
222
+                    $attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
223
+                    $isRangeRequest = true;
224
+                }
225
+            }
226
+        } while($isRangeRequest);
227
+
228
+        \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
229
+        return false;
230
+    }
231
+
232
+    /**
233
+     * Runs an read operation against LDAP
234
+     *
235
+     * @param resource $cr the LDAP connection
236
+     * @param string $dn
237
+     * @param string $attribute
238
+     * @param string $filter
239
+     * @param int $maxResults
240
+     * @return array|bool false if there was any error, true if an exists check
241
+     *                    was performed and the requested DN found, array with the
242
+     *                    returned data on a successful usual operation
243
+     */
244
+    public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
245
+        $this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0);
246
+        $dn = $this->helper->DNasBaseParameter($dn);
247
+        $rr = @$this->ldap->read($cr, $dn, $filter, array($attribute));
248
+        if (!$this->ldap->isResource($rr)) {
249
+            if ($attribute !== '') {
250
+                //do not throw this message on userExists check, irritates
251
+                \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
252
+            }
253
+            //in case an error occurs , e.g. object does not exist
254
+            return false;
255
+        }
256
+        if ($attribute === '' && ($filter === 'objectclass=*' || $this->ldap->countEntries($cr, $rr) === 1)) {
257
+            \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
258
+            return true;
259
+        }
260
+        $er = $this->ldap->firstEntry($cr, $rr);
261
+        if (!$this->ldap->isResource($er)) {
262
+            //did not match the filter, return false
263
+            return false;
264
+        }
265
+        //LDAP attributes are not case sensitive
266
+        $result = \OCP\Util::mb_array_change_key_case(
267
+            $this->ldap->getAttributes($cr, $er), MB_CASE_LOWER, 'UTF-8');
268
+
269
+        return $result;
270
+    }
271
+
272
+    /**
273
+     * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
274
+     * data if present.
275
+     *
276
+     * @param array $result from ILDAPWrapper::getAttributes()
277
+     * @param string $attribute the attribute name that was read
278
+     * @return string[]
279
+     */
280
+    public function extractAttributeValuesFromResult($result, $attribute) {
281
+        $values = [];
282
+        if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
283
+            $lowercaseAttribute = strtolower($attribute);
284
+            for($i=0;$i<$result[$attribute]['count'];$i++) {
285
+                if($this->resemblesDN($attribute)) {
286
+                    $values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
287
+                } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
288
+                    $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
289
+                } else {
290
+                    $values[] = $result[$attribute][$i];
291
+                }
292
+            }
293
+        }
294
+        return $values;
295
+    }
296
+
297
+    /**
298
+     * Attempts to find ranged data in a getAttribute results and extracts the
299
+     * returned values as well as information on the range and full attribute
300
+     * name for further processing.
301
+     *
302
+     * @param array $result from ILDAPWrapper::getAttributes()
303
+     * @param string $attribute the attribute name that was read. Without ";range=…"
304
+     * @return array If a range was detected with keys 'values', 'attributeName',
305
+     *               'attributeFull' and 'rangeHigh', otherwise empty.
306
+     */
307
+    public function extractRangeData($result, $attribute) {
308
+        $keys = array_keys($result);
309
+        foreach($keys as $key) {
310
+            if($key !== $attribute && strpos($key, $attribute) === 0) {
311
+                $queryData = explode(';', $key);
312
+                if(strpos($queryData[1], 'range=') === 0) {
313
+                    $high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
314
+                    $data = [
315
+                        'values' => $result[$key],
316
+                        'attributeName' => $queryData[0],
317
+                        'attributeFull' => $key,
318
+                        'rangeHigh' => $high,
319
+                    ];
320
+                    return $data;
321
+                }
322
+            }
323
+        }
324
+        return [];
325
+    }
326 326
 	
327
-	/**
328
-	 * Set password for an LDAP user identified by a DN
329
-	 *
330
-	 * @param string $userDN the user in question
331
-	 * @param string $password the new password
332
-	 * @return bool
333
-	 * @throws HintException
334
-	 * @throws \Exception
335
-	 */
336
-	public function setPassword($userDN, $password) {
337
-		if(intval($this->connection->turnOnPasswordChange) !== 1) {
338
-			throw new \Exception('LDAP password changes are disabled.');
339
-		}
340
-		$cr = $this->connection->getConnectionResource();
341
-		if(!$this->ldap->isResource($cr)) {
342
-			//LDAP not available
343
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
344
-			return false;
345
-		}
327
+    /**
328
+     * Set password for an LDAP user identified by a DN
329
+     *
330
+     * @param string $userDN the user in question
331
+     * @param string $password the new password
332
+     * @return bool
333
+     * @throws HintException
334
+     * @throws \Exception
335
+     */
336
+    public function setPassword($userDN, $password) {
337
+        if(intval($this->connection->turnOnPasswordChange) !== 1) {
338
+            throw new \Exception('LDAP password changes are disabled.');
339
+        }
340
+        $cr = $this->connection->getConnectionResource();
341
+        if(!$this->ldap->isResource($cr)) {
342
+            //LDAP not available
343
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
344
+            return false;
345
+        }
346 346
 		
347
-		try {
348
-			return $this->ldap->modReplace($cr, $userDN, $password);
349
-		} catch(ConstraintViolationException $e) {
350
-			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
351
-		}
352
-	}
353
-
354
-	/**
355
-	 * checks whether the given attributes value is probably a DN
356
-	 * @param string $attr the attribute in question
357
-	 * @return boolean if so true, otherwise false
358
-	 */
359
-	private function resemblesDN($attr) {
360
-		$resemblingAttributes = array(
361
-			'dn',
362
-			'uniquemember',
363
-			'member',
364
-			// memberOf is an "operational" attribute, without a definition in any RFC
365
-			'memberof'
366
-		);
367
-		return in_array($attr, $resemblingAttributes);
368
-	}
369
-
370
-	/**
371
-	 * checks whether the given string is probably a DN
372
-	 * @param string $string
373
-	 * @return boolean
374
-	 */
375
-	public function stringResemblesDN($string) {
376
-		$r = $this->ldap->explodeDN($string, 0);
377
-		// if exploding a DN succeeds and does not end up in
378
-		// an empty array except for $r[count] being 0.
379
-		return (is_array($r) && count($r) > 1);
380
-	}
381
-
382
-	/**
383
-	 * returns a DN-string that is cleaned from not domain parts, e.g.
384
-	 * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
385
-	 * becomes dc=foobar,dc=server,dc=org
386
-	 * @param string $dn
387
-	 * @return string
388
-	 */
389
-	public function getDomainDNFromDN($dn) {
390
-		$allParts = $this->ldap->explodeDN($dn, 0);
391
-		if($allParts === false) {
392
-			//not a valid DN
393
-			return '';
394
-		}
395
-		$domainParts = array();
396
-		$dcFound = false;
397
-		foreach($allParts as $part) {
398
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
399
-				$dcFound = true;
400
-			}
401
-			if($dcFound) {
402
-				$domainParts[] = $part;
403
-			}
404
-		}
405
-		$domainDN = implode(',', $domainParts);
406
-		return $domainDN;
407
-	}
408
-
409
-	/**
410
-	 * returns the LDAP DN for the given internal ownCloud name of the group
411
-	 * @param string $name the ownCloud name in question
412
-	 * @return string|false LDAP DN on success, otherwise false
413
-	 */
414
-	public function groupname2dn($name) {
415
-		return $this->groupMapper->getDNByName($name);
416
-	}
417
-
418
-	/**
419
-	 * returns the LDAP DN for the given internal ownCloud name of the user
420
-	 * @param string $name the ownCloud name in question
421
-	 * @return string|false with the LDAP DN on success, otherwise false
422
-	 */
423
-	public function username2dn($name) {
424
-		$fdn = $this->userMapper->getDNByName($name);
425
-
426
-		//Check whether the DN belongs to the Base, to avoid issues on multi-
427
-		//server setups
428
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
429
-			return $fdn;
430
-		}
431
-
432
-		return false;
433
-	}
434
-
435
-	/**
436
-	 * returns the internal ownCloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
437
-	 * @param string $fdn the dn of the group object
438
-	 * @param string $ldapName optional, the display name of the object
439
-	 * @return string|false with the name to use in ownCloud, false on DN outside of search DN
440
-	 */
441
-	public function dn2groupname($fdn, $ldapName = null) {
442
-		//To avoid bypassing the base DN settings under certain circumstances
443
-		//with the group support, check whether the provided DN matches one of
444
-		//the given Bases
445
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
446
-			return false;
447
-		}
448
-
449
-		return $this->dn2ocname($fdn, $ldapName, false);
450
-	}
451
-
452
-	/**
453
-	 * accepts an array of group DNs and tests whether they match the user
454
-	 * filter by doing read operations against the group entries. Returns an
455
-	 * array of DNs that match the filter.
456
-	 *
457
-	 * @param string[] $groupDNs
458
-	 * @return string[]
459
-	 */
460
-	public function groupsMatchFilter($groupDNs) {
461
-		$validGroupDNs = [];
462
-		foreach($groupDNs as $dn) {
463
-			$cacheKey = 'groupsMatchFilter-'.$dn;
464
-			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
465
-			if(!is_null($groupMatchFilter)) {
466
-				if($groupMatchFilter) {
467
-					$validGroupDNs[] = $dn;
468
-				}
469
-				continue;
470
-			}
471
-
472
-			// Check the base DN first. If this is not met already, we don't
473
-			// need to ask the server at all.
474
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
475
-				$this->connection->writeToCache($cacheKey, false);
476
-				continue;
477
-			}
478
-
479
-			$result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
480
-			if(is_array($result)) {
481
-				$this->connection->writeToCache($cacheKey, true);
482
-				$validGroupDNs[] = $dn;
483
-			} else {
484
-				$this->connection->writeToCache($cacheKey, false);
485
-			}
486
-
487
-		}
488
-		return $validGroupDNs;
489
-	}
490
-
491
-	/**
492
-	 * returns the internal ownCloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
493
-	 * @param string $dn the dn of the user object
494
-	 * @param string $ldapName optional, the display name of the object
495
-	 * @return string|false with with the name to use in ownCloud
496
-	 */
497
-	public function dn2username($fdn, $ldapName = null) {
498
-		//To avoid bypassing the base DN settings under certain circumstances
499
-		//with the group support, check whether the provided DN matches one of
500
-		//the given Bases
501
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
502
-			return false;
503
-		}
504
-
505
-		return $this->dn2ocname($fdn, $ldapName, true);
506
-	}
507
-
508
-	/**
509
-	 * returns an internal ownCloud name for the given LDAP DN, false on DN outside of search DN
510
-	 * @param string $dn the dn of the user object
511
-	 * @param string $ldapName optional, the display name of the object
512
-	 * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
513
-	 * @return string|false with with the name to use in ownCloud
514
-	 */
515
-	public function dn2ocname($fdn, $ldapName = null, $isUser = true) {
516
-		if($isUser) {
517
-			$mapper = $this->getUserMapper();
518
-			$nameAttribute = $this->connection->ldapUserDisplayName;
519
-		} else {
520
-			$mapper = $this->getGroupMapper();
521
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
522
-		}
523
-
524
-		//let's try to retrieve the ownCloud name from the mappings table
525
-		$ocName = $mapper->getNameByDN($fdn);
526
-		if(is_string($ocName)) {
527
-			return $ocName;
528
-		}
529
-
530
-		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
531
-		$uuid = $this->getUUID($fdn, $isUser);
532
-		if(is_string($uuid)) {
533
-			$ocName = $mapper->getNameByUUID($uuid);
534
-			if(is_string($ocName)) {
535
-				$mapper->setDNbyUUID($fdn, $uuid);
536
-				return $ocName;
537
-			}
538
-		} else {
539
-			//If the UUID can't be detected something is foul.
540
-			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', \OCP\Util::INFO);
541
-			return false;
542
-		}
543
-
544
-		if(is_null($ldapName)) {
545
-			$ldapName = $this->readAttribute($fdn, $nameAttribute);
546
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
547
-				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
548
-				return false;
549
-			}
550
-			$ldapName = $ldapName[0];
551
-		}
552
-
553
-		if($isUser) {
554
-			$usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
555
-			if ($usernameAttribute !== '') {
556
-				$username = $this->readAttribute($fdn, $usernameAttribute);
557
-				$username = $username[0];
558
-			} else {
559
-				$username = $uuid;
560
-			}
561
-			$intName = $this->sanitizeUsername($username);
562
-		} else {
563
-			$intName = $ldapName;
564
-		}
565
-
566
-		//a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
567
-		//disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
568
-		//NOTE: mind, disabling cache affects only this instance! Using it
569
-		// outside of core user management will still cache the user as non-existing.
570
-		$originalTTL = $this->connection->ldapCacheTTL;
571
-		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
572
-		if(($isUser && !\OCP\User::userExists($intName))
573
-			|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
574
-			if($mapper->map($fdn, $intName, $uuid)) {
575
-				$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
576
-				return $intName;
577
-			}
578
-		}
579
-		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
580
-
581
-		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
582
-		if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
583
-			return $altName;
584
-		}
585
-
586
-		//if everything else did not help..
587
-		\OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', \OCP\Util::INFO);
588
-		return false;
589
-	}
590
-
591
-	/**
592
-	 * gives back the user names as they are used ownClod internally
593
-	 * @param array $ldapUsers as returned by fetchList()
594
-	 * @return array an array with the user names to use in ownCloud
595
-	 *
596
-	 * gives back the user names as they are used ownClod internally
597
-	 */
598
-	public function ownCloudUserNames($ldapUsers) {
599
-		return $this->ldap2ownCloudNames($ldapUsers, true);
600
-	}
601
-
602
-	/**
603
-	 * gives back the group names as they are used ownClod internally
604
-	 * @param array $ldapGroups as returned by fetchList()
605
-	 * @return array an array with the group names to use in ownCloud
606
-	 *
607
-	 * gives back the group names as they are used ownClod internally
608
-	 */
609
-	public function ownCloudGroupNames($ldapGroups) {
610
-		return $this->ldap2ownCloudNames($ldapGroups, false);
611
-	}
612
-
613
-	/**
614
-	 * @param array $ldapObjects as returned by fetchList()
615
-	 * @param bool $isUsers
616
-	 * @return array
617
-	 */
618
-	private function ldap2ownCloudNames($ldapObjects, $isUsers) {
619
-		if($isUsers) {
620
-			$nameAttribute = $this->connection->ldapUserDisplayName;
621
-			$sndAttribute  = $this->connection->ldapUserDisplayName2;
622
-		} else {
623
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
624
-		}
625
-		$ownCloudNames = array();
626
-
627
-		foreach($ldapObjects as $ldapObject) {
628
-			$nameByLDAP = null;
629
-			if(    isset($ldapObject[$nameAttribute])
630
-				&& is_array($ldapObject[$nameAttribute])
631
-				&& isset($ldapObject[$nameAttribute][0])
632
-			) {
633
-				// might be set, but not necessarily. if so, we use it.
634
-				$nameByLDAP = $ldapObject[$nameAttribute][0];
635
-			}
636
-
637
-			$ocName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
638
-			if($ocName) {
639
-				$ownCloudNames[] = $ocName;
640
-				if($isUsers) {
641
-					//cache the user names so it does not need to be retrieved
642
-					//again later (e.g. sharing dialogue).
643
-					if(is_null($nameByLDAP)) {
644
-						continue;
645
-					}
646
-					$sndName = isset($ldapObject[$sndAttribute][0])
647
-						? $ldapObject[$sndAttribute][0] : '';
648
-					$this->cacheUserDisplayName($ocName, $nameByLDAP, $sndName);
649
-				}
650
-			}
651
-		}
652
-		return $ownCloudNames;
653
-	}
654
-
655
-	/**
656
-	 * caches the user display name
657
-	 * @param string $ocName the internal ownCloud username
658
-	 * @param string|false $home the home directory path
659
-	 */
660
-	public function cacheUserHome($ocName, $home) {
661
-		$cacheKey = 'getHome'.$ocName;
662
-		$this->connection->writeToCache($cacheKey, $home);
663
-	}
664
-
665
-	/**
666
-	 * caches a user as existing
667
-	 * @param string $ocName the internal ownCloud username
668
-	 */
669
-	public function cacheUserExists($ocName) {
670
-		$this->connection->writeToCache('userExists'.$ocName, true);
671
-	}
672
-
673
-	/**
674
-	 * caches the user display name
675
-	 * @param string $ocName the internal ownCloud username
676
-	 * @param string $displayName the display name
677
-	 * @param string $displayName2 the second display name
678
-	 */
679
-	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
680
-		$user = $this->userManager->get($ocName);
681
-		if($user === null) {
682
-			return;
683
-		}
684
-		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
685
-		$cacheKeyTrunk = 'getDisplayName';
686
-		$this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
687
-	}
688
-
689
-	/**
690
-	 * creates a unique name for internal ownCloud use for users. Don't call it directly.
691
-	 * @param string $name the display name of the object
692
-	 * @return string|false with with the name to use in ownCloud or false if unsuccessful
693
-	 *
694
-	 * Instead of using this method directly, call
695
-	 * createAltInternalOwnCloudName($name, true)
696
-	 */
697
-	private function _createAltInternalOwnCloudNameForUsers($name) {
698
-		$attempts = 0;
699
-		//while loop is just a precaution. If a name is not generated within
700
-		//20 attempts, something else is very wrong. Avoids infinite loop.
701
-		while($attempts < 20){
702
-			$altName = $name . '_' . rand(1000,9999);
703
-			if(!\OCP\User::userExists($altName)) {
704
-				return $altName;
705
-			}
706
-			$attempts++;
707
-		}
708
-		return false;
709
-	}
710
-
711
-	/**
712
-	 * creates a unique name for internal ownCloud use for groups. Don't call it directly.
713
-	 * @param string $name the display name of the object
714
-	 * @return string|false with with the name to use in ownCloud or false if unsuccessful.
715
-	 *
716
-	 * Instead of using this method directly, call
717
-	 * createAltInternalOwnCloudName($name, false)
718
-	 *
719
-	 * Group names are also used as display names, so we do a sequential
720
-	 * numbering, e.g. Developers_42 when there are 41 other groups called
721
-	 * "Developers"
722
-	 */
723
-	private function _createAltInternalOwnCloudNameForGroups($name) {
724
-		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
725
-		if(!($usedNames) || count($usedNames) === 0) {
726
-			$lastNo = 1; //will become name_2
727
-		} else {
728
-			natsort($usedNames);
729
-			$lastName = array_pop($usedNames);
730
-			$lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
731
-		}
732
-		$altName = $name.'_'.strval($lastNo+1);
733
-		unset($usedNames);
734
-
735
-		$attempts = 1;
736
-		while($attempts < 21){
737
-			// Check to be really sure it is unique
738
-			// while loop is just a precaution. If a name is not generated within
739
-			// 20 attempts, something else is very wrong. Avoids infinite loop.
740
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
741
-				return $altName;
742
-			}
743
-			$altName = $name . '_' . ($lastNo + $attempts);
744
-			$attempts++;
745
-		}
746
-		return false;
747
-	}
748
-
749
-	/**
750
-	 * creates a unique name for internal ownCloud use.
751
-	 * @param string $name the display name of the object
752
-	 * @param boolean $isUser whether name should be created for a user (true) or a group (false)
753
-	 * @return string|false with with the name to use in ownCloud or false if unsuccessful
754
-	 */
755
-	private function createAltInternalOwnCloudName($name, $isUser) {
756
-		$originalTTL = $this->connection->ldapCacheTTL;
757
-		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
758
-		if($isUser) {
759
-			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
760
-		} else {
761
-			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
762
-		}
763
-		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
764
-
765
-		return $altName;
766
-	}
767
-
768
-	/**
769
-	 * fetches a list of users according to a provided loginName and utilizing
770
-	 * the login filter.
771
-	 *
772
-	 * @param string $loginName
773
-	 * @param array $attributes optional, list of attributes to read
774
-	 * @return array
775
-	 */
776
-	public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
777
-		$loginName = $this->escapeFilterPart($loginName);
778
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
779
-		$users = $this->fetchListOfUsers($filter, $attributes);
780
-		return $users;
781
-	}
782
-
783
-	/**
784
-	 * counts the number of users according to a provided loginName and
785
-	 * utilizing the login filter.
786
-	 *
787
-	 * @param string $loginName
788
-	 * @return array
789
-	 */
790
-	public function countUsersByLoginName($loginName) {
791
-		$loginName = $this->escapeFilterPart($loginName);
792
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
793
-		$users = $this->countUsers($filter);
794
-		return $users;
795
-	}
796
-
797
-	/**
798
-	 * @param string $filter
799
-	 * @param string|string[] $attr
800
-	 * @param int $limit
801
-	 * @param int $offset
802
-	 * @return array
803
-	 */
804
-	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null) {
805
-		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
806
-		$this->batchApplyUserAttributes($ldapRecords);
807
-		return $this->fetchList($ldapRecords, (count($attr) > 1));
808
-	}
809
-
810
-	/**
811
-	 * provided with an array of LDAP user records the method will fetch the
812
-	 * user object and requests it to process the freshly fetched attributes and
813
-	 * and their values
814
-	 * @param array $ldapRecords
815
-	 */
816
-	public function batchApplyUserAttributes(array $ldapRecords){
817
-		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
818
-		foreach($ldapRecords as $userRecord) {
819
-			if(!isset($userRecord[$displayNameAttribute])) {
820
-				// displayName is obligatory
821
-				continue;
822
-			}
823
-			$ocName  = $this->dn2ocname($userRecord['dn'][0]);
824
-			if($ocName === false) {
825
-				continue;
826
-			}
827
-			$this->cacheUserExists($ocName);
828
-			$user = $this->userManager->get($ocName);
829
-			if($user instanceof OfflineUser) {
830
-				$user->unmark();
831
-				$user = $this->userManager->get($ocName);
832
-			}
833
-			if ($user !== null) {
834
-				$user->processAttributes($userRecord);
835
-			} else {
836
-				\OC::$server->getLogger()->debug(
837
-					"The ldap user manager returned null for $ocName",
838
-					['app'=>'user_ldap']
839
-				);
840
-			}
841
-		}
842
-	}
843
-
844
-	/**
845
-	 * @param string $filter
846
-	 * @param string|string[] $attr
847
-	 * @param int $limit
848
-	 * @param int $offset
849
-	 * @return array
850
-	 */
851
-	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
852
-		return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1));
853
-	}
854
-
855
-	/**
856
-	 * @param array $list
857
-	 * @param bool $manyAttributes
858
-	 * @return array
859
-	 */
860
-	private function fetchList($list, $manyAttributes) {
861
-		if(is_array($list)) {
862
-			if($manyAttributes) {
863
-				return $list;
864
-			} else {
865
-				$list = array_reduce($list, function($carry, $item) {
866
-					$attribute = array_keys($item)[0];
867
-					$carry[] = $item[$attribute][0];
868
-					return $carry;
869
-				}, array());
870
-				return array_unique($list, SORT_LOCALE_STRING);
871
-			}
872
-		}
873
-
874
-		//error cause actually, maybe throw an exception in future.
875
-		return array();
876
-	}
877
-
878
-	/**
879
-	 * executes an LDAP search, optimized for Users
880
-	 * @param string $filter the LDAP filter for the search
881
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
882
-	 * @param integer $limit
883
-	 * @param integer $offset
884
-	 * @return array with the search result
885
-	 *
886
-	 * Executes an LDAP search
887
-	 */
888
-	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
889
-		return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
890
-	}
891
-
892
-	/**
893
-	 * @param string $filter
894
-	 * @param string|string[] $attr
895
-	 * @param int $limit
896
-	 * @param int $offset
897
-	 * @return false|int
898
-	 */
899
-	public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) {
900
-		return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
901
-	}
902
-
903
-	/**
904
-	 * executes an LDAP search, optimized for Groups
905
-	 * @param string $filter the LDAP filter for the search
906
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
907
-	 * @param integer $limit
908
-	 * @param integer $offset
909
-	 * @return array with the search result
910
-	 *
911
-	 * Executes an LDAP search
912
-	 */
913
-	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
914
-		return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
915
-	}
916
-
917
-	/**
918
-	 * returns the number of available groups
919
-	 * @param string $filter the LDAP search filter
920
-	 * @param string[] $attr optional
921
-	 * @param int|null $limit
922
-	 * @param int|null $offset
923
-	 * @return int|bool
924
-	 */
925
-	public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) {
926
-		return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
927
-	}
928
-
929
-	/**
930
-	 * returns the number of available objects on the base DN
931
-	 *
932
-	 * @param int|null $limit
933
-	 * @param int|null $offset
934
-	 * @return int|bool
935
-	 */
936
-	public function countObjects($limit = null, $offset = null) {
937
-		return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset);
938
-	}
939
-
940
-	/**
941
-	 * retrieved. Results will according to the order in the array.
942
-	 * @param int $limit optional, maximum results to be counted
943
-	 * @param int $offset optional, a starting point
944
-	 * @return array|false array with the search result as first value and pagedSearchOK as
945
-	 * second | false if not successful
946
-	 */
947
-	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
948
-		if(!is_null($attr) && !is_array($attr)) {
949
-			$attr = array(mb_strtolower($attr, 'UTF-8'));
950
-		}
951
-
952
-		// See if we have a resource, in case not cancel with message
953
-		$cr = $this->connection->getConnectionResource();
954
-		if(!$this->ldap->isResource($cr)) {
955
-			// Seems like we didn't find any resource.
956
-			// Return an empty array just like before.
957
-			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
958
-			return false;
959
-		}
960
-
961
-		//check whether paged search should be attempted
962
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, intval($limit), $offset);
963
-
964
-		$linkResources = array_pad(array(), count($base), $cr);
965
-		$sr = $this->ldap->search($linkResources, $base, $filter, $attr);
966
-		$error = $this->ldap->errno($cr);
967
-		if(!is_array($sr) || $error !== 0) {
968
-			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
969
-			return false;
970
-		}
971
-
972
-		return array($sr, $pagedSearchOK);
973
-	}
974
-
975
-	/**
976
-	 * processes an LDAP paged search operation
977
-	 * @param array $sr the array containing the LDAP search resources
978
-	 * @param string $filter the LDAP filter for the search
979
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
980
-	 * @param int $iFoundItems number of results in the search operation
981
-	 * @param int $limit maximum results to be counted
982
-	 * @param int $offset a starting point
983
-	 * @param bool $pagedSearchOK whether a paged search has been executed
984
-	 * @param bool $skipHandling required for paged search when cookies to
985
-	 * prior results need to be gained
986
-	 * @return bool cookie validity, true if we have more pages, false otherwise.
987
-	 */
988
-	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
989
-		$cookie = null;
990
-		if($pagedSearchOK) {
991
-			$cr = $this->connection->getConnectionResource();
992
-			foreach($sr as $key => $res) {
993
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
994
-					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
995
-				}
996
-			}
997
-
998
-			//browsing through prior pages to get the cookie for the new one
999
-			if($skipHandling) {
1000
-				return false;
1001
-			}
1002
-			// if count is bigger, then the server does not support
1003
-			// paged search. Instead, he did a normal search. We set a
1004
-			// flag here, so the callee knows how to deal with it.
1005
-			if($iFoundItems <= $limit) {
1006
-				$this->pagedSearchedSuccessful = true;
1007
-			}
1008
-		} else {
1009
-			if(!is_null($limit)) {
1010
-				\OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO);
1011
-			}
1012
-		}
1013
-		/* ++ Fixing RHDS searches with pages with zero results ++
347
+        try {
348
+            return $this->ldap->modReplace($cr, $userDN, $password);
349
+        } catch(ConstraintViolationException $e) {
350
+            throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
351
+        }
352
+    }
353
+
354
+    /**
355
+     * checks whether the given attributes value is probably a DN
356
+     * @param string $attr the attribute in question
357
+     * @return boolean if so true, otherwise false
358
+     */
359
+    private function resemblesDN($attr) {
360
+        $resemblingAttributes = array(
361
+            'dn',
362
+            'uniquemember',
363
+            'member',
364
+            // memberOf is an "operational" attribute, without a definition in any RFC
365
+            'memberof'
366
+        );
367
+        return in_array($attr, $resemblingAttributes);
368
+    }
369
+
370
+    /**
371
+     * checks whether the given string is probably a DN
372
+     * @param string $string
373
+     * @return boolean
374
+     */
375
+    public function stringResemblesDN($string) {
376
+        $r = $this->ldap->explodeDN($string, 0);
377
+        // if exploding a DN succeeds and does not end up in
378
+        // an empty array except for $r[count] being 0.
379
+        return (is_array($r) && count($r) > 1);
380
+    }
381
+
382
+    /**
383
+     * returns a DN-string that is cleaned from not domain parts, e.g.
384
+     * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
385
+     * becomes dc=foobar,dc=server,dc=org
386
+     * @param string $dn
387
+     * @return string
388
+     */
389
+    public function getDomainDNFromDN($dn) {
390
+        $allParts = $this->ldap->explodeDN($dn, 0);
391
+        if($allParts === false) {
392
+            //not a valid DN
393
+            return '';
394
+        }
395
+        $domainParts = array();
396
+        $dcFound = false;
397
+        foreach($allParts as $part) {
398
+            if(!$dcFound && strpos($part, 'dc=') === 0) {
399
+                $dcFound = true;
400
+            }
401
+            if($dcFound) {
402
+                $domainParts[] = $part;
403
+            }
404
+        }
405
+        $domainDN = implode(',', $domainParts);
406
+        return $domainDN;
407
+    }
408
+
409
+    /**
410
+     * returns the LDAP DN for the given internal ownCloud name of the group
411
+     * @param string $name the ownCloud name in question
412
+     * @return string|false LDAP DN on success, otherwise false
413
+     */
414
+    public function groupname2dn($name) {
415
+        return $this->groupMapper->getDNByName($name);
416
+    }
417
+
418
+    /**
419
+     * returns the LDAP DN for the given internal ownCloud name of the user
420
+     * @param string $name the ownCloud name in question
421
+     * @return string|false with the LDAP DN on success, otherwise false
422
+     */
423
+    public function username2dn($name) {
424
+        $fdn = $this->userMapper->getDNByName($name);
425
+
426
+        //Check whether the DN belongs to the Base, to avoid issues on multi-
427
+        //server setups
428
+        if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
429
+            return $fdn;
430
+        }
431
+
432
+        return false;
433
+    }
434
+
435
+    /**
436
+     * returns the internal ownCloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
437
+     * @param string $fdn the dn of the group object
438
+     * @param string $ldapName optional, the display name of the object
439
+     * @return string|false with the name to use in ownCloud, false on DN outside of search DN
440
+     */
441
+    public function dn2groupname($fdn, $ldapName = null) {
442
+        //To avoid bypassing the base DN settings under certain circumstances
443
+        //with the group support, check whether the provided DN matches one of
444
+        //the given Bases
445
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
446
+            return false;
447
+        }
448
+
449
+        return $this->dn2ocname($fdn, $ldapName, false);
450
+    }
451
+
452
+    /**
453
+     * accepts an array of group DNs and tests whether they match the user
454
+     * filter by doing read operations against the group entries. Returns an
455
+     * array of DNs that match the filter.
456
+     *
457
+     * @param string[] $groupDNs
458
+     * @return string[]
459
+     */
460
+    public function groupsMatchFilter($groupDNs) {
461
+        $validGroupDNs = [];
462
+        foreach($groupDNs as $dn) {
463
+            $cacheKey = 'groupsMatchFilter-'.$dn;
464
+            $groupMatchFilter = $this->connection->getFromCache($cacheKey);
465
+            if(!is_null($groupMatchFilter)) {
466
+                if($groupMatchFilter) {
467
+                    $validGroupDNs[] = $dn;
468
+                }
469
+                continue;
470
+            }
471
+
472
+            // Check the base DN first. If this is not met already, we don't
473
+            // need to ask the server at all.
474
+            if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
475
+                $this->connection->writeToCache($cacheKey, false);
476
+                continue;
477
+            }
478
+
479
+            $result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
480
+            if(is_array($result)) {
481
+                $this->connection->writeToCache($cacheKey, true);
482
+                $validGroupDNs[] = $dn;
483
+            } else {
484
+                $this->connection->writeToCache($cacheKey, false);
485
+            }
486
+
487
+        }
488
+        return $validGroupDNs;
489
+    }
490
+
491
+    /**
492
+     * returns the internal ownCloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
493
+     * @param string $dn the dn of the user object
494
+     * @param string $ldapName optional, the display name of the object
495
+     * @return string|false with with the name to use in ownCloud
496
+     */
497
+    public function dn2username($fdn, $ldapName = null) {
498
+        //To avoid bypassing the base DN settings under certain circumstances
499
+        //with the group support, check whether the provided DN matches one of
500
+        //the given Bases
501
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
502
+            return false;
503
+        }
504
+
505
+        return $this->dn2ocname($fdn, $ldapName, true);
506
+    }
507
+
508
+    /**
509
+     * returns an internal ownCloud name for the given LDAP DN, false on DN outside of search DN
510
+     * @param string $dn the dn of the user object
511
+     * @param string $ldapName optional, the display name of the object
512
+     * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
513
+     * @return string|false with with the name to use in ownCloud
514
+     */
515
+    public function dn2ocname($fdn, $ldapName = null, $isUser = true) {
516
+        if($isUser) {
517
+            $mapper = $this->getUserMapper();
518
+            $nameAttribute = $this->connection->ldapUserDisplayName;
519
+        } else {
520
+            $mapper = $this->getGroupMapper();
521
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
522
+        }
523
+
524
+        //let's try to retrieve the ownCloud name from the mappings table
525
+        $ocName = $mapper->getNameByDN($fdn);
526
+        if(is_string($ocName)) {
527
+            return $ocName;
528
+        }
529
+
530
+        //second try: get the UUID and check if it is known. Then, update the DN and return the name.
531
+        $uuid = $this->getUUID($fdn, $isUser);
532
+        if(is_string($uuid)) {
533
+            $ocName = $mapper->getNameByUUID($uuid);
534
+            if(is_string($ocName)) {
535
+                $mapper->setDNbyUUID($fdn, $uuid);
536
+                return $ocName;
537
+            }
538
+        } else {
539
+            //If the UUID can't be detected something is foul.
540
+            \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', \OCP\Util::INFO);
541
+            return false;
542
+        }
543
+
544
+        if(is_null($ldapName)) {
545
+            $ldapName = $this->readAttribute($fdn, $nameAttribute);
546
+            if(!isset($ldapName[0]) && empty($ldapName[0])) {
547
+                \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
548
+                return false;
549
+            }
550
+            $ldapName = $ldapName[0];
551
+        }
552
+
553
+        if($isUser) {
554
+            $usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
555
+            if ($usernameAttribute !== '') {
556
+                $username = $this->readAttribute($fdn, $usernameAttribute);
557
+                $username = $username[0];
558
+            } else {
559
+                $username = $uuid;
560
+            }
561
+            $intName = $this->sanitizeUsername($username);
562
+        } else {
563
+            $intName = $ldapName;
564
+        }
565
+
566
+        //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
567
+        //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
568
+        //NOTE: mind, disabling cache affects only this instance! Using it
569
+        // outside of core user management will still cache the user as non-existing.
570
+        $originalTTL = $this->connection->ldapCacheTTL;
571
+        $this->connection->setConfiguration(array('ldapCacheTTL' => 0));
572
+        if(($isUser && !\OCP\User::userExists($intName))
573
+            || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
574
+            if($mapper->map($fdn, $intName, $uuid)) {
575
+                $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
576
+                return $intName;
577
+            }
578
+        }
579
+        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
580
+
581
+        $altName = $this->createAltInternalOwnCloudName($intName, $isUser);
582
+        if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
583
+            return $altName;
584
+        }
585
+
586
+        //if everything else did not help..
587
+        \OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', \OCP\Util::INFO);
588
+        return false;
589
+    }
590
+
591
+    /**
592
+     * gives back the user names as they are used ownClod internally
593
+     * @param array $ldapUsers as returned by fetchList()
594
+     * @return array an array with the user names to use in ownCloud
595
+     *
596
+     * gives back the user names as they are used ownClod internally
597
+     */
598
+    public function ownCloudUserNames($ldapUsers) {
599
+        return $this->ldap2ownCloudNames($ldapUsers, true);
600
+    }
601
+
602
+    /**
603
+     * gives back the group names as they are used ownClod internally
604
+     * @param array $ldapGroups as returned by fetchList()
605
+     * @return array an array with the group names to use in ownCloud
606
+     *
607
+     * gives back the group names as they are used ownClod internally
608
+     */
609
+    public function ownCloudGroupNames($ldapGroups) {
610
+        return $this->ldap2ownCloudNames($ldapGroups, false);
611
+    }
612
+
613
+    /**
614
+     * @param array $ldapObjects as returned by fetchList()
615
+     * @param bool $isUsers
616
+     * @return array
617
+     */
618
+    private function ldap2ownCloudNames($ldapObjects, $isUsers) {
619
+        if($isUsers) {
620
+            $nameAttribute = $this->connection->ldapUserDisplayName;
621
+            $sndAttribute  = $this->connection->ldapUserDisplayName2;
622
+        } else {
623
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
624
+        }
625
+        $ownCloudNames = array();
626
+
627
+        foreach($ldapObjects as $ldapObject) {
628
+            $nameByLDAP = null;
629
+            if(    isset($ldapObject[$nameAttribute])
630
+                && is_array($ldapObject[$nameAttribute])
631
+                && isset($ldapObject[$nameAttribute][0])
632
+            ) {
633
+                // might be set, but not necessarily. if so, we use it.
634
+                $nameByLDAP = $ldapObject[$nameAttribute][0];
635
+            }
636
+
637
+            $ocName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
638
+            if($ocName) {
639
+                $ownCloudNames[] = $ocName;
640
+                if($isUsers) {
641
+                    //cache the user names so it does not need to be retrieved
642
+                    //again later (e.g. sharing dialogue).
643
+                    if(is_null($nameByLDAP)) {
644
+                        continue;
645
+                    }
646
+                    $sndName = isset($ldapObject[$sndAttribute][0])
647
+                        ? $ldapObject[$sndAttribute][0] : '';
648
+                    $this->cacheUserDisplayName($ocName, $nameByLDAP, $sndName);
649
+                }
650
+            }
651
+        }
652
+        return $ownCloudNames;
653
+    }
654
+
655
+    /**
656
+     * caches the user display name
657
+     * @param string $ocName the internal ownCloud username
658
+     * @param string|false $home the home directory path
659
+     */
660
+    public function cacheUserHome($ocName, $home) {
661
+        $cacheKey = 'getHome'.$ocName;
662
+        $this->connection->writeToCache($cacheKey, $home);
663
+    }
664
+
665
+    /**
666
+     * caches a user as existing
667
+     * @param string $ocName the internal ownCloud username
668
+     */
669
+    public function cacheUserExists($ocName) {
670
+        $this->connection->writeToCache('userExists'.$ocName, true);
671
+    }
672
+
673
+    /**
674
+     * caches the user display name
675
+     * @param string $ocName the internal ownCloud username
676
+     * @param string $displayName the display name
677
+     * @param string $displayName2 the second display name
678
+     */
679
+    public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
680
+        $user = $this->userManager->get($ocName);
681
+        if($user === null) {
682
+            return;
683
+        }
684
+        $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
685
+        $cacheKeyTrunk = 'getDisplayName';
686
+        $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
687
+    }
688
+
689
+    /**
690
+     * creates a unique name for internal ownCloud use for users. Don't call it directly.
691
+     * @param string $name the display name of the object
692
+     * @return string|false with with the name to use in ownCloud or false if unsuccessful
693
+     *
694
+     * Instead of using this method directly, call
695
+     * createAltInternalOwnCloudName($name, true)
696
+     */
697
+    private function _createAltInternalOwnCloudNameForUsers($name) {
698
+        $attempts = 0;
699
+        //while loop is just a precaution. If a name is not generated within
700
+        //20 attempts, something else is very wrong. Avoids infinite loop.
701
+        while($attempts < 20){
702
+            $altName = $name . '_' . rand(1000,9999);
703
+            if(!\OCP\User::userExists($altName)) {
704
+                return $altName;
705
+            }
706
+            $attempts++;
707
+        }
708
+        return false;
709
+    }
710
+
711
+    /**
712
+     * creates a unique name for internal ownCloud use for groups. Don't call it directly.
713
+     * @param string $name the display name of the object
714
+     * @return string|false with with the name to use in ownCloud or false if unsuccessful.
715
+     *
716
+     * Instead of using this method directly, call
717
+     * createAltInternalOwnCloudName($name, false)
718
+     *
719
+     * Group names are also used as display names, so we do a sequential
720
+     * numbering, e.g. Developers_42 when there are 41 other groups called
721
+     * "Developers"
722
+     */
723
+    private function _createAltInternalOwnCloudNameForGroups($name) {
724
+        $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
725
+        if(!($usedNames) || count($usedNames) === 0) {
726
+            $lastNo = 1; //will become name_2
727
+        } else {
728
+            natsort($usedNames);
729
+            $lastName = array_pop($usedNames);
730
+            $lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
731
+        }
732
+        $altName = $name.'_'.strval($lastNo+1);
733
+        unset($usedNames);
734
+
735
+        $attempts = 1;
736
+        while($attempts < 21){
737
+            // Check to be really sure it is unique
738
+            // while loop is just a precaution. If a name is not generated within
739
+            // 20 attempts, something else is very wrong. Avoids infinite loop.
740
+            if(!\OC::$server->getGroupManager()->groupExists($altName)) {
741
+                return $altName;
742
+            }
743
+            $altName = $name . '_' . ($lastNo + $attempts);
744
+            $attempts++;
745
+        }
746
+        return false;
747
+    }
748
+
749
+    /**
750
+     * creates a unique name for internal ownCloud use.
751
+     * @param string $name the display name of the object
752
+     * @param boolean $isUser whether name should be created for a user (true) or a group (false)
753
+     * @return string|false with with the name to use in ownCloud or false if unsuccessful
754
+     */
755
+    private function createAltInternalOwnCloudName($name, $isUser) {
756
+        $originalTTL = $this->connection->ldapCacheTTL;
757
+        $this->connection->setConfiguration(array('ldapCacheTTL' => 0));
758
+        if($isUser) {
759
+            $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
760
+        } else {
761
+            $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
762
+        }
763
+        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
764
+
765
+        return $altName;
766
+    }
767
+
768
+    /**
769
+     * fetches a list of users according to a provided loginName and utilizing
770
+     * the login filter.
771
+     *
772
+     * @param string $loginName
773
+     * @param array $attributes optional, list of attributes to read
774
+     * @return array
775
+     */
776
+    public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
777
+        $loginName = $this->escapeFilterPart($loginName);
778
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
779
+        $users = $this->fetchListOfUsers($filter, $attributes);
780
+        return $users;
781
+    }
782
+
783
+    /**
784
+     * counts the number of users according to a provided loginName and
785
+     * utilizing the login filter.
786
+     *
787
+     * @param string $loginName
788
+     * @return array
789
+     */
790
+    public function countUsersByLoginName($loginName) {
791
+        $loginName = $this->escapeFilterPart($loginName);
792
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
793
+        $users = $this->countUsers($filter);
794
+        return $users;
795
+    }
796
+
797
+    /**
798
+     * @param string $filter
799
+     * @param string|string[] $attr
800
+     * @param int $limit
801
+     * @param int $offset
802
+     * @return array
803
+     */
804
+    public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null) {
805
+        $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
806
+        $this->batchApplyUserAttributes($ldapRecords);
807
+        return $this->fetchList($ldapRecords, (count($attr) > 1));
808
+    }
809
+
810
+    /**
811
+     * provided with an array of LDAP user records the method will fetch the
812
+     * user object and requests it to process the freshly fetched attributes and
813
+     * and their values
814
+     * @param array $ldapRecords
815
+     */
816
+    public function batchApplyUserAttributes(array $ldapRecords){
817
+        $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
818
+        foreach($ldapRecords as $userRecord) {
819
+            if(!isset($userRecord[$displayNameAttribute])) {
820
+                // displayName is obligatory
821
+                continue;
822
+            }
823
+            $ocName  = $this->dn2ocname($userRecord['dn'][0]);
824
+            if($ocName === false) {
825
+                continue;
826
+            }
827
+            $this->cacheUserExists($ocName);
828
+            $user = $this->userManager->get($ocName);
829
+            if($user instanceof OfflineUser) {
830
+                $user->unmark();
831
+                $user = $this->userManager->get($ocName);
832
+            }
833
+            if ($user !== null) {
834
+                $user->processAttributes($userRecord);
835
+            } else {
836
+                \OC::$server->getLogger()->debug(
837
+                    "The ldap user manager returned null for $ocName",
838
+                    ['app'=>'user_ldap']
839
+                );
840
+            }
841
+        }
842
+    }
843
+
844
+    /**
845
+     * @param string $filter
846
+     * @param string|string[] $attr
847
+     * @param int $limit
848
+     * @param int $offset
849
+     * @return array
850
+     */
851
+    public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
852
+        return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1));
853
+    }
854
+
855
+    /**
856
+     * @param array $list
857
+     * @param bool $manyAttributes
858
+     * @return array
859
+     */
860
+    private function fetchList($list, $manyAttributes) {
861
+        if(is_array($list)) {
862
+            if($manyAttributes) {
863
+                return $list;
864
+            } else {
865
+                $list = array_reduce($list, function($carry, $item) {
866
+                    $attribute = array_keys($item)[0];
867
+                    $carry[] = $item[$attribute][0];
868
+                    return $carry;
869
+                }, array());
870
+                return array_unique($list, SORT_LOCALE_STRING);
871
+            }
872
+        }
873
+
874
+        //error cause actually, maybe throw an exception in future.
875
+        return array();
876
+    }
877
+
878
+    /**
879
+     * executes an LDAP search, optimized for Users
880
+     * @param string $filter the LDAP filter for the search
881
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
882
+     * @param integer $limit
883
+     * @param integer $offset
884
+     * @return array with the search result
885
+     *
886
+     * Executes an LDAP search
887
+     */
888
+    public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
889
+        return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
890
+    }
891
+
892
+    /**
893
+     * @param string $filter
894
+     * @param string|string[] $attr
895
+     * @param int $limit
896
+     * @param int $offset
897
+     * @return false|int
898
+     */
899
+    public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) {
900
+        return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
901
+    }
902
+
903
+    /**
904
+     * executes an LDAP search, optimized for Groups
905
+     * @param string $filter the LDAP filter for the search
906
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
907
+     * @param integer $limit
908
+     * @param integer $offset
909
+     * @return array with the search result
910
+     *
911
+     * Executes an LDAP search
912
+     */
913
+    public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
914
+        return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
915
+    }
916
+
917
+    /**
918
+     * returns the number of available groups
919
+     * @param string $filter the LDAP search filter
920
+     * @param string[] $attr optional
921
+     * @param int|null $limit
922
+     * @param int|null $offset
923
+     * @return int|bool
924
+     */
925
+    public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) {
926
+        return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
927
+    }
928
+
929
+    /**
930
+     * returns the number of available objects on the base DN
931
+     *
932
+     * @param int|null $limit
933
+     * @param int|null $offset
934
+     * @return int|bool
935
+     */
936
+    public function countObjects($limit = null, $offset = null) {
937
+        return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset);
938
+    }
939
+
940
+    /**
941
+     * retrieved. Results will according to the order in the array.
942
+     * @param int $limit optional, maximum results to be counted
943
+     * @param int $offset optional, a starting point
944
+     * @return array|false array with the search result as first value and pagedSearchOK as
945
+     * second | false if not successful
946
+     */
947
+    private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
948
+        if(!is_null($attr) && !is_array($attr)) {
949
+            $attr = array(mb_strtolower($attr, 'UTF-8'));
950
+        }
951
+
952
+        // See if we have a resource, in case not cancel with message
953
+        $cr = $this->connection->getConnectionResource();
954
+        if(!$this->ldap->isResource($cr)) {
955
+            // Seems like we didn't find any resource.
956
+            // Return an empty array just like before.
957
+            \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
958
+            return false;
959
+        }
960
+
961
+        //check whether paged search should be attempted
962
+        $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, intval($limit), $offset);
963
+
964
+        $linkResources = array_pad(array(), count($base), $cr);
965
+        $sr = $this->ldap->search($linkResources, $base, $filter, $attr);
966
+        $error = $this->ldap->errno($cr);
967
+        if(!is_array($sr) || $error !== 0) {
968
+            \OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
969
+            return false;
970
+        }
971
+
972
+        return array($sr, $pagedSearchOK);
973
+    }
974
+
975
+    /**
976
+     * processes an LDAP paged search operation
977
+     * @param array $sr the array containing the LDAP search resources
978
+     * @param string $filter the LDAP filter for the search
979
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
980
+     * @param int $iFoundItems number of results in the search operation
981
+     * @param int $limit maximum results to be counted
982
+     * @param int $offset a starting point
983
+     * @param bool $pagedSearchOK whether a paged search has been executed
984
+     * @param bool $skipHandling required for paged search when cookies to
985
+     * prior results need to be gained
986
+     * @return bool cookie validity, true if we have more pages, false otherwise.
987
+     */
988
+    private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
989
+        $cookie = null;
990
+        if($pagedSearchOK) {
991
+            $cr = $this->connection->getConnectionResource();
992
+            foreach($sr as $key => $res) {
993
+                if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
994
+                    $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
995
+                }
996
+            }
997
+
998
+            //browsing through prior pages to get the cookie for the new one
999
+            if($skipHandling) {
1000
+                return false;
1001
+            }
1002
+            // if count is bigger, then the server does not support
1003
+            // paged search. Instead, he did a normal search. We set a
1004
+            // flag here, so the callee knows how to deal with it.
1005
+            if($iFoundItems <= $limit) {
1006
+                $this->pagedSearchedSuccessful = true;
1007
+            }
1008
+        } else {
1009
+            if(!is_null($limit)) {
1010
+                \OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO);
1011
+            }
1012
+        }
1013
+        /* ++ Fixing RHDS searches with pages with zero results ++
1014 1014
 		 * Return cookie status. If we don't have more pages, with RHDS
1015 1015
 		 * cookie is null, with openldap cookie is an empty string and
1016 1016
 		 * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0
1017 1017
 		 */
1018
-		return !empty($cookie) || $cookie === '0';
1019
-	}
1020
-
1021
-	/**
1022
-	 * executes an LDAP search, but counts the results only
1023
-	 * @param string $filter the LDAP filter for the search
1024
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1025
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1026
-	 * retrieved. Results will according to the order in the array.
1027
-	 * @param int $limit optional, maximum results to be counted
1028
-	 * @param int $offset optional, a starting point
1029
-	 * @param bool $skipHandling indicates whether the pages search operation is
1030
-	 * completed
1031
-	 * @return int|false Integer or false if the search could not be initialized
1032
-	 *
1033
-	 */
1034
-	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1035
-		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1036
-
1037
-		$limitPerPage = intval($this->connection->ldapPagingSize);
1038
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1039
-			$limitPerPage = $limit;
1040
-		}
1041
-
1042
-		$counter = 0;
1043
-		$count = null;
1044
-		$this->connection->getConnectionResource();
1045
-
1046
-		do {
1047
-			$search = $this->executeSearch($filter, $base, $attr,
1048
-										   $limitPerPage, $offset);
1049
-			if($search === false) {
1050
-				return $counter > 0 ? $counter : false;
1051
-			}
1052
-			list($sr, $pagedSearchOK) = $search;
1053
-
1054
-			/* ++ Fixing RHDS searches with pages with zero results ++
1018
+        return !empty($cookie) || $cookie === '0';
1019
+    }
1020
+
1021
+    /**
1022
+     * executes an LDAP search, but counts the results only
1023
+     * @param string $filter the LDAP filter for the search
1024
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1025
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1026
+     * retrieved. Results will according to the order in the array.
1027
+     * @param int $limit optional, maximum results to be counted
1028
+     * @param int $offset optional, a starting point
1029
+     * @param bool $skipHandling indicates whether the pages search operation is
1030
+     * completed
1031
+     * @return int|false Integer or false if the search could not be initialized
1032
+     *
1033
+     */
1034
+    private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1035
+        \OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1036
+
1037
+        $limitPerPage = intval($this->connection->ldapPagingSize);
1038
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1039
+            $limitPerPage = $limit;
1040
+        }
1041
+
1042
+        $counter = 0;
1043
+        $count = null;
1044
+        $this->connection->getConnectionResource();
1045
+
1046
+        do {
1047
+            $search = $this->executeSearch($filter, $base, $attr,
1048
+                                            $limitPerPage, $offset);
1049
+            if($search === false) {
1050
+                return $counter > 0 ? $counter : false;
1051
+            }
1052
+            list($sr, $pagedSearchOK) = $search;
1053
+
1054
+            /* ++ Fixing RHDS searches with pages with zero results ++
1055 1055
 			 * countEntriesInSearchResults() method signature changed
1056 1056
 			 * by removing $limit and &$hasHitLimit parameters
1057 1057
 			 */
1058
-			$count = $this->countEntriesInSearchResults($sr);
1059
-			$counter += $count;
1058
+            $count = $this->countEntriesInSearchResults($sr);
1059
+            $counter += $count;
1060 1060
 
1061
-			$hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1062
-										$offset, $pagedSearchOK, $skipHandling);
1063
-			$offset += $limitPerPage;
1064
-			/* ++ Fixing RHDS searches with pages with zero results ++
1061
+            $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1062
+                                        $offset, $pagedSearchOK, $skipHandling);
1063
+            $offset += $limitPerPage;
1064
+            /* ++ Fixing RHDS searches with pages with zero results ++
1065 1065
 			 * Continue now depends on $hasMorePages value
1066 1066
 			 */
1067
-			$continue = $pagedSearchOK && $hasMorePages;
1068
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1069
-
1070
-		return $counter;
1071
-	}
1072
-
1073
-	/**
1074
-	 * @param array $searchResults
1075
-	 * @return int
1076
-	 */
1077
-	private function countEntriesInSearchResults($searchResults) {
1078
-		$cr = $this->connection->getConnectionResource();
1079
-		$counter = 0;
1080
-
1081
-		foreach($searchResults as $res) {
1082
-			$count = intval($this->ldap->countEntries($cr, $res));
1083
-			$counter += $count;
1084
-		}
1085
-
1086
-		return $counter;
1087
-	}
1088
-
1089
-	/**
1090
-	 * Executes an LDAP search
1091
-	 * @param string $filter the LDAP filter for the search
1092
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1093
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1094
-	 * @param int $limit
1095
-	 * @param int $offset
1096
-	 * @param bool $skipHandling
1097
-	 * @return array with the search result
1098
-	 */
1099
-	private function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1100
-		if($limit <= 0) {
1101
-			//otherwise search will fail
1102
-			$limit = null;
1103
-		}
1104
-
1105
-		/* ++ Fixing RHDS searches with pages with zero results ++
1067
+            $continue = $pagedSearchOK && $hasMorePages;
1068
+        } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1069
+
1070
+        return $counter;
1071
+    }
1072
+
1073
+    /**
1074
+     * @param array $searchResults
1075
+     * @return int
1076
+     */
1077
+    private function countEntriesInSearchResults($searchResults) {
1078
+        $cr = $this->connection->getConnectionResource();
1079
+        $counter = 0;
1080
+
1081
+        foreach($searchResults as $res) {
1082
+            $count = intval($this->ldap->countEntries($cr, $res));
1083
+            $counter += $count;
1084
+        }
1085
+
1086
+        return $counter;
1087
+    }
1088
+
1089
+    /**
1090
+     * Executes an LDAP search
1091
+     * @param string $filter the LDAP filter for the search
1092
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1093
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1094
+     * @param int $limit
1095
+     * @param int $offset
1096
+     * @param bool $skipHandling
1097
+     * @return array with the search result
1098
+     */
1099
+    private function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1100
+        if($limit <= 0) {
1101
+            //otherwise search will fail
1102
+            $limit = null;
1103
+        }
1104
+
1105
+        /* ++ Fixing RHDS searches with pages with zero results ++
1106 1106
 		 * As we can have pages with zero results and/or pages with less
1107 1107
 		 * than $limit results but with a still valid server 'cookie',
1108 1108
 		 * loops through until we get $continue equals true and
1109 1109
 		 * $findings['count'] < $limit
1110 1110
 		 */
1111
-		$findings = array();
1112
-		$savedoffset = $offset;
1113
-		do {
1114
-			$search = $this->executeSearch($filter, $base, $attr, $limit, $offset);
1115
-			if($search === false) {
1116
-				return array();
1117
-			}
1118
-			list($sr, $pagedSearchOK) = $search;
1119
-			$cr = $this->connection->getConnectionResource();
1120
-
1121
-			if($skipHandling) {
1122
-				//i.e. result do not need to be fetched, we just need the cookie
1123
-				//thus pass 1 or any other value as $iFoundItems because it is not
1124
-				//used
1125
-				$this->processPagedSearchStatus($sr, $filter, $base, 1, $limit,
1126
-								$offset, $pagedSearchOK,
1127
-								$skipHandling);
1128
-				return array();
1129
-			}
1130
-
1131
-			foreach($sr as $res) {
1132
-				$findings = array_merge($findings, $this->ldap->getEntries($cr	, $res ));
1133
-			}
1134
-
1135
-			$continue = $this->processPagedSearchStatus($sr, $filter, $base, $findings['count'],
1136
-								$limit, $offset, $pagedSearchOK,
1137
-										$skipHandling);
1138
-			$offset += $limit;
1139
-		} while ($continue && $pagedSearchOK && $findings['count'] < $limit);
1140
-		// reseting offset
1141
-		$offset = $savedoffset;
1142
-
1143
-		// if we're here, probably no connection resource is returned.
1144
-		// to make ownCloud behave nicely, we simply give back an empty array.
1145
-		if(is_null($findings)) {
1146
-			return array();
1147
-		}
1148
-
1149
-		if(!is_null($attr)) {
1150
-			$selection = array();
1151
-			$i = 0;
1152
-			foreach($findings as $item) {
1153
-				if(!is_array($item)) {
1154
-					continue;
1155
-				}
1156
-				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1157
-				foreach($attr as $key) {
1158
-					$key = mb_strtolower($key, 'UTF-8');
1159
-					if(isset($item[$key])) {
1160
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1161
-							unset($item[$key]['count']);
1162
-						}
1163
-						if($key !== 'dn') {
1164
-							$selection[$i][$key] = $this->resemblesDN($key) ?
1165
-								$this->helper->sanitizeDN($item[$key])
1166
-								: $item[$key];
1167
-						} else {
1168
-							$selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1169
-						}
1170
-					}
1171
-
1172
-				}
1173
-				$i++;
1174
-			}
1175
-			$findings = $selection;
1176
-		}
1177
-		//we slice the findings, when
1178
-		//a) paged search unsuccessful, though attempted
1179
-		//b) no paged search, but limit set
1180
-		if((!$this->getPagedSearchResultState()
1181
-			&& $pagedSearchOK)
1182
-			|| (
1183
-				!$pagedSearchOK
1184
-				&& !is_null($limit)
1185
-			)
1186
-		) {
1187
-			$findings = array_slice($findings, intval($offset), $limit);
1188
-		}
1189
-		return $findings;
1190
-	}
1191
-
1192
-	/**
1193
-	 * @param string $name
1194
-	 * @return bool|mixed|string
1195
-	 */
1196
-	public function sanitizeUsername($name) {
1197
-		if($this->connection->ldapIgnoreNamingRules) {
1198
-			return $name;
1199
-		}
1200
-
1201
-		// Transliteration
1202
-		// latin characters to ASCII
1203
-		$name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1204
-
1205
-		// Replacements
1206
-		$name = str_replace(' ', '_', $name);
1207
-
1208
-		// Every remaining disallowed characters will be removed
1209
-		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1210
-
1211
-		return $name;
1212
-	}
1213
-
1214
-	/**
1215
-	* escapes (user provided) parts for LDAP filter
1216
-	* @param string $input, the provided value
1217
-	* @param bool $allowAsterisk whether in * at the beginning should be preserved
1218
-	* @return string the escaped string
1219
-	*/
1220
-	public function escapeFilterPart($input, $allowAsterisk = false) {
1221
-		$asterisk = '';
1222
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1223
-			$asterisk = '*';
1224
-			$input = mb_substr($input, 1, null, 'UTF-8');
1225
-		}
1226
-		$search  = array('*', '\\', '(', ')');
1227
-		$replace = array('\\*', '\\\\', '\\(', '\\)');
1228
-		return $asterisk . str_replace($search, $replace, $input);
1229
-	}
1230
-
1231
-	/**
1232
-	 * combines the input filters with AND
1233
-	 * @param string[] $filters the filters to connect
1234
-	 * @return string the combined filter
1235
-	 */
1236
-	public function combineFilterWithAnd($filters) {
1237
-		return $this->combineFilter($filters, '&');
1238
-	}
1239
-
1240
-	/**
1241
-	 * combines the input filters with OR
1242
-	 * @param string[] $filters the filters to connect
1243
-	 * @return string the combined filter
1244
-	 * Combines Filter arguments with OR
1245
-	 */
1246
-	public function combineFilterWithOr($filters) {
1247
-		return $this->combineFilter($filters, '|');
1248
-	}
1249
-
1250
-	/**
1251
-	 * combines the input filters with given operator
1252
-	 * @param string[] $filters the filters to connect
1253
-	 * @param string $operator either & or |
1254
-	 * @return string the combined filter
1255
-	 */
1256
-	private function combineFilter($filters, $operator) {
1257
-		$combinedFilter = '('.$operator;
1258
-		foreach($filters as $filter) {
1259
-			if ($filter !== '' && $filter[0] !== '(') {
1260
-				$filter = '('.$filter.')';
1261
-			}
1262
-			$combinedFilter.=$filter;
1263
-		}
1264
-		$combinedFilter.=')';
1265
-		return $combinedFilter;
1266
-	}
1267
-
1268
-	/**
1269
-	 * creates a filter part for to perform search for users
1270
-	 * @param string $search the search term
1271
-	 * @return string the final filter part to use in LDAP searches
1272
-	 */
1273
-	public function getFilterPartForUserSearch($search) {
1274
-		return $this->getFilterPartForSearch($search,
1275
-			$this->connection->ldapAttributesForUserSearch,
1276
-			$this->connection->ldapUserDisplayName);
1277
-	}
1278
-
1279
-	/**
1280
-	 * creates a filter part for to perform search for groups
1281
-	 * @param string $search the search term
1282
-	 * @return string the final filter part to use in LDAP searches
1283
-	 */
1284
-	public function getFilterPartForGroupSearch($search) {
1285
-		return $this->getFilterPartForSearch($search,
1286
-			$this->connection->ldapAttributesForGroupSearch,
1287
-			$this->connection->ldapGroupDisplayName);
1288
-	}
1289
-
1290
-	/**
1291
-	 * creates a filter part for searches by splitting up the given search
1292
-	 * string into single words
1293
-	 * @param string $search the search term
1294
-	 * @param string[] $searchAttributes needs to have at least two attributes,
1295
-	 * otherwise it does not make sense :)
1296
-	 * @return string the final filter part to use in LDAP searches
1297
-	 * @throws \Exception
1298
-	 */
1299
-	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1300
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1301
-			throw new \Exception('searchAttributes must be an array with at least two string');
1302
-		}
1303
-		$searchWords = explode(' ', trim($search));
1304
-		$wordFilters = array();
1305
-		foreach($searchWords as $word) {
1306
-			$word = $this->prepareSearchTerm($word);
1307
-			//every word needs to appear at least once
1308
-			$wordMatchOneAttrFilters = array();
1309
-			foreach($searchAttributes as $attr) {
1310
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1311
-			}
1312
-			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1313
-		}
1314
-		return $this->combineFilterWithAnd($wordFilters);
1315
-	}
1316
-
1317
-	/**
1318
-	 * creates a filter part for searches
1319
-	 * @param string $search the search term
1320
-	 * @param string[]|null $searchAttributes
1321
-	 * @param string $fallbackAttribute a fallback attribute in case the user
1322
-	 * did not define search attributes. Typically the display name attribute.
1323
-	 * @return string the final filter part to use in LDAP searches
1324
-	 */
1325
-	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1326
-		$filter = array();
1327
-		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1328
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1329
-			try {
1330
-				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1331
-			} catch(\Exception $e) {
1332
-				\OCP\Util::writeLog(
1333
-					'user_ldap',
1334
-					'Creating advanced filter for search failed, falling back to simple method.',
1335
-					\OCP\Util::INFO
1336
-				);
1337
-			}
1338
-		}
1339
-
1340
-		$search = $this->prepareSearchTerm($search);
1341
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1342
-			if ($fallbackAttribute === '') {
1343
-				return '';
1344
-			}
1345
-			$filter[] = $fallbackAttribute . '=' . $search;
1346
-		} else {
1347
-			foreach($searchAttributes as $attribute) {
1348
-				$filter[] = $attribute . '=' . $search;
1349
-			}
1350
-		}
1351
-		if(count($filter) === 1) {
1352
-			return '('.$filter[0].')';
1353
-		}
1354
-		return $this->combineFilterWithOr($filter);
1355
-	}
1356
-
1357
-	/**
1358
-	 * returns the search term depending on whether we are allowed
1359
-	 * list users found by ldap with the current input appended by
1360
-	 * a *
1361
-	 * @return string
1362
-	 */
1363
-	private function prepareSearchTerm($term) {
1364
-		$config = \OC::$server->getConfig();
1365
-
1366
-		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1367
-
1368
-		$result = $term;
1369
-		if ($term === '') {
1370
-			$result = '*';
1371
-		} else if ($allowEnum !== 'no') {
1372
-			$result = $term . '*';
1373
-		}
1374
-		return $result;
1375
-	}
1376
-
1377
-	/**
1378
-	 * returns the filter used for counting users
1379
-	 * @return string
1380
-	 */
1381
-	public function getFilterForUserCount() {
1382
-		$filter = $this->combineFilterWithAnd(array(
1383
-			$this->connection->ldapUserFilter,
1384
-			$this->connection->ldapUserDisplayName . '=*'
1385
-		));
1386
-
1387
-		return $filter;
1388
-	}
1389
-
1390
-	/**
1391
-	 * @param string $name
1392
-	 * @param string $password
1393
-	 * @return bool
1394
-	 */
1395
-	public function areCredentialsValid($name, $password) {
1396
-		$name = $this->helper->DNasBaseParameter($name);
1397
-		$testConnection = clone $this->connection;
1398
-		$credentials = array(
1399
-			'ldapAgentName' => $name,
1400
-			'ldapAgentPassword' => $password
1401
-		);
1402
-		if(!$testConnection->setConfiguration($credentials)) {
1403
-			return false;
1404
-		}
1405
-		return $testConnection->bind();
1406
-	}
1407
-
1408
-	/**
1409
-	 * reverse lookup of a DN given a known UUID
1410
-	 *
1411
-	 * @param string $uuid
1412
-	 * @return string
1413
-	 * @throws \Exception
1414
-	 */
1415
-	public function getUserDnByUuid($uuid) {
1416
-		$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1417
-		$filter       = $this->connection->ldapUserFilter;
1418
-		$base         = $this->connection->ldapBaseUsers;
1419
-
1420
-		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1421
-			// Sacrebleu! The UUID attribute is unknown :( We need first an
1422
-			// existing DN to be able to reliably detect it.
1423
-			$result = $this->search($filter, $base, ['dn'], 1);
1424
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1425
-				throw new \Exception('Cannot determine UUID attribute');
1426
-			}
1427
-			$dn = $result[0]['dn'][0];
1428
-			if(!$this->detectUuidAttribute($dn, true)) {
1429
-				throw new \Exception('Cannot determine UUID attribute');
1430
-			}
1431
-		} else {
1432
-			// The UUID attribute is either known or an override is given.
1433
-			// By calling this method we ensure that $this->connection->$uuidAttr
1434
-			// is definitely set
1435
-			if(!$this->detectUuidAttribute('', true)) {
1436
-				throw new \Exception('Cannot determine UUID attribute');
1437
-			}
1438
-		}
1439
-
1440
-		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1441
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1442
-			$uuid = $this->formatGuid2ForFilterUser($uuid);
1443
-		}
1444
-
1445
-		$filter = $uuidAttr . '=' . $uuid;
1446
-		$result = $this->searchUsers($filter, ['dn'], 2);
1447
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1448
-			// we put the count into account to make sure that this is
1449
-			// really unique
1450
-			return $result[0]['dn'][0];
1451
-		}
1452
-
1453
-		throw new \Exception('Cannot determine UUID attribute');
1454
-	}
1455
-
1456
-	/**
1457
-	 * auto-detects the directory's UUID attribute
1458
-	 * @param string $dn a known DN used to check against
1459
-	 * @param bool $isUser
1460
-	 * @param bool $force the detection should be run, even if it is not set to auto
1461
-	 * @return bool true on success, false otherwise
1462
-	 */
1463
-	private function detectUuidAttribute($dn, $isUser = true, $force = false) {
1464
-		if($isUser) {
1465
-			$uuidAttr     = 'ldapUuidUserAttribute';
1466
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1467
-		} else {
1468
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1469
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1470
-		}
1471
-
1472
-		if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1473
-			return true;
1474
-		}
1475
-
1476
-		if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1477
-			$this->connection->$uuidAttr = $uuidOverride;
1478
-			return true;
1479
-		}
1480
-
1481
-		// for now, supported attributes are entryUUID, nsuniqueid, objectGUID, ipaUniqueID
1482
-		$testAttributes = array('entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid');
1483
-
1484
-		foreach($testAttributes as $attribute) {
1485
-			$value = $this->readAttribute($dn, $attribute);
1486
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1487
-				\OCP\Util::writeLog('user_ldap',
1488
-									'Setting '.$attribute.' as '.$uuidAttr,
1489
-									\OCP\Util::DEBUG);
1490
-				$this->connection->$uuidAttr = $attribute;
1491
-				return true;
1492
-			}
1493
-		}
1494
-		\OCP\Util::writeLog('user_ldap',
1495
-							'Could not autodetect the UUID attribute',
1496
-							\OCP\Util::ERROR);
1497
-
1498
-		return false;
1499
-	}
1500
-
1501
-	/**
1502
-	 * @param string $dn
1503
-	 * @param bool $isUser
1504
-	 * @return string|bool
1505
-	 */
1506
-	public function getUUID($dn, $isUser = true) {
1507
-		if($isUser) {
1508
-			$uuidAttr     = 'ldapUuidUserAttribute';
1509
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1510
-		} else {
1511
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1512
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1513
-		}
1514
-
1515
-		$uuid = false;
1516
-		if($this->detectUuidAttribute($dn, $isUser)) {
1517
-			$uuid = $this->readAttribute($dn, $this->connection->$uuidAttr);
1518
-			if( !is_array($uuid)
1519
-				&& $uuidOverride !== ''
1520
-				&& $this->detectUuidAttribute($dn, $isUser, true)) {
1521
-					$uuid = $this->readAttribute($dn,
1522
-												 $this->connection->$uuidAttr);
1523
-			}
1524
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1525
-				$uuid = $uuid[0];
1526
-			}
1527
-		}
1528
-
1529
-		return $uuid;
1530
-	}
1531
-
1532
-	/**
1533
-	 * converts a binary ObjectGUID into a string representation
1534
-	 * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1535
-	 * @return string
1536
-	 * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1537
-	 */
1538
-	private function convertObjectGUID2Str($oguid) {
1539
-		$hex_guid = bin2hex($oguid);
1540
-		$hex_guid_to_guid_str = '';
1541
-		for($k = 1; $k <= 4; ++$k) {
1542
-			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1543
-		}
1544
-		$hex_guid_to_guid_str .= '-';
1545
-		for($k = 1; $k <= 2; ++$k) {
1546
-			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1547
-		}
1548
-		$hex_guid_to_guid_str .= '-';
1549
-		for($k = 1; $k <= 2; ++$k) {
1550
-			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1551
-		}
1552
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1553
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1554
-
1555
-		return strtoupper($hex_guid_to_guid_str);
1556
-	}
1557
-
1558
-	/**
1559
-	 * the first three blocks of the string-converted GUID happen to be in
1560
-	 * reverse order. In order to use it in a filter, this needs to be
1561
-	 * corrected. Furthermore the dashes need to be replaced and \\ preprended
1562
-	 * to every two hax figures.
1563
-	 *
1564
-	 * If an invalid string is passed, it will be returned without change.
1565
-	 *
1566
-	 * @param string $guid
1567
-	 * @return string
1568
-	 */
1569
-	public function formatGuid2ForFilterUser($guid) {
1570
-		if(!is_string($guid)) {
1571
-			throw new \InvalidArgumentException('String expected');
1572
-		}
1573
-		$blocks = explode('-', $guid);
1574
-		if(count($blocks) !== 5) {
1575
-			/*
1111
+        $findings = array();
1112
+        $savedoffset = $offset;
1113
+        do {
1114
+            $search = $this->executeSearch($filter, $base, $attr, $limit, $offset);
1115
+            if($search === false) {
1116
+                return array();
1117
+            }
1118
+            list($sr, $pagedSearchOK) = $search;
1119
+            $cr = $this->connection->getConnectionResource();
1120
+
1121
+            if($skipHandling) {
1122
+                //i.e. result do not need to be fetched, we just need the cookie
1123
+                //thus pass 1 or any other value as $iFoundItems because it is not
1124
+                //used
1125
+                $this->processPagedSearchStatus($sr, $filter, $base, 1, $limit,
1126
+                                $offset, $pagedSearchOK,
1127
+                                $skipHandling);
1128
+                return array();
1129
+            }
1130
+
1131
+            foreach($sr as $res) {
1132
+                $findings = array_merge($findings, $this->ldap->getEntries($cr	, $res ));
1133
+            }
1134
+
1135
+            $continue = $this->processPagedSearchStatus($sr, $filter, $base, $findings['count'],
1136
+                                $limit, $offset, $pagedSearchOK,
1137
+                                        $skipHandling);
1138
+            $offset += $limit;
1139
+        } while ($continue && $pagedSearchOK && $findings['count'] < $limit);
1140
+        // reseting offset
1141
+        $offset = $savedoffset;
1142
+
1143
+        // if we're here, probably no connection resource is returned.
1144
+        // to make ownCloud behave nicely, we simply give back an empty array.
1145
+        if(is_null($findings)) {
1146
+            return array();
1147
+        }
1148
+
1149
+        if(!is_null($attr)) {
1150
+            $selection = array();
1151
+            $i = 0;
1152
+            foreach($findings as $item) {
1153
+                if(!is_array($item)) {
1154
+                    continue;
1155
+                }
1156
+                $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1157
+                foreach($attr as $key) {
1158
+                    $key = mb_strtolower($key, 'UTF-8');
1159
+                    if(isset($item[$key])) {
1160
+                        if(is_array($item[$key]) && isset($item[$key]['count'])) {
1161
+                            unset($item[$key]['count']);
1162
+                        }
1163
+                        if($key !== 'dn') {
1164
+                            $selection[$i][$key] = $this->resemblesDN($key) ?
1165
+                                $this->helper->sanitizeDN($item[$key])
1166
+                                : $item[$key];
1167
+                        } else {
1168
+                            $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1169
+                        }
1170
+                    }
1171
+
1172
+                }
1173
+                $i++;
1174
+            }
1175
+            $findings = $selection;
1176
+        }
1177
+        //we slice the findings, when
1178
+        //a) paged search unsuccessful, though attempted
1179
+        //b) no paged search, but limit set
1180
+        if((!$this->getPagedSearchResultState()
1181
+            && $pagedSearchOK)
1182
+            || (
1183
+                !$pagedSearchOK
1184
+                && !is_null($limit)
1185
+            )
1186
+        ) {
1187
+            $findings = array_slice($findings, intval($offset), $limit);
1188
+        }
1189
+        return $findings;
1190
+    }
1191
+
1192
+    /**
1193
+     * @param string $name
1194
+     * @return bool|mixed|string
1195
+     */
1196
+    public function sanitizeUsername($name) {
1197
+        if($this->connection->ldapIgnoreNamingRules) {
1198
+            return $name;
1199
+        }
1200
+
1201
+        // Transliteration
1202
+        // latin characters to ASCII
1203
+        $name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1204
+
1205
+        // Replacements
1206
+        $name = str_replace(' ', '_', $name);
1207
+
1208
+        // Every remaining disallowed characters will be removed
1209
+        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1210
+
1211
+        return $name;
1212
+    }
1213
+
1214
+    /**
1215
+     * escapes (user provided) parts for LDAP filter
1216
+     * @param string $input, the provided value
1217
+     * @param bool $allowAsterisk whether in * at the beginning should be preserved
1218
+     * @return string the escaped string
1219
+     */
1220
+    public function escapeFilterPart($input, $allowAsterisk = false) {
1221
+        $asterisk = '';
1222
+        if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1223
+            $asterisk = '*';
1224
+            $input = mb_substr($input, 1, null, 'UTF-8');
1225
+        }
1226
+        $search  = array('*', '\\', '(', ')');
1227
+        $replace = array('\\*', '\\\\', '\\(', '\\)');
1228
+        return $asterisk . str_replace($search, $replace, $input);
1229
+    }
1230
+
1231
+    /**
1232
+     * combines the input filters with AND
1233
+     * @param string[] $filters the filters to connect
1234
+     * @return string the combined filter
1235
+     */
1236
+    public function combineFilterWithAnd($filters) {
1237
+        return $this->combineFilter($filters, '&');
1238
+    }
1239
+
1240
+    /**
1241
+     * combines the input filters with OR
1242
+     * @param string[] $filters the filters to connect
1243
+     * @return string the combined filter
1244
+     * Combines Filter arguments with OR
1245
+     */
1246
+    public function combineFilterWithOr($filters) {
1247
+        return $this->combineFilter($filters, '|');
1248
+    }
1249
+
1250
+    /**
1251
+     * combines the input filters with given operator
1252
+     * @param string[] $filters the filters to connect
1253
+     * @param string $operator either & or |
1254
+     * @return string the combined filter
1255
+     */
1256
+    private function combineFilter($filters, $operator) {
1257
+        $combinedFilter = '('.$operator;
1258
+        foreach($filters as $filter) {
1259
+            if ($filter !== '' && $filter[0] !== '(') {
1260
+                $filter = '('.$filter.')';
1261
+            }
1262
+            $combinedFilter.=$filter;
1263
+        }
1264
+        $combinedFilter.=')';
1265
+        return $combinedFilter;
1266
+    }
1267
+
1268
+    /**
1269
+     * creates a filter part for to perform search for users
1270
+     * @param string $search the search term
1271
+     * @return string the final filter part to use in LDAP searches
1272
+     */
1273
+    public function getFilterPartForUserSearch($search) {
1274
+        return $this->getFilterPartForSearch($search,
1275
+            $this->connection->ldapAttributesForUserSearch,
1276
+            $this->connection->ldapUserDisplayName);
1277
+    }
1278
+
1279
+    /**
1280
+     * creates a filter part for to perform search for groups
1281
+     * @param string $search the search term
1282
+     * @return string the final filter part to use in LDAP searches
1283
+     */
1284
+    public function getFilterPartForGroupSearch($search) {
1285
+        return $this->getFilterPartForSearch($search,
1286
+            $this->connection->ldapAttributesForGroupSearch,
1287
+            $this->connection->ldapGroupDisplayName);
1288
+    }
1289
+
1290
+    /**
1291
+     * creates a filter part for searches by splitting up the given search
1292
+     * string into single words
1293
+     * @param string $search the search term
1294
+     * @param string[] $searchAttributes needs to have at least two attributes,
1295
+     * otherwise it does not make sense :)
1296
+     * @return string the final filter part to use in LDAP searches
1297
+     * @throws \Exception
1298
+     */
1299
+    private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1300
+        if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1301
+            throw new \Exception('searchAttributes must be an array with at least two string');
1302
+        }
1303
+        $searchWords = explode(' ', trim($search));
1304
+        $wordFilters = array();
1305
+        foreach($searchWords as $word) {
1306
+            $word = $this->prepareSearchTerm($word);
1307
+            //every word needs to appear at least once
1308
+            $wordMatchOneAttrFilters = array();
1309
+            foreach($searchAttributes as $attr) {
1310
+                $wordMatchOneAttrFilters[] = $attr . '=' . $word;
1311
+            }
1312
+            $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1313
+        }
1314
+        return $this->combineFilterWithAnd($wordFilters);
1315
+    }
1316
+
1317
+    /**
1318
+     * creates a filter part for searches
1319
+     * @param string $search the search term
1320
+     * @param string[]|null $searchAttributes
1321
+     * @param string $fallbackAttribute a fallback attribute in case the user
1322
+     * did not define search attributes. Typically the display name attribute.
1323
+     * @return string the final filter part to use in LDAP searches
1324
+     */
1325
+    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1326
+        $filter = array();
1327
+        $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1328
+        if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1329
+            try {
1330
+                return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1331
+            } catch(\Exception $e) {
1332
+                \OCP\Util::writeLog(
1333
+                    'user_ldap',
1334
+                    'Creating advanced filter for search failed, falling back to simple method.',
1335
+                    \OCP\Util::INFO
1336
+                );
1337
+            }
1338
+        }
1339
+
1340
+        $search = $this->prepareSearchTerm($search);
1341
+        if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1342
+            if ($fallbackAttribute === '') {
1343
+                return '';
1344
+            }
1345
+            $filter[] = $fallbackAttribute . '=' . $search;
1346
+        } else {
1347
+            foreach($searchAttributes as $attribute) {
1348
+                $filter[] = $attribute . '=' . $search;
1349
+            }
1350
+        }
1351
+        if(count($filter) === 1) {
1352
+            return '('.$filter[0].')';
1353
+        }
1354
+        return $this->combineFilterWithOr($filter);
1355
+    }
1356
+
1357
+    /**
1358
+     * returns the search term depending on whether we are allowed
1359
+     * list users found by ldap with the current input appended by
1360
+     * a *
1361
+     * @return string
1362
+     */
1363
+    private function prepareSearchTerm($term) {
1364
+        $config = \OC::$server->getConfig();
1365
+
1366
+        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1367
+
1368
+        $result = $term;
1369
+        if ($term === '') {
1370
+            $result = '*';
1371
+        } else if ($allowEnum !== 'no') {
1372
+            $result = $term . '*';
1373
+        }
1374
+        return $result;
1375
+    }
1376
+
1377
+    /**
1378
+     * returns the filter used for counting users
1379
+     * @return string
1380
+     */
1381
+    public function getFilterForUserCount() {
1382
+        $filter = $this->combineFilterWithAnd(array(
1383
+            $this->connection->ldapUserFilter,
1384
+            $this->connection->ldapUserDisplayName . '=*'
1385
+        ));
1386
+
1387
+        return $filter;
1388
+    }
1389
+
1390
+    /**
1391
+     * @param string $name
1392
+     * @param string $password
1393
+     * @return bool
1394
+     */
1395
+    public function areCredentialsValid($name, $password) {
1396
+        $name = $this->helper->DNasBaseParameter($name);
1397
+        $testConnection = clone $this->connection;
1398
+        $credentials = array(
1399
+            'ldapAgentName' => $name,
1400
+            'ldapAgentPassword' => $password
1401
+        );
1402
+        if(!$testConnection->setConfiguration($credentials)) {
1403
+            return false;
1404
+        }
1405
+        return $testConnection->bind();
1406
+    }
1407
+
1408
+    /**
1409
+     * reverse lookup of a DN given a known UUID
1410
+     *
1411
+     * @param string $uuid
1412
+     * @return string
1413
+     * @throws \Exception
1414
+     */
1415
+    public function getUserDnByUuid($uuid) {
1416
+        $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1417
+        $filter       = $this->connection->ldapUserFilter;
1418
+        $base         = $this->connection->ldapBaseUsers;
1419
+
1420
+        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1421
+            // Sacrebleu! The UUID attribute is unknown :( We need first an
1422
+            // existing DN to be able to reliably detect it.
1423
+            $result = $this->search($filter, $base, ['dn'], 1);
1424
+            if(!isset($result[0]) || !isset($result[0]['dn'])) {
1425
+                throw new \Exception('Cannot determine UUID attribute');
1426
+            }
1427
+            $dn = $result[0]['dn'][0];
1428
+            if(!$this->detectUuidAttribute($dn, true)) {
1429
+                throw new \Exception('Cannot determine UUID attribute');
1430
+            }
1431
+        } else {
1432
+            // The UUID attribute is either known or an override is given.
1433
+            // By calling this method we ensure that $this->connection->$uuidAttr
1434
+            // is definitely set
1435
+            if(!$this->detectUuidAttribute('', true)) {
1436
+                throw new \Exception('Cannot determine UUID attribute');
1437
+            }
1438
+        }
1439
+
1440
+        $uuidAttr = $this->connection->ldapUuidUserAttribute;
1441
+        if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1442
+            $uuid = $this->formatGuid2ForFilterUser($uuid);
1443
+        }
1444
+
1445
+        $filter = $uuidAttr . '=' . $uuid;
1446
+        $result = $this->searchUsers($filter, ['dn'], 2);
1447
+        if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1448
+            // we put the count into account to make sure that this is
1449
+            // really unique
1450
+            return $result[0]['dn'][0];
1451
+        }
1452
+
1453
+        throw new \Exception('Cannot determine UUID attribute');
1454
+    }
1455
+
1456
+    /**
1457
+     * auto-detects the directory's UUID attribute
1458
+     * @param string $dn a known DN used to check against
1459
+     * @param bool $isUser
1460
+     * @param bool $force the detection should be run, even if it is not set to auto
1461
+     * @return bool true on success, false otherwise
1462
+     */
1463
+    private function detectUuidAttribute($dn, $isUser = true, $force = false) {
1464
+        if($isUser) {
1465
+            $uuidAttr     = 'ldapUuidUserAttribute';
1466
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1467
+        } else {
1468
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1469
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1470
+        }
1471
+
1472
+        if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1473
+            return true;
1474
+        }
1475
+
1476
+        if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1477
+            $this->connection->$uuidAttr = $uuidOverride;
1478
+            return true;
1479
+        }
1480
+
1481
+        // for now, supported attributes are entryUUID, nsuniqueid, objectGUID, ipaUniqueID
1482
+        $testAttributes = array('entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid');
1483
+
1484
+        foreach($testAttributes as $attribute) {
1485
+            $value = $this->readAttribute($dn, $attribute);
1486
+            if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1487
+                \OCP\Util::writeLog('user_ldap',
1488
+                                    'Setting '.$attribute.' as '.$uuidAttr,
1489
+                                    \OCP\Util::DEBUG);
1490
+                $this->connection->$uuidAttr = $attribute;
1491
+                return true;
1492
+            }
1493
+        }
1494
+        \OCP\Util::writeLog('user_ldap',
1495
+                            'Could not autodetect the UUID attribute',
1496
+                            \OCP\Util::ERROR);
1497
+
1498
+        return false;
1499
+    }
1500
+
1501
+    /**
1502
+     * @param string $dn
1503
+     * @param bool $isUser
1504
+     * @return string|bool
1505
+     */
1506
+    public function getUUID($dn, $isUser = true) {
1507
+        if($isUser) {
1508
+            $uuidAttr     = 'ldapUuidUserAttribute';
1509
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1510
+        } else {
1511
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1512
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1513
+        }
1514
+
1515
+        $uuid = false;
1516
+        if($this->detectUuidAttribute($dn, $isUser)) {
1517
+            $uuid = $this->readAttribute($dn, $this->connection->$uuidAttr);
1518
+            if( !is_array($uuid)
1519
+                && $uuidOverride !== ''
1520
+                && $this->detectUuidAttribute($dn, $isUser, true)) {
1521
+                    $uuid = $this->readAttribute($dn,
1522
+                                                    $this->connection->$uuidAttr);
1523
+            }
1524
+            if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1525
+                $uuid = $uuid[0];
1526
+            }
1527
+        }
1528
+
1529
+        return $uuid;
1530
+    }
1531
+
1532
+    /**
1533
+     * converts a binary ObjectGUID into a string representation
1534
+     * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1535
+     * @return string
1536
+     * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1537
+     */
1538
+    private function convertObjectGUID2Str($oguid) {
1539
+        $hex_guid = bin2hex($oguid);
1540
+        $hex_guid_to_guid_str = '';
1541
+        for($k = 1; $k <= 4; ++$k) {
1542
+            $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1543
+        }
1544
+        $hex_guid_to_guid_str .= '-';
1545
+        for($k = 1; $k <= 2; ++$k) {
1546
+            $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1547
+        }
1548
+        $hex_guid_to_guid_str .= '-';
1549
+        for($k = 1; $k <= 2; ++$k) {
1550
+            $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1551
+        }
1552
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1553
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1554
+
1555
+        return strtoupper($hex_guid_to_guid_str);
1556
+    }
1557
+
1558
+    /**
1559
+     * the first three blocks of the string-converted GUID happen to be in
1560
+     * reverse order. In order to use it in a filter, this needs to be
1561
+     * corrected. Furthermore the dashes need to be replaced and \\ preprended
1562
+     * to every two hax figures.
1563
+     *
1564
+     * If an invalid string is passed, it will be returned without change.
1565
+     *
1566
+     * @param string $guid
1567
+     * @return string
1568
+     */
1569
+    public function formatGuid2ForFilterUser($guid) {
1570
+        if(!is_string($guid)) {
1571
+            throw new \InvalidArgumentException('String expected');
1572
+        }
1573
+        $blocks = explode('-', $guid);
1574
+        if(count($blocks) !== 5) {
1575
+            /*
1576 1576
 			 * Why not throw an Exception instead? This method is a utility
1577 1577
 			 * called only when trying to figure out whether a "missing" known
1578 1578
 			 * LDAP user was or was not renamed on the LDAP server. And this
@@ -1583,275 +1583,275 @@  discard block
 block discarded – undo
1583 1583
 			 * an exception here would kill the experience for a valid, acting
1584 1584
 			 * user. Instead we write a log message.
1585 1585
 			 */
1586
-			\OC::$server->getLogger()->info(
1587
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1588
-				'({uuid}) probably does not match UUID configuration.',
1589
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1590
-			);
1591
-			return $guid;
1592
-		}
1593
-		for($i=0; $i < 3; $i++) {
1594
-			$pairs = str_split($blocks[$i], 2);
1595
-			$pairs = array_reverse($pairs);
1596
-			$blocks[$i] = implode('', $pairs);
1597
-		}
1598
-		for($i=0; $i < 5; $i++) {
1599
-			$pairs = str_split($blocks[$i], 2);
1600
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1601
-		}
1602
-		return implode('', $blocks);
1603
-	}
1604
-
1605
-	/**
1606
-	 * gets a SID of the domain of the given dn
1607
-	 * @param string $dn
1608
-	 * @return string|bool
1609
-	 */
1610
-	public function getSID($dn) {
1611
-		$domainDN = $this->getDomainDNFromDN($dn);
1612
-		$cacheKey = 'getSID-'.$domainDN;
1613
-		$sid = $this->connection->getFromCache($cacheKey);
1614
-		if(!is_null($sid)) {
1615
-			return $sid;
1616
-		}
1617
-
1618
-		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1619
-		if(!is_array($objectSid) || empty($objectSid)) {
1620
-			$this->connection->writeToCache($cacheKey, false);
1621
-			return false;
1622
-		}
1623
-		$domainObjectSid = $this->convertSID2Str($objectSid[0]);
1624
-		$this->connection->writeToCache($cacheKey, $domainObjectSid);
1625
-
1626
-		return $domainObjectSid;
1627
-	}
1628
-
1629
-	/**
1630
-	 * converts a binary SID into a string representation
1631
-	 * @param string $sid
1632
-	 * @return string
1633
-	 */
1634
-	public function convertSID2Str($sid) {
1635
-		// The format of a SID binary string is as follows:
1636
-		// 1 byte for the revision level
1637
-		// 1 byte for the number n of variable sub-ids
1638
-		// 6 bytes for identifier authority value
1639
-		// n*4 bytes for n sub-ids
1640
-		//
1641
-		// Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1642
-		//  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1643
-		$revision = ord($sid[0]);
1644
-		$numberSubID = ord($sid[1]);
1645
-
1646
-		$subIdStart = 8; // 1 + 1 + 6
1647
-		$subIdLength = 4;
1648
-		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1649
-			// Incorrect number of bytes present.
1650
-			return '';
1651
-		}
1652
-
1653
-		// 6 bytes = 48 bits can be represented using floats without loss of
1654
-		// precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1655
-		$iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1656
-
1657
-		$subIDs = array();
1658
-		for ($i = 0; $i < $numberSubID; $i++) {
1659
-			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1660
-			$subIDs[] = sprintf('%u', $subID[1]);
1661
-		}
1662
-
1663
-		// Result for example above: S-1-5-21-249921958-728525901-1594176202
1664
-		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1665
-	}
1666
-
1667
-	/**
1668
-	 * checks if the given DN is part of the given base DN(s)
1669
-	 * @param string $dn the DN
1670
-	 * @param string[] $bases array containing the allowed base DN or DNs
1671
-	 * @return bool
1672
-	 */
1673
-	public function isDNPartOfBase($dn, $bases) {
1674
-		$belongsToBase = false;
1675
-		$bases = $this->helper->sanitizeDN($bases);
1676
-
1677
-		foreach($bases as $base) {
1678
-			$belongsToBase = true;
1679
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1680
-				$belongsToBase = false;
1681
-			}
1682
-			if($belongsToBase) {
1683
-				break;
1684
-			}
1685
-		}
1686
-		return $belongsToBase;
1687
-	}
1688
-
1689
-	/**
1690
-	 * resets a running Paged Search operation
1691
-	 */
1692
-	private function abandonPagedSearch() {
1693
-		if($this->connection->hasPagedResultSupport) {
1694
-			$cr = $this->connection->getConnectionResource();
1695
-			$this->ldap->controlPagedResult($cr, 0, false, $this->lastCookie);
1696
-			$this->getPagedSearchResultState();
1697
-			$this->lastCookie = '';
1698
-			$this->cookies = array();
1699
-		}
1700
-	}
1701
-
1702
-	/**
1703
-	 * get a cookie for the next LDAP paged search
1704
-	 * @param string $base a string with the base DN for the search
1705
-	 * @param string $filter the search filter to identify the correct search
1706
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1707
-	 * @param int $offset the offset for the new search to identify the correct search really good
1708
-	 * @return string containing the key or empty if none is cached
1709
-	 */
1710
-	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1711
-		if($offset === 0) {
1712
-			return '';
1713
-		}
1714
-		$offset -= $limit;
1715
-		//we work with cache here
1716
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1717
-		$cookie = '';
1718
-		if(isset($this->cookies[$cacheKey])) {
1719
-			$cookie = $this->cookies[$cacheKey];
1720
-			if(is_null($cookie)) {
1721
-				$cookie = '';
1722
-			}
1723
-		}
1724
-		return $cookie;
1725
-	}
1726
-
1727
-	/**
1728
-	 * checks whether an LDAP paged search operation has more pages that can be
1729
-	 * retrieved, typically when offset and limit are provided.
1730
-	 *
1731
-	 * Be very careful to use it: the last cookie value, which is inspected, can
1732
-	 * be reset by other operations. Best, call it immediately after a search(),
1733
-	 * searchUsers() or searchGroups() call. count-methods are probably safe as
1734
-	 * well. Don't rely on it with any fetchList-method.
1735
-	 * @return bool
1736
-	 */
1737
-	public function hasMoreResults() {
1738
-		if(!$this->connection->hasPagedResultSupport) {
1739
-			return false;
1740
-		}
1741
-
1742
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1743
-			// as in RFC 2696, when all results are returned, the cookie will
1744
-			// be empty.
1745
-			return false;
1746
-		}
1747
-
1748
-		return true;
1749
-	}
1750
-
1751
-	/**
1752
-	 * set a cookie for LDAP paged search run
1753
-	 * @param string $base a string with the base DN for the search
1754
-	 * @param string $filter the search filter to identify the correct search
1755
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1756
-	 * @param int $offset the offset for the run search to identify the correct search really good
1757
-	 * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1758
-	 * @return void
1759
-	 */
1760
-	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1761
-		// allow '0' for 389ds
1762
-		if(!empty($cookie) || $cookie === '0') {
1763
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1764
-			$this->cookies[$cacheKey] = $cookie;
1765
-			$this->lastCookie = $cookie;
1766
-		}
1767
-	}
1768
-
1769
-	/**
1770
-	 * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1771
-	 * @return boolean|null true on success, null or false otherwise
1772
-	 */
1773
-	public function getPagedSearchResultState() {
1774
-		$result = $this->pagedSearchedSuccessful;
1775
-		$this->pagedSearchedSuccessful = null;
1776
-		return $result;
1777
-	}
1778
-
1779
-	/**
1780
-	 * Prepares a paged search, if possible
1781
-	 * @param string $filter the LDAP filter for the search
1782
-	 * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1783
-	 * @param string[] $attr optional, when a certain attribute shall be filtered outside
1784
-	 * @param int $limit
1785
-	 * @param int $offset
1786
-	 * @return bool|true
1787
-	 */
1788
-	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1789
-		$pagedSearchOK = false;
1790
-		if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1791
-			$offset = intval($offset); //can be null
1792
-			\OCP\Util::writeLog('user_ldap',
1793
-				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1794
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1795
-				\OCP\Util::DEBUG);
1796
-			//get the cookie from the search for the previous search, required by LDAP
1797
-			foreach($bases as $base) {
1798
-
1799
-				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1800
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1801
-					// no cookie known, although the offset is not 0. Maybe cache run out. We need
1802
-					// to start all over *sigh* (btw, Dear Reader, did you know LDAP paged
1803
-					// searching was designed by MSFT?)
1804
-					// 		Lukas: No, but thanks to reading that source I finally know!
1805
-					// '0' is valid, because 389ds
1806
-					$reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
1807
-					//a bit recursive, $offset of 0 is the exit
1808
-					\OCP\Util::writeLog('user_ldap', 'Looking for cookie L/O '.$limit.'/'.$reOffset, \OCP\Util::INFO);
1809
-					$this->search($filter, array($base), $attr, $limit, $reOffset, true);
1810
-					$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1811
-					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1812
-					//TODO: remember this, probably does not change in the next request...
1813
-					if(empty($cookie) && $cookie !== '0') {
1814
-						// '0' is valid, because 389ds
1815
-						$cookie = null;
1816
-					}
1817
-				}
1818
-				if(!is_null($cookie)) {
1819
-					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1820
-					$this->abandonPagedSearch();
1821
-					$pagedSearchOK = $this->ldap->controlPagedResult(
1822
-						$this->connection->getConnectionResource(), $limit,
1823
-						false, $cookie);
1824
-					if(!$pagedSearchOK) {
1825
-						return false;
1826
-					}
1827
-					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
1828
-				} else {
1829
-					\OCP\Util::writeLog('user_ldap',
1830
-						'No paged search for us, Cpt., Limit '.$limit.' Offset '.$offset,
1831
-						\OCP\Util::INFO);
1832
-				}
1833
-
1834
-			}
1835
-		/* ++ Fixing RHDS searches with pages with zero results ++
1586
+            \OC::$server->getLogger()->info(
1587
+                'Passed string does not resemble a valid GUID. Known UUID ' .
1588
+                '({uuid}) probably does not match UUID configuration.',
1589
+                [ 'app' => 'user_ldap', 'uuid' => $guid ]
1590
+            );
1591
+            return $guid;
1592
+        }
1593
+        for($i=0; $i < 3; $i++) {
1594
+            $pairs = str_split($blocks[$i], 2);
1595
+            $pairs = array_reverse($pairs);
1596
+            $blocks[$i] = implode('', $pairs);
1597
+        }
1598
+        for($i=0; $i < 5; $i++) {
1599
+            $pairs = str_split($blocks[$i], 2);
1600
+            $blocks[$i] = '\\' . implode('\\', $pairs);
1601
+        }
1602
+        return implode('', $blocks);
1603
+    }
1604
+
1605
+    /**
1606
+     * gets a SID of the domain of the given dn
1607
+     * @param string $dn
1608
+     * @return string|bool
1609
+     */
1610
+    public function getSID($dn) {
1611
+        $domainDN = $this->getDomainDNFromDN($dn);
1612
+        $cacheKey = 'getSID-'.$domainDN;
1613
+        $sid = $this->connection->getFromCache($cacheKey);
1614
+        if(!is_null($sid)) {
1615
+            return $sid;
1616
+        }
1617
+
1618
+        $objectSid = $this->readAttribute($domainDN, 'objectsid');
1619
+        if(!is_array($objectSid) || empty($objectSid)) {
1620
+            $this->connection->writeToCache($cacheKey, false);
1621
+            return false;
1622
+        }
1623
+        $domainObjectSid = $this->convertSID2Str($objectSid[0]);
1624
+        $this->connection->writeToCache($cacheKey, $domainObjectSid);
1625
+
1626
+        return $domainObjectSid;
1627
+    }
1628
+
1629
+    /**
1630
+     * converts a binary SID into a string representation
1631
+     * @param string $sid
1632
+     * @return string
1633
+     */
1634
+    public function convertSID2Str($sid) {
1635
+        // The format of a SID binary string is as follows:
1636
+        // 1 byte for the revision level
1637
+        // 1 byte for the number n of variable sub-ids
1638
+        // 6 bytes for identifier authority value
1639
+        // n*4 bytes for n sub-ids
1640
+        //
1641
+        // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1642
+        //  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1643
+        $revision = ord($sid[0]);
1644
+        $numberSubID = ord($sid[1]);
1645
+
1646
+        $subIdStart = 8; // 1 + 1 + 6
1647
+        $subIdLength = 4;
1648
+        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1649
+            // Incorrect number of bytes present.
1650
+            return '';
1651
+        }
1652
+
1653
+        // 6 bytes = 48 bits can be represented using floats without loss of
1654
+        // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1655
+        $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1656
+
1657
+        $subIDs = array();
1658
+        for ($i = 0; $i < $numberSubID; $i++) {
1659
+            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1660
+            $subIDs[] = sprintf('%u', $subID[1]);
1661
+        }
1662
+
1663
+        // Result for example above: S-1-5-21-249921958-728525901-1594176202
1664
+        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1665
+    }
1666
+
1667
+    /**
1668
+     * checks if the given DN is part of the given base DN(s)
1669
+     * @param string $dn the DN
1670
+     * @param string[] $bases array containing the allowed base DN or DNs
1671
+     * @return bool
1672
+     */
1673
+    public function isDNPartOfBase($dn, $bases) {
1674
+        $belongsToBase = false;
1675
+        $bases = $this->helper->sanitizeDN($bases);
1676
+
1677
+        foreach($bases as $base) {
1678
+            $belongsToBase = true;
1679
+            if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1680
+                $belongsToBase = false;
1681
+            }
1682
+            if($belongsToBase) {
1683
+                break;
1684
+            }
1685
+        }
1686
+        return $belongsToBase;
1687
+    }
1688
+
1689
+    /**
1690
+     * resets a running Paged Search operation
1691
+     */
1692
+    private function abandonPagedSearch() {
1693
+        if($this->connection->hasPagedResultSupport) {
1694
+            $cr = $this->connection->getConnectionResource();
1695
+            $this->ldap->controlPagedResult($cr, 0, false, $this->lastCookie);
1696
+            $this->getPagedSearchResultState();
1697
+            $this->lastCookie = '';
1698
+            $this->cookies = array();
1699
+        }
1700
+    }
1701
+
1702
+    /**
1703
+     * get a cookie for the next LDAP paged search
1704
+     * @param string $base a string with the base DN for the search
1705
+     * @param string $filter the search filter to identify the correct search
1706
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1707
+     * @param int $offset the offset for the new search to identify the correct search really good
1708
+     * @return string containing the key or empty if none is cached
1709
+     */
1710
+    private function getPagedResultCookie($base, $filter, $limit, $offset) {
1711
+        if($offset === 0) {
1712
+            return '';
1713
+        }
1714
+        $offset -= $limit;
1715
+        //we work with cache here
1716
+        $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1717
+        $cookie = '';
1718
+        if(isset($this->cookies[$cacheKey])) {
1719
+            $cookie = $this->cookies[$cacheKey];
1720
+            if(is_null($cookie)) {
1721
+                $cookie = '';
1722
+            }
1723
+        }
1724
+        return $cookie;
1725
+    }
1726
+
1727
+    /**
1728
+     * checks whether an LDAP paged search operation has more pages that can be
1729
+     * retrieved, typically when offset and limit are provided.
1730
+     *
1731
+     * Be very careful to use it: the last cookie value, which is inspected, can
1732
+     * be reset by other operations. Best, call it immediately after a search(),
1733
+     * searchUsers() or searchGroups() call. count-methods are probably safe as
1734
+     * well. Don't rely on it with any fetchList-method.
1735
+     * @return bool
1736
+     */
1737
+    public function hasMoreResults() {
1738
+        if(!$this->connection->hasPagedResultSupport) {
1739
+            return false;
1740
+        }
1741
+
1742
+        if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1743
+            // as in RFC 2696, when all results are returned, the cookie will
1744
+            // be empty.
1745
+            return false;
1746
+        }
1747
+
1748
+        return true;
1749
+    }
1750
+
1751
+    /**
1752
+     * set a cookie for LDAP paged search run
1753
+     * @param string $base a string with the base DN for the search
1754
+     * @param string $filter the search filter to identify the correct search
1755
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1756
+     * @param int $offset the offset for the run search to identify the correct search really good
1757
+     * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1758
+     * @return void
1759
+     */
1760
+    private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1761
+        // allow '0' for 389ds
1762
+        if(!empty($cookie) || $cookie === '0') {
1763
+            $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1764
+            $this->cookies[$cacheKey] = $cookie;
1765
+            $this->lastCookie = $cookie;
1766
+        }
1767
+    }
1768
+
1769
+    /**
1770
+     * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1771
+     * @return boolean|null true on success, null or false otherwise
1772
+     */
1773
+    public function getPagedSearchResultState() {
1774
+        $result = $this->pagedSearchedSuccessful;
1775
+        $this->pagedSearchedSuccessful = null;
1776
+        return $result;
1777
+    }
1778
+
1779
+    /**
1780
+     * Prepares a paged search, if possible
1781
+     * @param string $filter the LDAP filter for the search
1782
+     * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1783
+     * @param string[] $attr optional, when a certain attribute shall be filtered outside
1784
+     * @param int $limit
1785
+     * @param int $offset
1786
+     * @return bool|true
1787
+     */
1788
+    private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1789
+        $pagedSearchOK = false;
1790
+        if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1791
+            $offset = intval($offset); //can be null
1792
+            \OCP\Util::writeLog('user_ldap',
1793
+                'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1794
+                .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1795
+                \OCP\Util::DEBUG);
1796
+            //get the cookie from the search for the previous search, required by LDAP
1797
+            foreach($bases as $base) {
1798
+
1799
+                $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1800
+                if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1801
+                    // no cookie known, although the offset is not 0. Maybe cache run out. We need
1802
+                    // to start all over *sigh* (btw, Dear Reader, did you know LDAP paged
1803
+                    // searching was designed by MSFT?)
1804
+                    // 		Lukas: No, but thanks to reading that source I finally know!
1805
+                    // '0' is valid, because 389ds
1806
+                    $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
1807
+                    //a bit recursive, $offset of 0 is the exit
1808
+                    \OCP\Util::writeLog('user_ldap', 'Looking for cookie L/O '.$limit.'/'.$reOffset, \OCP\Util::INFO);
1809
+                    $this->search($filter, array($base), $attr, $limit, $reOffset, true);
1810
+                    $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1811
+                    //still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1812
+                    //TODO: remember this, probably does not change in the next request...
1813
+                    if(empty($cookie) && $cookie !== '0') {
1814
+                        // '0' is valid, because 389ds
1815
+                        $cookie = null;
1816
+                    }
1817
+                }
1818
+                if(!is_null($cookie)) {
1819
+                    //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1820
+                    $this->abandonPagedSearch();
1821
+                    $pagedSearchOK = $this->ldap->controlPagedResult(
1822
+                        $this->connection->getConnectionResource(), $limit,
1823
+                        false, $cookie);
1824
+                    if(!$pagedSearchOK) {
1825
+                        return false;
1826
+                    }
1827
+                    \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
1828
+                } else {
1829
+                    \OCP\Util::writeLog('user_ldap',
1830
+                        'No paged search for us, Cpt., Limit '.$limit.' Offset '.$offset,
1831
+                        \OCP\Util::INFO);
1832
+                }
1833
+
1834
+            }
1835
+        /* ++ Fixing RHDS searches with pages with zero results ++
1836 1836
 		 * We coudn't get paged searches working with our RHDS for login ($limit = 0),
1837 1837
 		 * due to pages with zero results.
1838 1838
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
1839 1839
 		 * if we don't have a previous paged search.
1840 1840
 		 */
1841
-		} else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1842
-			// a search without limit was requested. However, if we do use
1843
-			// Paged Search once, we always must do it. This requires us to
1844
-			// initialize it with the configured page size.
1845
-			$this->abandonPagedSearch();
1846
-			// in case someone set it to 0 … use 500, otherwise no results will
1847
-			// be returned.
1848
-			$pageSize = intval($this->connection->ldapPagingSize) > 0 ? intval($this->connection->ldapPagingSize) : 500;
1849
-			$pagedSearchOK = $this->ldap->controlPagedResult(
1850
-				$this->connection->getConnectionResource(), $pageSize, false, ''
1851
-			);
1852
-		}
1853
-
1854
-		return $pagedSearchOK;
1855
-	}
1841
+        } else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1842
+            // a search without limit was requested. However, if we do use
1843
+            // Paged Search once, we always must do it. This requires us to
1844
+            // initialize it with the configured page size.
1845
+            $this->abandonPagedSearch();
1846
+            // in case someone set it to 0 … use 500, otherwise no results will
1847
+            // be returned.
1848
+            $pageSize = intval($this->connection->ldapPagingSize) > 0 ? intval($this->connection->ldapPagingSize) : 500;
1849
+            $pagedSearchOK = $this->ldap->controlPagedResult(
1850
+                $this->connection->getConnectionResource(), $pageSize, false, ''
1851
+            );
1852
+        }
1853
+
1854
+        return $pagedSearchOK;
1855
+    }
1856 1856
 
1857 1857
 }
Please login to merge, or discard this patch.
Spacing   +163 added lines, -163 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 	 * @return AbstractMapping
111 111
 	 */
112 112
 	public function getUserMapper() {
113
-		if(is_null($this->userMapper)) {
113
+		if (is_null($this->userMapper)) {
114 114
 			throw new \Exception('UserMapper was not assigned to this Access instance.');
115 115
 		}
116 116
 		return $this->userMapper;
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 	 * @return AbstractMapping
131 131
 	 */
132 132
 	public function getGroupMapper() {
133
-		if(is_null($this->groupMapper)) {
133
+		if (is_null($this->groupMapper)) {
134 134
 			throw new \Exception('GroupMapper was not assigned to this Access instance.');
135 135
 		}
136 136
 		return $this->groupMapper;
@@ -161,14 +161,14 @@  discard block
 block discarded – undo
161 161
 	 *          array if $attr is empty, false otherwise
162 162
 	 */
163 163
 	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
164
-		if(!$this->checkConnection()) {
164
+		if (!$this->checkConnection()) {
165 165
 			\OCP\Util::writeLog('user_ldap',
166 166
 				'No LDAP Connector assigned, access impossible for readAttribute.',
167 167
 				\OCP\Util::WARN);
168 168
 			return false;
169 169
 		}
170 170
 		$cr = $this->connection->getConnectionResource();
171
-		if(!$this->ldap->isResource($cr)) {
171
+		if (!$this->ldap->isResource($cr)) {
172 172
 			//LDAP not available
173 173
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
174 174
 			return false;
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 		$isRangeRequest = false;
192 192
 		do {
193 193
 			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
194
-			if(is_bool($result)) {
194
+			if (is_bool($result)) {
195 195
 				// when an exists request was run and it was successful, an empty
196 196
 				// array must be returned
197 197
 				return $result ? [] : false;
@@ -208,22 +208,22 @@  discard block
 block discarded – undo
208 208
 			$result = $this->extractRangeData($result, $attr);
209 209
 			if (!empty($result)) {
210 210
 				$normalizedResult = $this->extractAttributeValuesFromResult(
211
-					[ $attr => $result['values'] ],
211
+					[$attr => $result['values']],
212 212
 					$attr
213 213
 				);
214 214
 				$values = array_merge($values, $normalizedResult);
215 215
 
216
-				if($result['rangeHigh'] === '*') {
216
+				if ($result['rangeHigh'] === '*') {
217 217
 					// when server replies with * as high range value, there are
218 218
 					// no more results left
219 219
 					return $values;
220 220
 				} else {
221
-					$low  = $result['rangeHigh'] + 1;
222
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
221
+					$low = $result['rangeHigh'] + 1;
222
+					$attrToRead = $result['attributeName'].';range='.$low.'-*';
223 223
 					$isRangeRequest = true;
224 224
 				}
225 225
 			}
226
-		} while($isRangeRequest);
226
+		} while ($isRangeRequest);
227 227
 
228 228
 		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
229 229
 		return false;
@@ -248,13 +248,13 @@  discard block
 block discarded – undo
248 248
 		if (!$this->ldap->isResource($rr)) {
249 249
 			if ($attribute !== '') {
250 250
 				//do not throw this message on userExists check, irritates
251
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
251
+				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN '.$dn, \OCP\Util::DEBUG);
252 252
 			}
253 253
 			//in case an error occurs , e.g. object does not exist
254 254
 			return false;
255 255
 		}
256 256
 		if ($attribute === '' && ($filter === 'objectclass=*' || $this->ldap->countEntries($cr, $rr) === 1)) {
257
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
257
+			\OCP\Util::writeLog('user_ldap', 'readAttribute: '.$dn.' found', \OCP\Util::DEBUG);
258 258
 			return true;
259 259
 		}
260 260
 		$er = $this->ldap->firstEntry($cr, $rr);
@@ -279,12 +279,12 @@  discard block
 block discarded – undo
279 279
 	 */
280 280
 	public function extractAttributeValuesFromResult($result, $attribute) {
281 281
 		$values = [];
282
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
282
+		if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
283 283
 			$lowercaseAttribute = strtolower($attribute);
284
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
285
-				if($this->resemblesDN($attribute)) {
284
+			for ($i = 0; $i < $result[$attribute]['count']; $i++) {
285
+				if ($this->resemblesDN($attribute)) {
286 286
 					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
287
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
287
+				} elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
288 288
 					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
289 289
 				} else {
290 290
 					$values[] = $result[$attribute][$i];
@@ -306,10 +306,10 @@  discard block
 block discarded – undo
306 306
 	 */
307 307
 	public function extractRangeData($result, $attribute) {
308 308
 		$keys = array_keys($result);
309
-		foreach($keys as $key) {
310
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
309
+		foreach ($keys as $key) {
310
+			if ($key !== $attribute && strpos($key, $attribute) === 0) {
311 311
 				$queryData = explode(';', $key);
312
-				if(strpos($queryData[1], 'range=') === 0) {
312
+				if (strpos($queryData[1], 'range=') === 0) {
313 313
 					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
314 314
 					$data = [
315 315
 						'values' => $result[$key],
@@ -334,11 +334,11 @@  discard block
 block discarded – undo
334 334
 	 * @throws \Exception
335 335
 	 */
336 336
 	public function setPassword($userDN, $password) {
337
-		if(intval($this->connection->turnOnPasswordChange) !== 1) {
337
+		if (intval($this->connection->turnOnPasswordChange) !== 1) {
338 338
 			throw new \Exception('LDAP password changes are disabled.');
339 339
 		}
340 340
 		$cr = $this->connection->getConnectionResource();
341
-		if(!$this->ldap->isResource($cr)) {
341
+		if (!$this->ldap->isResource($cr)) {
342 342
 			//LDAP not available
343 343
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
344 344
 			return false;
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
 		
347 347
 		try {
348 348
 			return $this->ldap->modReplace($cr, $userDN, $password);
349
-		} catch(ConstraintViolationException $e) {
349
+		} catch (ConstraintViolationException $e) {
350 350
 			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
351 351
 		}
352 352
 	}
@@ -388,17 +388,17 @@  discard block
 block discarded – undo
388 388
 	 */
389 389
 	public function getDomainDNFromDN($dn) {
390 390
 		$allParts = $this->ldap->explodeDN($dn, 0);
391
-		if($allParts === false) {
391
+		if ($allParts === false) {
392 392
 			//not a valid DN
393 393
 			return '';
394 394
 		}
395 395
 		$domainParts = array();
396 396
 		$dcFound = false;
397
-		foreach($allParts as $part) {
398
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
397
+		foreach ($allParts as $part) {
398
+			if (!$dcFound && strpos($part, 'dc=') === 0) {
399 399
 				$dcFound = true;
400 400
 			}
401
-			if($dcFound) {
401
+			if ($dcFound) {
402 402
 				$domainParts[] = $part;
403 403
 			}
404 404
 		}
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
 
426 426
 		//Check whether the DN belongs to the Base, to avoid issues on multi-
427 427
 		//server setups
428
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
428
+		if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
429 429
 			return $fdn;
430 430
 		}
431 431
 
@@ -442,7 +442,7 @@  discard block
 block discarded – undo
442 442
 		//To avoid bypassing the base DN settings under certain circumstances
443 443
 		//with the group support, check whether the provided DN matches one of
444 444
 		//the given Bases
445
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
445
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
446 446
 			return false;
447 447
 		}
448 448
 
@@ -459,11 +459,11 @@  discard block
 block discarded – undo
459 459
 	 */
460 460
 	public function groupsMatchFilter($groupDNs) {
461 461
 		$validGroupDNs = [];
462
-		foreach($groupDNs as $dn) {
462
+		foreach ($groupDNs as $dn) {
463 463
 			$cacheKey = 'groupsMatchFilter-'.$dn;
464 464
 			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
465
-			if(!is_null($groupMatchFilter)) {
466
-				if($groupMatchFilter) {
465
+			if (!is_null($groupMatchFilter)) {
466
+				if ($groupMatchFilter) {
467 467
 					$validGroupDNs[] = $dn;
468 468
 				}
469 469
 				continue;
@@ -471,13 +471,13 @@  discard block
 block discarded – undo
471 471
 
472 472
 			// Check the base DN first. If this is not met already, we don't
473 473
 			// need to ask the server at all.
474
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
474
+			if (!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
475 475
 				$this->connection->writeToCache($cacheKey, false);
476 476
 				continue;
477 477
 			}
478 478
 
479 479
 			$result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
480
-			if(is_array($result)) {
480
+			if (is_array($result)) {
481 481
 				$this->connection->writeToCache($cacheKey, true);
482 482
 				$validGroupDNs[] = $dn;
483 483
 			} else {
@@ -498,7 +498,7 @@  discard block
 block discarded – undo
498 498
 		//To avoid bypassing the base DN settings under certain circumstances
499 499
 		//with the group support, check whether the provided DN matches one of
500 500
 		//the given Bases
501
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
501
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
502 502
 			return false;
503 503
 		}
504 504
 
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
 	 * @return string|false with with the name to use in ownCloud
514 514
 	 */
515 515
 	public function dn2ocname($fdn, $ldapName = null, $isUser = true) {
516
-		if($isUser) {
516
+		if ($isUser) {
517 517
 			$mapper = $this->getUserMapper();
518 518
 			$nameAttribute = $this->connection->ldapUserDisplayName;
519 519
 		} else {
@@ -523,15 +523,15 @@  discard block
 block discarded – undo
523 523
 
524 524
 		//let's try to retrieve the ownCloud name from the mappings table
525 525
 		$ocName = $mapper->getNameByDN($fdn);
526
-		if(is_string($ocName)) {
526
+		if (is_string($ocName)) {
527 527
 			return $ocName;
528 528
 		}
529 529
 
530 530
 		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
531 531
 		$uuid = $this->getUUID($fdn, $isUser);
532
-		if(is_string($uuid)) {
532
+		if (is_string($uuid)) {
533 533
 			$ocName = $mapper->getNameByUUID($uuid);
534
-			if(is_string($ocName)) {
534
+			if (is_string($ocName)) {
535 535
 				$mapper->setDNbyUUID($fdn, $uuid);
536 536
 				return $ocName;
537 537
 			}
@@ -541,16 +541,16 @@  discard block
 block discarded – undo
541 541
 			return false;
542 542
 		}
543 543
 
544
-		if(is_null($ldapName)) {
544
+		if (is_null($ldapName)) {
545 545
 			$ldapName = $this->readAttribute($fdn, $nameAttribute);
546
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
546
+			if (!isset($ldapName[0]) && empty($ldapName[0])) {
547 547
 				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
548 548
 				return false;
549 549
 			}
550 550
 			$ldapName = $ldapName[0];
551 551
 		}
552 552
 
553
-		if($isUser) {
553
+		if ($isUser) {
554 554
 			$usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
555 555
 			if ($usernameAttribute !== '') {
556 556
 				$username = $this->readAttribute($fdn, $usernameAttribute);
@@ -569,9 +569,9 @@  discard block
 block discarded – undo
569 569
 		// outside of core user management will still cache the user as non-existing.
570 570
 		$originalTTL = $this->connection->ldapCacheTTL;
571 571
 		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
572
-		if(($isUser && !\OCP\User::userExists($intName))
572
+		if (($isUser && !\OCP\User::userExists($intName))
573 573
 			|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
574
-			if($mapper->map($fdn, $intName, $uuid)) {
574
+			if ($mapper->map($fdn, $intName, $uuid)) {
575 575
 				$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
576 576
 				return $intName;
577 577
 			}
@@ -579,7 +579,7 @@  discard block
 block discarded – undo
579 579
 		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
580 580
 
581 581
 		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
582
-		if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
582
+		if (is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
583 583
 			return $altName;
584 584
 		}
585 585
 
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
 	 * @return array
617 617
 	 */
618 618
 	private function ldap2ownCloudNames($ldapObjects, $isUsers) {
619
-		if($isUsers) {
619
+		if ($isUsers) {
620 620
 			$nameAttribute = $this->connection->ldapUserDisplayName;
621 621
 			$sndAttribute  = $this->connection->ldapUserDisplayName2;
622 622
 		} else {
@@ -624,9 +624,9 @@  discard block
 block discarded – undo
624 624
 		}
625 625
 		$ownCloudNames = array();
626 626
 
627
-		foreach($ldapObjects as $ldapObject) {
627
+		foreach ($ldapObjects as $ldapObject) {
628 628
 			$nameByLDAP = null;
629
-			if(    isset($ldapObject[$nameAttribute])
629
+			if (isset($ldapObject[$nameAttribute])
630 630
 				&& is_array($ldapObject[$nameAttribute])
631 631
 				&& isset($ldapObject[$nameAttribute][0])
632 632
 			) {
@@ -635,12 +635,12 @@  discard block
 block discarded – undo
635 635
 			}
636 636
 
637 637
 			$ocName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
638
-			if($ocName) {
638
+			if ($ocName) {
639 639
 				$ownCloudNames[] = $ocName;
640
-				if($isUsers) {
640
+				if ($isUsers) {
641 641
 					//cache the user names so it does not need to be retrieved
642 642
 					//again later (e.g. sharing dialogue).
643
-					if(is_null($nameByLDAP)) {
643
+					if (is_null($nameByLDAP)) {
644 644
 						continue;
645 645
 					}
646 646
 					$sndName = isset($ldapObject[$sndAttribute][0])
@@ -678,7 +678,7 @@  discard block
 block discarded – undo
678 678
 	 */
679 679
 	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
680 680
 		$user = $this->userManager->get($ocName);
681
-		if($user === null) {
681
+		if ($user === null) {
682 682
 			return;
683 683
 		}
684 684
 		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
@@ -698,9 +698,9 @@  discard block
 block discarded – undo
698 698
 		$attempts = 0;
699 699
 		//while loop is just a precaution. If a name is not generated within
700 700
 		//20 attempts, something else is very wrong. Avoids infinite loop.
701
-		while($attempts < 20){
702
-			$altName = $name . '_' . rand(1000,9999);
703
-			if(!\OCP\User::userExists($altName)) {
701
+		while ($attempts < 20) {
702
+			$altName = $name.'_'.rand(1000, 9999);
703
+			if (!\OCP\User::userExists($altName)) {
704 704
 				return $altName;
705 705
 			}
706 706
 			$attempts++;
@@ -722,25 +722,25 @@  discard block
 block discarded – undo
722 722
 	 */
723 723
 	private function _createAltInternalOwnCloudNameForGroups($name) {
724 724
 		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
725
-		if(!($usedNames) || count($usedNames) === 0) {
725
+		if (!($usedNames) || count($usedNames) === 0) {
726 726
 			$lastNo = 1; //will become name_2
727 727
 		} else {
728 728
 			natsort($usedNames);
729 729
 			$lastName = array_pop($usedNames);
730 730
 			$lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
731 731
 		}
732
-		$altName = $name.'_'.strval($lastNo+1);
732
+		$altName = $name.'_'.strval($lastNo + 1);
733 733
 		unset($usedNames);
734 734
 
735 735
 		$attempts = 1;
736
-		while($attempts < 21){
736
+		while ($attempts < 21) {
737 737
 			// Check to be really sure it is unique
738 738
 			// while loop is just a precaution. If a name is not generated within
739 739
 			// 20 attempts, something else is very wrong. Avoids infinite loop.
740
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
740
+			if (!\OC::$server->getGroupManager()->groupExists($altName)) {
741 741
 				return $altName;
742 742
 			}
743
-			$altName = $name . '_' . ($lastNo + $attempts);
743
+			$altName = $name.'_'.($lastNo + $attempts);
744 744
 			$attempts++;
745 745
 		}
746 746
 		return false;
@@ -755,7 +755,7 @@  discard block
 block discarded – undo
755 755
 	private function createAltInternalOwnCloudName($name, $isUser) {
756 756
 		$originalTTL = $this->connection->ldapCacheTTL;
757 757
 		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
758
-		if($isUser) {
758
+		if ($isUser) {
759 759
 			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
760 760
 		} else {
761 761
 			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
@@ -813,20 +813,20 @@  discard block
 block discarded – undo
813 813
 	 * and their values
814 814
 	 * @param array $ldapRecords
815 815
 	 */
816
-	public function batchApplyUserAttributes(array $ldapRecords){
816
+	public function batchApplyUserAttributes(array $ldapRecords) {
817 817
 		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
818
-		foreach($ldapRecords as $userRecord) {
819
-			if(!isset($userRecord[$displayNameAttribute])) {
818
+		foreach ($ldapRecords as $userRecord) {
819
+			if (!isset($userRecord[$displayNameAttribute])) {
820 820
 				// displayName is obligatory
821 821
 				continue;
822 822
 			}
823
-			$ocName  = $this->dn2ocname($userRecord['dn'][0]);
824
-			if($ocName === false) {
823
+			$ocName = $this->dn2ocname($userRecord['dn'][0]);
824
+			if ($ocName === false) {
825 825
 				continue;
826 826
 			}
827 827
 			$this->cacheUserExists($ocName);
828 828
 			$user = $this->userManager->get($ocName);
829
-			if($user instanceof OfflineUser) {
829
+			if ($user instanceof OfflineUser) {
830 830
 				$user->unmark();
831 831
 				$user = $this->userManager->get($ocName);
832 832
 			}
@@ -858,8 +858,8 @@  discard block
 block discarded – undo
858 858
 	 * @return array
859 859
 	 */
860 860
 	private function fetchList($list, $manyAttributes) {
861
-		if(is_array($list)) {
862
-			if($manyAttributes) {
861
+		if (is_array($list)) {
862
+			if ($manyAttributes) {
863 863
 				return $list;
864 864
 			} else {
865 865
 				$list = array_reduce($list, function($carry, $item) {
@@ -945,13 +945,13 @@  discard block
 block discarded – undo
945 945
 	 * second | false if not successful
946 946
 	 */
947 947
 	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
948
-		if(!is_null($attr) && !is_array($attr)) {
948
+		if (!is_null($attr) && !is_array($attr)) {
949 949
 			$attr = array(mb_strtolower($attr, 'UTF-8'));
950 950
 		}
951 951
 
952 952
 		// See if we have a resource, in case not cancel with message
953 953
 		$cr = $this->connection->getConnectionResource();
954
-		if(!$this->ldap->isResource($cr)) {
954
+		if (!$this->ldap->isResource($cr)) {
955 955
 			// Seems like we didn't find any resource.
956 956
 			// Return an empty array just like before.
957 957
 			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
@@ -964,7 +964,7 @@  discard block
 block discarded – undo
964 964
 		$linkResources = array_pad(array(), count($base), $cr);
965 965
 		$sr = $this->ldap->search($linkResources, $base, $filter, $attr);
966 966
 		$error = $this->ldap->errno($cr);
967
-		if(!is_array($sr) || $error !== 0) {
967
+		if (!is_array($sr) || $error !== 0) {
968 968
 			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
969 969
 			return false;
970 970
 		}
@@ -987,26 +987,26 @@  discard block
 block discarded – undo
987 987
 	 */
988 988
 	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
989 989
 		$cookie = null;
990
-		if($pagedSearchOK) {
990
+		if ($pagedSearchOK) {
991 991
 			$cr = $this->connection->getConnectionResource();
992
-			foreach($sr as $key => $res) {
993
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
992
+			foreach ($sr as $key => $res) {
993
+				if ($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
994 994
 					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
995 995
 				}
996 996
 			}
997 997
 
998 998
 			//browsing through prior pages to get the cookie for the new one
999
-			if($skipHandling) {
999
+			if ($skipHandling) {
1000 1000
 				return false;
1001 1001
 			}
1002 1002
 			// if count is bigger, then the server does not support
1003 1003
 			// paged search. Instead, he did a normal search. We set a
1004 1004
 			// flag here, so the callee knows how to deal with it.
1005
-			if($iFoundItems <= $limit) {
1005
+			if ($iFoundItems <= $limit) {
1006 1006
 				$this->pagedSearchedSuccessful = true;
1007 1007
 			}
1008 1008
 		} else {
1009
-			if(!is_null($limit)) {
1009
+			if (!is_null($limit)) {
1010 1010
 				\OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO);
1011 1011
 			}
1012 1012
 		}
@@ -1035,7 +1035,7 @@  discard block
 block discarded – undo
1035 1035
 		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1036 1036
 
1037 1037
 		$limitPerPage = intval($this->connection->ldapPagingSize);
1038
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1038
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1039 1039
 			$limitPerPage = $limit;
1040 1040
 		}
1041 1041
 
@@ -1046,7 +1046,7 @@  discard block
 block discarded – undo
1046 1046
 		do {
1047 1047
 			$search = $this->executeSearch($filter, $base, $attr,
1048 1048
 										   $limitPerPage, $offset);
1049
-			if($search === false) {
1049
+			if ($search === false) {
1050 1050
 				return $counter > 0 ? $counter : false;
1051 1051
 			}
1052 1052
 			list($sr, $pagedSearchOK) = $search;
@@ -1065,7 +1065,7 @@  discard block
 block discarded – undo
1065 1065
 			 * Continue now depends on $hasMorePages value
1066 1066
 			 */
1067 1067
 			$continue = $pagedSearchOK && $hasMorePages;
1068
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1068
+		} while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1069 1069
 
1070 1070
 		return $counter;
1071 1071
 	}
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
 		$cr = $this->connection->getConnectionResource();
1079 1079
 		$counter = 0;
1080 1080
 
1081
-		foreach($searchResults as $res) {
1081
+		foreach ($searchResults as $res) {
1082 1082
 			$count = intval($this->ldap->countEntries($cr, $res));
1083 1083
 			$counter += $count;
1084 1084
 		}
@@ -1097,7 +1097,7 @@  discard block
 block discarded – undo
1097 1097
 	 * @return array with the search result
1098 1098
 	 */
1099 1099
 	private function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1100
-		if($limit <= 0) {
1100
+		if ($limit <= 0) {
1101 1101
 			//otherwise search will fail
1102 1102
 			$limit = null;
1103 1103
 		}
@@ -1112,13 +1112,13 @@  discard block
 block discarded – undo
1112 1112
 		$savedoffset = $offset;
1113 1113
 		do {
1114 1114
 			$search = $this->executeSearch($filter, $base, $attr, $limit, $offset);
1115
-			if($search === false) {
1115
+			if ($search === false) {
1116 1116
 				return array();
1117 1117
 			}
1118 1118
 			list($sr, $pagedSearchOK) = $search;
1119 1119
 			$cr = $this->connection->getConnectionResource();
1120 1120
 
1121
-			if($skipHandling) {
1121
+			if ($skipHandling) {
1122 1122
 				//i.e. result do not need to be fetched, we just need the cookie
1123 1123
 				//thus pass 1 or any other value as $iFoundItems because it is not
1124 1124
 				//used
@@ -1128,8 +1128,8 @@  discard block
 block discarded – undo
1128 1128
 				return array();
1129 1129
 			}
1130 1130
 
1131
-			foreach($sr as $res) {
1132
-				$findings = array_merge($findings, $this->ldap->getEntries($cr	, $res ));
1131
+			foreach ($sr as $res) {
1132
+				$findings = array_merge($findings, $this->ldap->getEntries($cr, $res));
1133 1133
 			}
1134 1134
 
1135 1135
 			$continue = $this->processPagedSearchStatus($sr, $filter, $base, $findings['count'],
@@ -1142,25 +1142,25 @@  discard block
 block discarded – undo
1142 1142
 
1143 1143
 		// if we're here, probably no connection resource is returned.
1144 1144
 		// to make ownCloud behave nicely, we simply give back an empty array.
1145
-		if(is_null($findings)) {
1145
+		if (is_null($findings)) {
1146 1146
 			return array();
1147 1147
 		}
1148 1148
 
1149
-		if(!is_null($attr)) {
1149
+		if (!is_null($attr)) {
1150 1150
 			$selection = array();
1151 1151
 			$i = 0;
1152
-			foreach($findings as $item) {
1153
-				if(!is_array($item)) {
1152
+			foreach ($findings as $item) {
1153
+				if (!is_array($item)) {
1154 1154
 					continue;
1155 1155
 				}
1156 1156
 				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1157
-				foreach($attr as $key) {
1157
+				foreach ($attr as $key) {
1158 1158
 					$key = mb_strtolower($key, 'UTF-8');
1159
-					if(isset($item[$key])) {
1160
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1159
+					if (isset($item[$key])) {
1160
+						if (is_array($item[$key]) && isset($item[$key]['count'])) {
1161 1161
 							unset($item[$key]['count']);
1162 1162
 						}
1163
-						if($key !== 'dn') {
1163
+						if ($key !== 'dn') {
1164 1164
 							$selection[$i][$key] = $this->resemblesDN($key) ?
1165 1165
 								$this->helper->sanitizeDN($item[$key])
1166 1166
 								: $item[$key];
@@ -1177,7 +1177,7 @@  discard block
 block discarded – undo
1177 1177
 		//we slice the findings, when
1178 1178
 		//a) paged search unsuccessful, though attempted
1179 1179
 		//b) no paged search, but limit set
1180
-		if((!$this->getPagedSearchResultState()
1180
+		if ((!$this->getPagedSearchResultState()
1181 1181
 			&& $pagedSearchOK)
1182 1182
 			|| (
1183 1183
 				!$pagedSearchOK
@@ -1194,7 +1194,7 @@  discard block
 block discarded – undo
1194 1194
 	 * @return bool|mixed|string
1195 1195
 	 */
1196 1196
 	public function sanitizeUsername($name) {
1197
-		if($this->connection->ldapIgnoreNamingRules) {
1197
+		if ($this->connection->ldapIgnoreNamingRules) {
1198 1198
 			return $name;
1199 1199
 		}
1200 1200
 
@@ -1219,13 +1219,13 @@  discard block
 block discarded – undo
1219 1219
 	*/
1220 1220
 	public function escapeFilterPart($input, $allowAsterisk = false) {
1221 1221
 		$asterisk = '';
1222
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1222
+		if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1223 1223
 			$asterisk = '*';
1224 1224
 			$input = mb_substr($input, 1, null, 'UTF-8');
1225 1225
 		}
1226 1226
 		$search  = array('*', '\\', '(', ')');
1227 1227
 		$replace = array('\\*', '\\\\', '\\(', '\\)');
1228
-		return $asterisk . str_replace($search, $replace, $input);
1228
+		return $asterisk.str_replace($search, $replace, $input);
1229 1229
 	}
1230 1230
 
1231 1231
 	/**
@@ -1255,13 +1255,13 @@  discard block
 block discarded – undo
1255 1255
 	 */
1256 1256
 	private function combineFilter($filters, $operator) {
1257 1257
 		$combinedFilter = '('.$operator;
1258
-		foreach($filters as $filter) {
1258
+		foreach ($filters as $filter) {
1259 1259
 			if ($filter !== '' && $filter[0] !== '(') {
1260 1260
 				$filter = '('.$filter.')';
1261 1261
 			}
1262
-			$combinedFilter.=$filter;
1262
+			$combinedFilter .= $filter;
1263 1263
 		}
1264
-		$combinedFilter.=')';
1264
+		$combinedFilter .= ')';
1265 1265
 		return $combinedFilter;
1266 1266
 	}
1267 1267
 
@@ -1297,17 +1297,17 @@  discard block
 block discarded – undo
1297 1297
 	 * @throws \Exception
1298 1298
 	 */
1299 1299
 	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1300
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1300
+		if (!is_array($searchAttributes) || count($searchAttributes) < 2) {
1301 1301
 			throw new \Exception('searchAttributes must be an array with at least two string');
1302 1302
 		}
1303 1303
 		$searchWords = explode(' ', trim($search));
1304 1304
 		$wordFilters = array();
1305
-		foreach($searchWords as $word) {
1305
+		foreach ($searchWords as $word) {
1306 1306
 			$word = $this->prepareSearchTerm($word);
1307 1307
 			//every word needs to appear at least once
1308 1308
 			$wordMatchOneAttrFilters = array();
1309
-			foreach($searchAttributes as $attr) {
1310
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1309
+			foreach ($searchAttributes as $attr) {
1310
+				$wordMatchOneAttrFilters[] = $attr.'='.$word;
1311 1311
 			}
1312 1312
 			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1313 1313
 		}
@@ -1325,10 +1325,10 @@  discard block
 block discarded – undo
1325 1325
 	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1326 1326
 		$filter = array();
1327 1327
 		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1328
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1328
+		if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1329 1329
 			try {
1330 1330
 				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1331
-			} catch(\Exception $e) {
1331
+			} catch (\Exception $e) {
1332 1332
 				\OCP\Util::writeLog(
1333 1333
 					'user_ldap',
1334 1334
 					'Creating advanced filter for search failed, falling back to simple method.',
@@ -1338,17 +1338,17 @@  discard block
 block discarded – undo
1338 1338
 		}
1339 1339
 
1340 1340
 		$search = $this->prepareSearchTerm($search);
1341
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1341
+		if (!is_array($searchAttributes) || count($searchAttributes) === 0) {
1342 1342
 			if ($fallbackAttribute === '') {
1343 1343
 				return '';
1344 1344
 			}
1345
-			$filter[] = $fallbackAttribute . '=' . $search;
1345
+			$filter[] = $fallbackAttribute.'='.$search;
1346 1346
 		} else {
1347
-			foreach($searchAttributes as $attribute) {
1348
-				$filter[] = $attribute . '=' . $search;
1347
+			foreach ($searchAttributes as $attribute) {
1348
+				$filter[] = $attribute.'='.$search;
1349 1349
 			}
1350 1350
 		}
1351
-		if(count($filter) === 1) {
1351
+		if (count($filter) === 1) {
1352 1352
 			return '('.$filter[0].')';
1353 1353
 		}
1354 1354
 		return $this->combineFilterWithOr($filter);
@@ -1369,7 +1369,7 @@  discard block
 block discarded – undo
1369 1369
 		if ($term === '') {
1370 1370
 			$result = '*';
1371 1371
 		} else if ($allowEnum !== 'no') {
1372
-			$result = $term . '*';
1372
+			$result = $term.'*';
1373 1373
 		}
1374 1374
 		return $result;
1375 1375
 	}
@@ -1381,7 +1381,7 @@  discard block
 block discarded – undo
1381 1381
 	public function getFilterForUserCount() {
1382 1382
 		$filter = $this->combineFilterWithAnd(array(
1383 1383
 			$this->connection->ldapUserFilter,
1384
-			$this->connection->ldapUserDisplayName . '=*'
1384
+			$this->connection->ldapUserDisplayName.'=*'
1385 1385
 		));
1386 1386
 
1387 1387
 		return $filter;
@@ -1399,7 +1399,7 @@  discard block
 block discarded – undo
1399 1399
 			'ldapAgentName' => $name,
1400 1400
 			'ldapAgentPassword' => $password
1401 1401
 		);
1402
-		if(!$testConnection->setConfiguration($credentials)) {
1402
+		if (!$testConnection->setConfiguration($credentials)) {
1403 1403
 			return false;
1404 1404
 		}
1405 1405
 		return $testConnection->bind();
@@ -1421,30 +1421,30 @@  discard block
 block discarded – undo
1421 1421
 			// Sacrebleu! The UUID attribute is unknown :( We need first an
1422 1422
 			// existing DN to be able to reliably detect it.
1423 1423
 			$result = $this->search($filter, $base, ['dn'], 1);
1424
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1424
+			if (!isset($result[0]) || !isset($result[0]['dn'])) {
1425 1425
 				throw new \Exception('Cannot determine UUID attribute');
1426 1426
 			}
1427 1427
 			$dn = $result[0]['dn'][0];
1428
-			if(!$this->detectUuidAttribute($dn, true)) {
1428
+			if (!$this->detectUuidAttribute($dn, true)) {
1429 1429
 				throw new \Exception('Cannot determine UUID attribute');
1430 1430
 			}
1431 1431
 		} else {
1432 1432
 			// The UUID attribute is either known or an override is given.
1433 1433
 			// By calling this method we ensure that $this->connection->$uuidAttr
1434 1434
 			// is definitely set
1435
-			if(!$this->detectUuidAttribute('', true)) {
1435
+			if (!$this->detectUuidAttribute('', true)) {
1436 1436
 				throw new \Exception('Cannot determine UUID attribute');
1437 1437
 			}
1438 1438
 		}
1439 1439
 
1440 1440
 		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1441
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1441
+		if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1442 1442
 			$uuid = $this->formatGuid2ForFilterUser($uuid);
1443 1443
 		}
1444 1444
 
1445
-		$filter = $uuidAttr . '=' . $uuid;
1445
+		$filter = $uuidAttr.'='.$uuid;
1446 1446
 		$result = $this->searchUsers($filter, ['dn'], 2);
1447
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1447
+		if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1448 1448
 			// we put the count into account to make sure that this is
1449 1449
 			// really unique
1450 1450
 			return $result[0]['dn'][0];
@@ -1461,7 +1461,7 @@  discard block
 block discarded – undo
1461 1461
 	 * @return bool true on success, false otherwise
1462 1462
 	 */
1463 1463
 	private function detectUuidAttribute($dn, $isUser = true, $force = false) {
1464
-		if($isUser) {
1464
+		if ($isUser) {
1465 1465
 			$uuidAttr     = 'ldapUuidUserAttribute';
1466 1466
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1467 1467
 		} else {
@@ -1469,7 +1469,7 @@  discard block
 block discarded – undo
1469 1469
 			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1470 1470
 		}
1471 1471
 
1472
-		if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1472
+		if (($this->connection->$uuidAttr !== 'auto') && !$force) {
1473 1473
 			return true;
1474 1474
 		}
1475 1475
 
@@ -1481,9 +1481,9 @@  discard block
 block discarded – undo
1481 1481
 		// for now, supported attributes are entryUUID, nsuniqueid, objectGUID, ipaUniqueID
1482 1482
 		$testAttributes = array('entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid');
1483 1483
 
1484
-		foreach($testAttributes as $attribute) {
1484
+		foreach ($testAttributes as $attribute) {
1485 1485
 			$value = $this->readAttribute($dn, $attribute);
1486
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1486
+			if (is_array($value) && isset($value[0]) && !empty($value[0])) {
1487 1487
 				\OCP\Util::writeLog('user_ldap',
1488 1488
 									'Setting '.$attribute.' as '.$uuidAttr,
1489 1489
 									\OCP\Util::DEBUG);
@@ -1504,7 +1504,7 @@  discard block
 block discarded – undo
1504 1504
 	 * @return string|bool
1505 1505
 	 */
1506 1506
 	public function getUUID($dn, $isUser = true) {
1507
-		if($isUser) {
1507
+		if ($isUser) {
1508 1508
 			$uuidAttr     = 'ldapUuidUserAttribute';
1509 1509
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1510 1510
 		} else {
@@ -1513,15 +1513,15 @@  discard block
 block discarded – undo
1513 1513
 		}
1514 1514
 
1515 1515
 		$uuid = false;
1516
-		if($this->detectUuidAttribute($dn, $isUser)) {
1516
+		if ($this->detectUuidAttribute($dn, $isUser)) {
1517 1517
 			$uuid = $this->readAttribute($dn, $this->connection->$uuidAttr);
1518
-			if( !is_array($uuid)
1518
+			if (!is_array($uuid)
1519 1519
 				&& $uuidOverride !== ''
1520 1520
 				&& $this->detectUuidAttribute($dn, $isUser, true)) {
1521 1521
 					$uuid = $this->readAttribute($dn,
1522 1522
 												 $this->connection->$uuidAttr);
1523 1523
 			}
1524
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1524
+			if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1525 1525
 				$uuid = $uuid[0];
1526 1526
 			}
1527 1527
 		}
@@ -1538,19 +1538,19 @@  discard block
 block discarded – undo
1538 1538
 	private function convertObjectGUID2Str($oguid) {
1539 1539
 		$hex_guid = bin2hex($oguid);
1540 1540
 		$hex_guid_to_guid_str = '';
1541
-		for($k = 1; $k <= 4; ++$k) {
1541
+		for ($k = 1; $k <= 4; ++$k) {
1542 1542
 			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1543 1543
 		}
1544 1544
 		$hex_guid_to_guid_str .= '-';
1545
-		for($k = 1; $k <= 2; ++$k) {
1545
+		for ($k = 1; $k <= 2; ++$k) {
1546 1546
 			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1547 1547
 		}
1548 1548
 		$hex_guid_to_guid_str .= '-';
1549
-		for($k = 1; $k <= 2; ++$k) {
1549
+		for ($k = 1; $k <= 2; ++$k) {
1550 1550
 			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1551 1551
 		}
1552
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1553
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1552
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 16, 4);
1553
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 20);
1554 1554
 
1555 1555
 		return strtoupper($hex_guid_to_guid_str);
1556 1556
 	}
@@ -1567,11 +1567,11 @@  discard block
 block discarded – undo
1567 1567
 	 * @return string
1568 1568
 	 */
1569 1569
 	public function formatGuid2ForFilterUser($guid) {
1570
-		if(!is_string($guid)) {
1570
+		if (!is_string($guid)) {
1571 1571
 			throw new \InvalidArgumentException('String expected');
1572 1572
 		}
1573 1573
 		$blocks = explode('-', $guid);
1574
-		if(count($blocks) !== 5) {
1574
+		if (count($blocks) !== 5) {
1575 1575
 			/*
1576 1576
 			 * Why not throw an Exception instead? This method is a utility
1577 1577
 			 * called only when trying to figure out whether a "missing" known
@@ -1584,20 +1584,20 @@  discard block
 block discarded – undo
1584 1584
 			 * user. Instead we write a log message.
1585 1585
 			 */
1586 1586
 			\OC::$server->getLogger()->info(
1587
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1587
+				'Passed string does not resemble a valid GUID. Known UUID '.
1588 1588
 				'({uuid}) probably does not match UUID configuration.',
1589
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1589
+				['app' => 'user_ldap', 'uuid' => $guid]
1590 1590
 			);
1591 1591
 			return $guid;
1592 1592
 		}
1593
-		for($i=0; $i < 3; $i++) {
1593
+		for ($i = 0; $i < 3; $i++) {
1594 1594
 			$pairs = str_split($blocks[$i], 2);
1595 1595
 			$pairs = array_reverse($pairs);
1596 1596
 			$blocks[$i] = implode('', $pairs);
1597 1597
 		}
1598
-		for($i=0; $i < 5; $i++) {
1598
+		for ($i = 0; $i < 5; $i++) {
1599 1599
 			$pairs = str_split($blocks[$i], 2);
1600
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1600
+			$blocks[$i] = '\\'.implode('\\', $pairs);
1601 1601
 		}
1602 1602
 		return implode('', $blocks);
1603 1603
 	}
@@ -1611,12 +1611,12 @@  discard block
 block discarded – undo
1611 1611
 		$domainDN = $this->getDomainDNFromDN($dn);
1612 1612
 		$cacheKey = 'getSID-'.$domainDN;
1613 1613
 		$sid = $this->connection->getFromCache($cacheKey);
1614
-		if(!is_null($sid)) {
1614
+		if (!is_null($sid)) {
1615 1615
 			return $sid;
1616 1616
 		}
1617 1617
 
1618 1618
 		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1619
-		if(!is_array($objectSid) || empty($objectSid)) {
1619
+		if (!is_array($objectSid) || empty($objectSid)) {
1620 1620
 			$this->connection->writeToCache($cacheKey, false);
1621 1621
 			return false;
1622 1622
 		}
@@ -1674,12 +1674,12 @@  discard block
 block discarded – undo
1674 1674
 		$belongsToBase = false;
1675 1675
 		$bases = $this->helper->sanitizeDN($bases);
1676 1676
 
1677
-		foreach($bases as $base) {
1677
+		foreach ($bases as $base) {
1678 1678
 			$belongsToBase = true;
1679
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1679
+			if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) {
1680 1680
 				$belongsToBase = false;
1681 1681
 			}
1682
-			if($belongsToBase) {
1682
+			if ($belongsToBase) {
1683 1683
 				break;
1684 1684
 			}
1685 1685
 		}
@@ -1690,7 +1690,7 @@  discard block
 block discarded – undo
1690 1690
 	 * resets a running Paged Search operation
1691 1691
 	 */
1692 1692
 	private function abandonPagedSearch() {
1693
-		if($this->connection->hasPagedResultSupport) {
1693
+		if ($this->connection->hasPagedResultSupport) {
1694 1694
 			$cr = $this->connection->getConnectionResource();
1695 1695
 			$this->ldap->controlPagedResult($cr, 0, false, $this->lastCookie);
1696 1696
 			$this->getPagedSearchResultState();
@@ -1708,16 +1708,16 @@  discard block
 block discarded – undo
1708 1708
 	 * @return string containing the key or empty if none is cached
1709 1709
 	 */
1710 1710
 	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1711
-		if($offset === 0) {
1711
+		if ($offset === 0) {
1712 1712
 			return '';
1713 1713
 		}
1714 1714
 		$offset -= $limit;
1715 1715
 		//we work with cache here
1716
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1716
+		$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.intval($limit).'-'.intval($offset);
1717 1717
 		$cookie = '';
1718
-		if(isset($this->cookies[$cacheKey])) {
1718
+		if (isset($this->cookies[$cacheKey])) {
1719 1719
 			$cookie = $this->cookies[$cacheKey];
1720
-			if(is_null($cookie)) {
1720
+			if (is_null($cookie)) {
1721 1721
 				$cookie = '';
1722 1722
 			}
1723 1723
 		}
@@ -1735,11 +1735,11 @@  discard block
 block discarded – undo
1735 1735
 	 * @return bool
1736 1736
 	 */
1737 1737
 	public function hasMoreResults() {
1738
-		if(!$this->connection->hasPagedResultSupport) {
1738
+		if (!$this->connection->hasPagedResultSupport) {
1739 1739
 			return false;
1740 1740
 		}
1741 1741
 
1742
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1742
+		if (empty($this->lastCookie) && $this->lastCookie !== '0') {
1743 1743
 			// as in RFC 2696, when all results are returned, the cookie will
1744 1744
 			// be empty.
1745 1745
 			return false;
@@ -1759,8 +1759,8 @@  discard block
 block discarded – undo
1759 1759
 	 */
1760 1760
 	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1761 1761
 		// allow '0' for 389ds
1762
-		if(!empty($cookie) || $cookie === '0') {
1763
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1762
+		if (!empty($cookie) || $cookie === '0') {
1763
+			$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.intval($limit).'-'.intval($offset);
1764 1764
 			$this->cookies[$cacheKey] = $cookie;
1765 1765
 			$this->lastCookie = $cookie;
1766 1766
 		}
@@ -1787,17 +1787,17 @@  discard block
 block discarded – undo
1787 1787
 	 */
1788 1788
 	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1789 1789
 		$pagedSearchOK = false;
1790
-		if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1790
+		if ($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1791 1791
 			$offset = intval($offset); //can be null
1792 1792
 			\OCP\Util::writeLog('user_ldap',
1793 1793
 				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1794
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1794
+				.' attr '.print_r($attr, true).' limit '.$limit.' offset '.$offset,
1795 1795
 				\OCP\Util::DEBUG);
1796 1796
 			//get the cookie from the search for the previous search, required by LDAP
1797
-			foreach($bases as $base) {
1797
+			foreach ($bases as $base) {
1798 1798
 
1799 1799
 				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1800
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1800
+				if (empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1801 1801
 					// no cookie known, although the offset is not 0. Maybe cache run out. We need
1802 1802
 					// to start all over *sigh* (btw, Dear Reader, did you know LDAP paged
1803 1803
 					// searching was designed by MSFT?)
@@ -1810,18 +1810,18 @@  discard block
 block discarded – undo
1810 1810
 					$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1811 1811
 					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1812 1812
 					//TODO: remember this, probably does not change in the next request...
1813
-					if(empty($cookie) && $cookie !== '0') {
1813
+					if (empty($cookie) && $cookie !== '0') {
1814 1814
 						// '0' is valid, because 389ds
1815 1815
 						$cookie = null;
1816 1816
 					}
1817 1817
 				}
1818
-				if(!is_null($cookie)) {
1818
+				if (!is_null($cookie)) {
1819 1819
 					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1820 1820
 					$this->abandonPagedSearch();
1821 1821
 					$pagedSearchOK = $this->ldap->controlPagedResult(
1822 1822
 						$this->connection->getConnectionResource(), $limit,
1823 1823
 						false, $cookie);
1824
-					if(!$pagedSearchOK) {
1824
+					if (!$pagedSearchOK) {
1825 1825
 						return false;
1826 1826
 					}
1827 1827
 					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
@@ -1838,7 +1838,7 @@  discard block
 block discarded – undo
1838 1838
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
1839 1839
 		 * if we don't have a previous paged search.
1840 1840
 		 */
1841
-		} else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1841
+		} else if ($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1842 1842
 			// a search without limit was requested. However, if we do use
1843 1843
 			// Paged Search once, we always must do it. This requires us to
1844 1844
 			// initialize it with the configured page size.
Please login to merge, or discard this patch.
apps/theming/lib/Util.php 3 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -52,7 +52,7 @@  discard block
 block discarded – undo
52 52
 	/**
53 53
 	 * get color for on-page elements:
54 54
 	 * theme color by default, grey if theme color is to bright
55
-	 * @param $color
55
+	 * @param string $color
56 56
 	 * @return string
57 57
 	 */
58 58
 	public function elementColor($color) {
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
 	}
84 84
 
85 85
 	/**
86
-	 * @param $color
86
+	 * @param string $color
87 87
 	 * @return string base64 encoded radio button svg
88 88
 	 */
89 89
 	public function generateRadioButton($color) {
@@ -152,8 +152,8 @@  discard block
 block discarded – undo
152 152
 	/**
153 153
 	 * replace default color with a custom one
154 154
 	 *
155
-	 * @param $svg string content of a svg file
156
-	 * @param $color string color to match
155
+	 * @param string $svg string content of a svg file
156
+	 * @param string $color string color to match
157 157
 	 * @return string
158 158
 	 */
159 159
 	public function colorizeSvg($svg, $color) {
Please login to merge, or discard this patch.
Indentation   +159 added lines, -159 removed lines patch added patch discarded remove patch
@@ -30,164 +30,164 @@
 block discarded – undo
30 30
 
31 31
 class Util {
32 32
 
33
-	/** @var IConfig */
34
-	private $config;
35
-
36
-	/** @var IRootFolder */
37
-	private $rootFolder;
38
-
39
-	/** @var IAppManager */
40
-	private $appManager;
41
-
42
-	/**
43
-	 * Util constructor.
44
-	 *
45
-	 * @param IConfig $config
46
-	 * @param IRootFolder $rootFolder
47
-	 * @param IAppManager $appManager
48
-	 */
49
-	public function __construct(IConfig $config, IRootFolder $rootFolder, IAppManager $appManager) {
50
-		$this->config = $config;
51
-		$this->rootFolder = $rootFolder;
52
-		$this->appManager = $appManager;
53
-	}
54
-
55
-	/**
56
-	 * @param string $color rgb color value
57
-	 * @return bool
58
-	 */
59
-	public function invertTextColor($color) {
60
-		$l = $this->calculateLuminance($color);
61
-		if($l>0.5) {
62
-			return true;
63
-		} else {
64
-			return false;
65
-		}
66
-	}
67
-
68
-	/**
69
-	 * get color for on-page elements:
70
-	 * theme color by default, grey if theme color is to bright
71
-	 * @param $color
72
-	 * @return string
73
-	 */
74
-	public function elementColor($color) {
75
-		$l = $this->calculateLuminance($color);
76
-		if($l>0.8) {
77
-			return '#555555';
78
-		} else {
79
-			return $color;
80
-		}
81
-	}
82
-
83
-	/**
84
-	 * @param string $color rgb color value
85
-	 * @return float
86
-	 */
87
-	public function calculateLuminance($color) {
88
-		$hex = preg_replace("/[^0-9A-Fa-f]/", '', $color);
89
-		if (strlen($hex) === 3) {
90
-			$hex = $hex{0} . $hex{0} . $hex{1} . $hex{1} . $hex{2} . $hex{2};
91
-		}
92
-		if (strlen($hex) !== 6) {
93
-			return 0;
94
-		}
95
-		$r = hexdec(substr($hex, 0, 2));
96
-		$g = hexdec(substr($hex, 2, 2));
97
-		$b = hexdec(substr($hex, 4, 2));
98
-		return (0.299 * $r + 0.587 * $g + 0.114 * $b)/255;
99
-	}
100
-
101
-	/**
102
-	 * @param $color
103
-	 * @return string base64 encoded radio button svg
104
-	 */
105
-	public function generateRadioButton($color) {
106
-		$radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">' .
107
-			'<path d="M8 1a7 7 0 0 0-7 7 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0-7-7zm0 1a6 6 0 0 1 6 6 6 6 0 0 1-6 6 6 6 0 0 1-6-6 6 6 0 0 1 6-6zm0 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z" fill="'.$color.'"/></svg>';
108
-		return base64_encode($radioButtonIcon);
109
-	}
110
-
111
-
112
-	/**
113
-	 * @param $app string app name
114
-	 * @return string path to app icon / logo
115
-	 */
116
-	public function getAppIcon($app) {
117
-		$app = str_replace(array('\0', '/', '\\', '..'), '', $app);
118
-		try {
119
-			$appPath = $this->appManager->getAppPath($app);
120
-			$icon = $appPath . '/img/' . $app . '.svg';
121
-			if (file_exists($icon)) {
122
-				return $icon;
123
-			}
124
-			$icon = $appPath . '/img/app.svg';
125
-			if (file_exists($icon)) {
126
-				return $icon;
127
-			}
128
-		} catch (AppPathNotFoundException $e) {}
129
-
130
-		if($this->config->getAppValue('theming', 'logoMime', '') !== '' && $this->rootFolder->nodeExists('/themedinstancelogo')) {
131
-			return $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/themedinstancelogo';
132
-		}
133
-		return \OC::$SERVERROOT . '/core/img/logo.svg';
134
-	}
135
-
136
-	/**
137
-	 * @param $app string app name
138
-	 * @param $image string relative path to image in app folder
139
-	 * @return string|false absolute path to image
140
-	 */
141
-	public function getAppImage($app, $image) {
142
-		$app = str_replace(array('\0', '/', '\\', '..'), '', $app);
143
-		$image = str_replace(array('\0', '\\', '..'), '', $image);
144
-		if ($app === "core") {
145
-			$icon = \OC::$SERVERROOT . '/core/img/' . $image;
146
-			if (file_exists($icon)) {
147
-				return $icon;
148
-			}
149
-		}
150
-
151
-		try {
152
-			$appPath = $this->appManager->getAppPath($app);
153
-		} catch (AppPathNotFoundException $e) {
154
-			return false;
155
-		}
156
-
157
-		$icon = $appPath . '/img/' . $image;
158
-		if (file_exists($icon)) {
159
-			return $icon;
160
-		}
161
-		$icon = $appPath . '/img/' . $image . '.svg';
162
-		if (file_exists($icon)) {
163
-			return $icon;
164
-		}
165
-		$icon = $appPath . '/img/' . $image . '.png';
166
-		if (file_exists($icon)) {
167
-			return $icon;
168
-		}
169
-		$icon = $appPath . '/img/' . $image . '.gif';
170
-		if (file_exists($icon)) {
171
-			return $icon;
172
-		}
173
-		$icon = $appPath . '/img/' . $image . '.jpg';
174
-		if (file_exists($icon)) {
175
-			return $icon;
176
-		}
177
-
178
-		return false;
179
-	}
180
-
181
-	/**
182
-	 * replace default color with a custom one
183
-	 *
184
-	 * @param $svg string content of a svg file
185
-	 * @param $color string color to match
186
-	 * @return string
187
-	 */
188
-	public function colorizeSvg($svg, $color) {
189
-		$svg = preg_replace('/#0082c9/i', $color, $svg);
190
-		return $svg;
191
-	}
33
+    /** @var IConfig */
34
+    private $config;
35
+
36
+    /** @var IRootFolder */
37
+    private $rootFolder;
38
+
39
+    /** @var IAppManager */
40
+    private $appManager;
41
+
42
+    /**
43
+     * Util constructor.
44
+     *
45
+     * @param IConfig $config
46
+     * @param IRootFolder $rootFolder
47
+     * @param IAppManager $appManager
48
+     */
49
+    public function __construct(IConfig $config, IRootFolder $rootFolder, IAppManager $appManager) {
50
+        $this->config = $config;
51
+        $this->rootFolder = $rootFolder;
52
+        $this->appManager = $appManager;
53
+    }
54
+
55
+    /**
56
+     * @param string $color rgb color value
57
+     * @return bool
58
+     */
59
+    public function invertTextColor($color) {
60
+        $l = $this->calculateLuminance($color);
61
+        if($l>0.5) {
62
+            return true;
63
+        } else {
64
+            return false;
65
+        }
66
+    }
67
+
68
+    /**
69
+     * get color for on-page elements:
70
+     * theme color by default, grey if theme color is to bright
71
+     * @param $color
72
+     * @return string
73
+     */
74
+    public function elementColor($color) {
75
+        $l = $this->calculateLuminance($color);
76
+        if($l>0.8) {
77
+            return '#555555';
78
+        } else {
79
+            return $color;
80
+        }
81
+    }
82
+
83
+    /**
84
+     * @param string $color rgb color value
85
+     * @return float
86
+     */
87
+    public function calculateLuminance($color) {
88
+        $hex = preg_replace("/[^0-9A-Fa-f]/", '', $color);
89
+        if (strlen($hex) === 3) {
90
+            $hex = $hex{0} . $hex{0} . $hex{1} . $hex{1} . $hex{2} . $hex{2};
91
+        }
92
+        if (strlen($hex) !== 6) {
93
+            return 0;
94
+        }
95
+        $r = hexdec(substr($hex, 0, 2));
96
+        $g = hexdec(substr($hex, 2, 2));
97
+        $b = hexdec(substr($hex, 4, 2));
98
+        return (0.299 * $r + 0.587 * $g + 0.114 * $b)/255;
99
+    }
100
+
101
+    /**
102
+     * @param $color
103
+     * @return string base64 encoded radio button svg
104
+     */
105
+    public function generateRadioButton($color) {
106
+        $radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">' .
107
+            '<path d="M8 1a7 7 0 0 0-7 7 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0-7-7zm0 1a6 6 0 0 1 6 6 6 6 0 0 1-6 6 6 6 0 0 1-6-6 6 6 0 0 1 6-6zm0 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z" fill="'.$color.'"/></svg>';
108
+        return base64_encode($radioButtonIcon);
109
+    }
110
+
111
+
112
+    /**
113
+     * @param $app string app name
114
+     * @return string path to app icon / logo
115
+     */
116
+    public function getAppIcon($app) {
117
+        $app = str_replace(array('\0', '/', '\\', '..'), '', $app);
118
+        try {
119
+            $appPath = $this->appManager->getAppPath($app);
120
+            $icon = $appPath . '/img/' . $app . '.svg';
121
+            if (file_exists($icon)) {
122
+                return $icon;
123
+            }
124
+            $icon = $appPath . '/img/app.svg';
125
+            if (file_exists($icon)) {
126
+                return $icon;
127
+            }
128
+        } catch (AppPathNotFoundException $e) {}
129
+
130
+        if($this->config->getAppValue('theming', 'logoMime', '') !== '' && $this->rootFolder->nodeExists('/themedinstancelogo')) {
131
+            return $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/themedinstancelogo';
132
+        }
133
+        return \OC::$SERVERROOT . '/core/img/logo.svg';
134
+    }
135
+
136
+    /**
137
+     * @param $app string app name
138
+     * @param $image string relative path to image in app folder
139
+     * @return string|false absolute path to image
140
+     */
141
+    public function getAppImage($app, $image) {
142
+        $app = str_replace(array('\0', '/', '\\', '..'), '', $app);
143
+        $image = str_replace(array('\0', '\\', '..'), '', $image);
144
+        if ($app === "core") {
145
+            $icon = \OC::$SERVERROOT . '/core/img/' . $image;
146
+            if (file_exists($icon)) {
147
+                return $icon;
148
+            }
149
+        }
150
+
151
+        try {
152
+            $appPath = $this->appManager->getAppPath($app);
153
+        } catch (AppPathNotFoundException $e) {
154
+            return false;
155
+        }
156
+
157
+        $icon = $appPath . '/img/' . $image;
158
+        if (file_exists($icon)) {
159
+            return $icon;
160
+        }
161
+        $icon = $appPath . '/img/' . $image . '.svg';
162
+        if (file_exists($icon)) {
163
+            return $icon;
164
+        }
165
+        $icon = $appPath . '/img/' . $image . '.png';
166
+        if (file_exists($icon)) {
167
+            return $icon;
168
+        }
169
+        $icon = $appPath . '/img/' . $image . '.gif';
170
+        if (file_exists($icon)) {
171
+            return $icon;
172
+        }
173
+        $icon = $appPath . '/img/' . $image . '.jpg';
174
+        if (file_exists($icon)) {
175
+            return $icon;
176
+        }
177
+
178
+        return false;
179
+    }
180
+
181
+    /**
182
+     * replace default color with a custom one
183
+     *
184
+     * @param $svg string content of a svg file
185
+     * @param $color string color to match
186
+     * @return string
187
+     */
188
+    public function colorizeSvg($svg, $color) {
189
+        $svg = preg_replace('/#0082c9/i', $color, $svg);
190
+        return $svg;
191
+    }
192 192
 
193 193
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 	 */
59 59
 	public function invertTextColor($color) {
60 60
 		$l = $this->calculateLuminance($color);
61
-		if($l>0.5) {
61
+		if ($l > 0.5) {
62 62
 			return true;
63 63
 		} else {
64 64
 			return false;
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 	 */
74 74
 	public function elementColor($color) {
75 75
 		$l = $this->calculateLuminance($color);
76
-		if($l>0.8) {
76
+		if ($l > 0.8) {
77 77
 			return '#555555';
78 78
 		} else {
79 79
 			return $color;
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 	public function calculateLuminance($color) {
88 88
 		$hex = preg_replace("/[^0-9A-Fa-f]/", '', $color);
89 89
 		if (strlen($hex) === 3) {
90
-			$hex = $hex{0} . $hex{0} . $hex{1} . $hex{1} . $hex{2} . $hex{2};
90
+			$hex = $hex{0}.$hex{0}.$hex{1}.$hex{1}.$hex{2}.$hex{2};
91 91
 		}
92 92
 		if (strlen($hex) !== 6) {
93 93
 			return 0;
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 		$r = hexdec(substr($hex, 0, 2));
96 96
 		$g = hexdec(substr($hex, 2, 2));
97 97
 		$b = hexdec(substr($hex, 4, 2));
98
-		return (0.299 * $r + 0.587 * $g + 0.114 * $b)/255;
98
+		return (0.299 * $r + 0.587 * $g + 0.114 * $b) / 255;
99 99
 	}
100 100
 
101 101
 	/**
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 	 * @return string base64 encoded radio button svg
104 104
 	 */
105 105
 	public function generateRadioButton($color) {
106
-		$radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">' .
106
+		$radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">'.
107 107
 			'<path d="M8 1a7 7 0 0 0-7 7 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0-7-7zm0 1a6 6 0 0 1 6 6 6 6 0 0 1-6 6 6 6 0 0 1-6-6 6 6 0 0 1 6-6zm0 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z" fill="'.$color.'"/></svg>';
108 108
 		return base64_encode($radioButtonIcon);
109 109
 	}
@@ -117,20 +117,20 @@  discard block
 block discarded – undo
117 117
 		$app = str_replace(array('\0', '/', '\\', '..'), '', $app);
118 118
 		try {
119 119
 			$appPath = $this->appManager->getAppPath($app);
120
-			$icon = $appPath . '/img/' . $app . '.svg';
120
+			$icon = $appPath.'/img/'.$app.'.svg';
121 121
 			if (file_exists($icon)) {
122 122
 				return $icon;
123 123
 			}
124
-			$icon = $appPath . '/img/app.svg';
124
+			$icon = $appPath.'/img/app.svg';
125 125
 			if (file_exists($icon)) {
126 126
 				return $icon;
127 127
 			}
128 128
 		} catch (AppPathNotFoundException $e) {}
129 129
 
130
-		if($this->config->getAppValue('theming', 'logoMime', '') !== '' && $this->rootFolder->nodeExists('/themedinstancelogo')) {
131
-			return $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/themedinstancelogo';
130
+		if ($this->config->getAppValue('theming', 'logoMime', '') !== '' && $this->rootFolder->nodeExists('/themedinstancelogo')) {
131
+			return $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/themedinstancelogo';
132 132
 		}
133
-		return \OC::$SERVERROOT . '/core/img/logo.svg';
133
+		return \OC::$SERVERROOT.'/core/img/logo.svg';
134 134
 	}
135 135
 
136 136
 	/**
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 		$app = str_replace(array('\0', '/', '\\', '..'), '', $app);
143 143
 		$image = str_replace(array('\0', '\\', '..'), '', $image);
144 144
 		if ($app === "core") {
145
-			$icon = \OC::$SERVERROOT . '/core/img/' . $image;
145
+			$icon = \OC::$SERVERROOT.'/core/img/'.$image;
146 146
 			if (file_exists($icon)) {
147 147
 				return $icon;
148 148
 			}
@@ -154,23 +154,23 @@  discard block
 block discarded – undo
154 154
 			return false;
155 155
 		}
156 156
 
157
-		$icon = $appPath . '/img/' . $image;
157
+		$icon = $appPath.'/img/'.$image;
158 158
 		if (file_exists($icon)) {
159 159
 			return $icon;
160 160
 		}
161
-		$icon = $appPath . '/img/' . $image . '.svg';
161
+		$icon = $appPath.'/img/'.$image.'.svg';
162 162
 		if (file_exists($icon)) {
163 163
 			return $icon;
164 164
 		}
165
-		$icon = $appPath . '/img/' . $image . '.png';
165
+		$icon = $appPath.'/img/'.$image.'.png';
166 166
 		if (file_exists($icon)) {
167 167
 			return $icon;
168 168
 		}
169
-		$icon = $appPath . '/img/' . $image . '.gif';
169
+		$icon = $appPath.'/img/'.$image.'.gif';
170 170
 		if (file_exists($icon)) {
171 171
 			return $icon;
172 172
 		}
173
-		$icon = $appPath . '/img/' . $image . '.jpg';
173
+		$icon = $appPath.'/img/'.$image.'.jpg';
174 174
 		if (file_exists($icon)) {
175 175
 			return $icon;
176 176
 		}
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/PublicCalendarRoot.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -21,7 +21,6 @@
 block discarded – undo
21 21
 namespace OCA\DAV\CalDAV;
22 22
 
23 23
 use Sabre\DAV\Collection;
24
-use Sabre\DAV\Exception\NotFound;
25 24
 
26 25
 class PublicCalendarRoot extends Collection {
27 26
 
Please login to merge, or discard this patch.
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -25,43 +25,43 @@
 block discarded – undo
25 25
 
26 26
 class PublicCalendarRoot extends Collection {
27 27
 
28
-	/** @var CalDavBackend */
29
-	protected $caldavBackend;
28
+    /** @var CalDavBackend */
29
+    protected $caldavBackend;
30 30
 
31
-	/** @var \OCP\IL10N */
32
-	protected $l10n;
31
+    /** @var \OCP\IL10N */
32
+    protected $l10n;
33 33
 
34
-	function __construct(CalDavBackend $caldavBackend) {
35
-		$this->caldavBackend = $caldavBackend;
36
-		$this->l10n = \OC::$server->getL10N('dav');
37
-	}
34
+    function __construct(CalDavBackend $caldavBackend) {
35
+        $this->caldavBackend = $caldavBackend;
36
+        $this->l10n = \OC::$server->getL10N('dav');
37
+    }
38 38
 
39
-	/**
40
-	 * @inheritdoc
41
-	 */
42
-	function getName() {
43
-		return 'public-calendars';
44
-	}
39
+    /**
40
+     * @inheritdoc
41
+     */
42
+    function getName() {
43
+        return 'public-calendars';
44
+    }
45 45
 
46
-	/**
47
-	 * @inheritdoc
48
-	 */
49
-	function getChild($name) {
50
-		$calendar = $this->caldavBackend->getPublicCalendar($name);
51
-		return new Calendar($this->caldavBackend, $calendar, $this->l10n);
52
-	}
46
+    /**
47
+     * @inheritdoc
48
+     */
49
+    function getChild($name) {
50
+        $calendar = $this->caldavBackend->getPublicCalendar($name);
51
+        return new Calendar($this->caldavBackend, $calendar, $this->l10n);
52
+    }
53 53
 
54
-	/**
55
-	 * @inheritdoc
56
-	 */
57
-	function getChildren() {
58
-		$calendars = $this->caldavBackend->getPublicCalendars();
59
-		$children = [];
60
-		foreach ($calendars as $calendar) {
61
-			// TODO: maybe implement a new class PublicCalendar ???
62
-			$children[] = new Calendar($this->caldavBackend, $calendar, $this->l10n);
63
-		}
54
+    /**
55
+     * @inheritdoc
56
+     */
57
+    function getChildren() {
58
+        $calendars = $this->caldavBackend->getPublicCalendars();
59
+        $children = [];
60
+        foreach ($calendars as $calendar) {
61
+            // TODO: maybe implement a new class PublicCalendar ???
62
+            $children[] = new Calendar($this->caldavBackend, $calendar, $this->l10n);
63
+        }
64 64
 
65
-		return $children;
66
-	}
65
+        return $children;
66
+    }
67 67
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Http/Output.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@
 block discarded – undo
34 34
 	private $webRoot;
35 35
 
36 36
 	/**
37
-	 * @param $webRoot
37
+	 * @param string $webRoot
38 38
 	 */
39 39
 	public function __construct($webRoot) {
40 40
 		$this->webRoot = $webRoot;
Please login to merge, or discard this patch.
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -30,70 +30,70 @@
 block discarded – undo
30 30
  * Very thin wrapper class to make output testable
31 31
  */
32 32
 class Output implements IOutput {
33
-	/** @var string */
34
-	private $webRoot;
33
+    /** @var string */
34
+    private $webRoot;
35 35
 
36
-	/**
37
-	 * @param $webRoot
38
-	 */
39
-	public function __construct($webRoot) {
40
-		$this->webRoot = $webRoot;
41
-	}
36
+    /**
37
+     * @param $webRoot
38
+     */
39
+    public function __construct($webRoot) {
40
+        $this->webRoot = $webRoot;
41
+    }
42 42
 
43
-	/**
44
-	 * @param string $out
45
-	 */
46
-	public function setOutput($out) {
47
-		print($out);
48
-	}
43
+    /**
44
+     * @param string $out
45
+     */
46
+    public function setOutput($out) {
47
+        print($out);
48
+    }
49 49
 
50
-	/**
51
-	 * @param string|resource $path or file handle
52
-	 *
53
-	 * @return bool false if an error occurred
54
-	 */
55
-	public function setReadfile($path) {
56
-		if (is_resource($path)) {
57
-			$output = fopen('php://output', 'w');
58
-			return stream_copy_to_stream($path, $output) > 0;
59
-		} else {
60
-			return @readfile($path);
61
-		}
62
-	}
50
+    /**
51
+     * @param string|resource $path or file handle
52
+     *
53
+     * @return bool false if an error occurred
54
+     */
55
+    public function setReadfile($path) {
56
+        if (is_resource($path)) {
57
+            $output = fopen('php://output', 'w');
58
+            return stream_copy_to_stream($path, $output) > 0;
59
+        } else {
60
+            return @readfile($path);
61
+        }
62
+    }
63 63
 
64
-	/**
65
-	 * @param string $header
66
-	 */
67
-	public function setHeader($header) {
68
-		header($header);
69
-	}
64
+    /**
65
+     * @param string $header
66
+     */
67
+    public function setHeader($header) {
68
+        header($header);
69
+    }
70 70
 
71
-	/**
72
-	 * @param int $code sets the http status code
73
-	 */
74
-	public function setHttpResponseCode($code) {
75
-		http_response_code($code);
76
-	}
71
+    /**
72
+     * @param int $code sets the http status code
73
+     */
74
+    public function setHttpResponseCode($code) {
75
+        http_response_code($code);
76
+    }
77 77
 
78
-	/**
79
-	 * @return int returns the current http response code
80
-	 */
81
-	public function getHttpResponseCode() {
82
-		return http_response_code();
83
-	}
78
+    /**
79
+     * @return int returns the current http response code
80
+     */
81
+    public function getHttpResponseCode() {
82
+        return http_response_code();
83
+    }
84 84
 
85
-	/**
86
-	 * @param string $name
87
-	 * @param string $value
88
-	 * @param int $expire
89
-	 * @param string $path
90
-	 * @param string $domain
91
-	 * @param bool $secure
92
-	 * @param bool $httpOnly
93
-	 */
94
-	public function setCookie($name, $value, $expire, $path, $domain, $secure, $httpOnly) {
95
-		$path = $this->webRoot ? : '/';
96
-		setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly);
97
-	}
85
+    /**
86
+     * @param string $name
87
+     * @param string $value
88
+     * @param int $expire
89
+     * @param string $path
90
+     * @param string $domain
91
+     * @param bool $secure
92
+     * @param bool $httpOnly
93
+     */
94
+    public function setCookie($name, $value, $expire, $path, $domain, $secure, $httpOnly) {
95
+        $path = $this->webRoot ? : '/';
96
+        setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly);
97
+    }
98 98
 
99 99
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -92,7 +92,7 @@
 block discarded – undo
92 92
 	 * @param bool $httpOnly
93 93
 	 */
94 94
 	public function setCookie($name, $value, $expire, $path, $domain, $secure, $httpOnly) {
95
-		$path = $this->webRoot ? : '/';
95
+		$path = $this->webRoot ?: '/';
96 96
 		setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly);
97 97
 	}
98 98
 
Please login to merge, or discard this patch.
apps/files_external/lib/Service/DBConfigService.php 3 patches
Doc Comments   +16 added lines patch added patch discarded remove patch
@@ -89,6 +89,9 @@  discard block
 block discarded – undo
89 89
 		return $this->getMountsFromQuery($query);
90 90
 	}
91 91
 
92
+	/**
93
+	 * @param string $userId
94
+	 */
92 95
 	public function getMountsForUser($userId, $groupIds) {
93 96
 		$builder = $this->connection->getQueryBuilder();
94 97
 		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
@@ -125,6 +128,10 @@  discard block
 block discarded – undo
125 128
 		return $this->getMountsFromQuery($query);
126 129
 	}
127 130
 
131
+	/**
132
+	 * @param integer $type
133
+	 * @param string|null $value
134
+	 */
128 135
 	protected function getForQuery(IQueryBuilder $builder, $type, $value) {
129 136
 		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
130 137
 			->from('external_mounts', 'm')
@@ -332,6 +339,9 @@  discard block
 block discarded – undo
332 339
 		}
333 340
 	}
334 341
 
342
+	/**
343
+	 * @param integer $mountId
344
+	 */
335 345
 	public function addApplicable($mountId, $type, $value) {
336 346
 		$this->connection->insertIfNotExist('*PREFIX*external_applicable', [
337 347
 			'mount_id' => $mountId,
@@ -340,6 +350,9 @@  discard block
 block discarded – undo
340 350
 		], ['mount_id', 'type', 'value']);
341 351
 	}
342 352
 
353
+	/**
354
+	 * @param integer $mountId
355
+	 */
343 356
 	public function removeApplicable($mountId, $type, $value) {
344 357
 		$builder = $this->connection->getQueryBuilder();
345 358
 		$query = $builder->delete('external_applicable')
@@ -473,6 +486,9 @@  discard block
 block discarded – undo
473 486
 		return array_combine($keys, $values);
474 487
 	}
475 488
 
489
+	/**
490
+	 * @param string $value
491
+	 */
476 492
 	private function encryptValue($value) {
477 493
 		return $this->crypto->encrypt($value);
478 494
 	}
Please login to merge, or discard this patch.
Indentation   +452 added lines, -452 removed lines patch added patch discarded remove patch
@@ -32,456 +32,456 @@
 block discarded – undo
32 32
  * Stores the mount config in the database
33 33
  */
34 34
 class DBConfigService {
35
-	const MOUNT_TYPE_ADMIN = 1;
36
-	const MOUNT_TYPE_PERSONAl = 2;
37
-
38
-	const APPLICABLE_TYPE_GLOBAL = 1;
39
-	const APPLICABLE_TYPE_GROUP = 2;
40
-	const APPLICABLE_TYPE_USER = 3;
41
-
42
-	/**
43
-	 * @var IDBConnection
44
-	 */
45
-	private $connection;
46
-
47
-	/**
48
-	 * @var ICrypto
49
-	 */
50
-	private $crypto;
51
-
52
-	/**
53
-	 * DBConfigService constructor.
54
-	 *
55
-	 * @param IDBConnection $connection
56
-	 * @param ICrypto $crypto
57
-	 */
58
-	public function __construct(IDBConnection $connection, ICrypto $crypto) {
59
-		$this->connection = $connection;
60
-		$this->crypto = $crypto;
61
-	}
62
-
63
-	/**
64
-	 * @param int $mountId
65
-	 * @return array
66
-	 */
67
-	public function getMountById($mountId) {
68
-		$builder = $this->connection->getQueryBuilder();
69
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
70
-			->from('external_mounts', 'm')
71
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
72
-		$mounts = $this->getMountsFromQuery($query);
73
-		if (count($mounts) > 0) {
74
-			return $mounts[0];
75
-		} else {
76
-			return null;
77
-		}
78
-	}
79
-
80
-	/**
81
-	 * Get all configured mounts
82
-	 *
83
-	 * @return array
84
-	 */
85
-	public function getAllMounts() {
86
-		$builder = $this->connection->getQueryBuilder();
87
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
88
-			->from('external_mounts');
89
-		return $this->getMountsFromQuery($query);
90
-	}
91
-
92
-	public function getMountsForUser($userId, $groupIds) {
93
-		$builder = $this->connection->getQueryBuilder();
94
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
95
-			->from('external_mounts', 'm')
96
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
97
-			->where($builder->expr()->orX(
98
-				$builder->expr()->andX( // global mounts
99
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GLOBAL, IQueryBuilder::PARAM_INT)),
100
-					$builder->expr()->isNull('a.value')
101
-				),
102
-				$builder->expr()->andX( // mounts for user
103
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_USER, IQueryBuilder::PARAM_INT)),
104
-					$builder->expr()->eq('a.value', $builder->createNamedParameter($userId))
105
-				),
106
-				$builder->expr()->andX( // mounts for group
107
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GROUP, IQueryBuilder::PARAM_INT)),
108
-					$builder->expr()->in('a.value', $builder->createNamedParameter($groupIds, IQueryBuilder::PARAM_INT_ARRAY))
109
-				)
110
-			));
111
-
112
-		return $this->getMountsFromQuery($query);
113
-	}
114
-
115
-	/**
116
-	 * Get admin defined mounts
117
-	 *
118
-	 * @return array
119
-	 */
120
-	public function getAdminMounts() {
121
-		$builder = $this->connection->getQueryBuilder();
122
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
123
-			->from('external_mounts')
124
-			->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
125
-		return $this->getMountsFromQuery($query);
126
-	}
127
-
128
-	protected function getForQuery(IQueryBuilder $builder, $type, $value) {
129
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
130
-			->from('external_mounts', 'm')
131
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
132
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
133
-
134
-		if (is_null($value)) {
135
-			$query = $query->andWhere($builder->expr()->isNull('a.value'));
136
-		} else {
137
-			$query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
138
-		}
139
-
140
-		return $query;
141
-	}
142
-
143
-	/**
144
-	 * Get mounts by applicable
145
-	 *
146
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
147
-	 * @param string|null $value user_id, group_id or null for global mounts
148
-	 * @return array
149
-	 */
150
-	public function getMountsFor($type, $value) {
151
-		$builder = $this->connection->getQueryBuilder();
152
-		$query = $this->getForQuery($builder, $type, $value);
153
-
154
-		return $this->getMountsFromQuery($query);
155
-	}
156
-
157
-	/**
158
-	 * Get admin defined mounts by applicable
159
-	 *
160
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
161
-	 * @param string|null $value user_id, group_id or null for global mounts
162
-	 * @return array
163
-	 */
164
-	public function getAdminMountsFor($type, $value) {
165
-		$builder = $this->connection->getQueryBuilder();
166
-		$query = $this->getForQuery($builder, $type, $value);
167
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
168
-
169
-		return $this->getMountsFromQuery($query);
170
-	}
171
-
172
-	/**
173
-	 * Get admin defined mounts for multiple applicable
174
-	 *
175
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
176
-	 * @param string[] $values user_ids or group_ids
177
-	 * @return array
178
-	 */
179
-	public function getAdminMountsForMultiple($type, array $values) {
180
-		$builder = $this->connection->getQueryBuilder();
181
-		$params = array_map(function ($value) use ($builder) {
182
-			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
183
-		}, $values);
184
-
185
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
186
-			->from('external_mounts', 'm')
187
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
188
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
189
-			->andWhere($builder->expr()->in('a.value', $params));
190
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
191
-
192
-		return $this->getMountsFromQuery($query);
193
-	}
194
-
195
-	/**
196
-	 * Get user defined mounts by applicable
197
-	 *
198
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
199
-	 * @param string|null $value user_id, group_id or null for global mounts
200
-	 * @return array
201
-	 */
202
-	public function getUserMountsFor($type, $value) {
203
-		$builder = $this->connection->getQueryBuilder();
204
-		$query = $this->getForQuery($builder, $type, $value);
205
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
206
-
207
-		return $this->getMountsFromQuery($query);
208
-	}
209
-
210
-	/**
211
-	 * Add a mount to the database
212
-	 *
213
-	 * @param string $mountPoint
214
-	 * @param string $storageBackend
215
-	 * @param string $authBackend
216
-	 * @param int $priority
217
-	 * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
218
-	 * @return int the id of the new mount
219
-	 */
220
-	public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
221
-		if (!$priority) {
222
-			$priority = 100;
223
-		}
224
-		$builder = $this->connection->getQueryBuilder();
225
-		$query = $builder->insert('external_mounts')
226
-			->values([
227
-				'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
228
-				'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
229
-				'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
230
-				'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
231
-				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
232
-			]);
233
-		$query->execute();
234
-		return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
235
-	}
236
-
237
-	/**
238
-	 * Remove a mount from the database
239
-	 *
240
-	 * @param int $mountId
241
-	 */
242
-	public function removeMount($mountId) {
243
-		$builder = $this->connection->getQueryBuilder();
244
-		$query = $builder->delete('external_mounts')
245
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
246
-		$query->execute();
247
-
248
-		$query = $builder->delete('external_applicable')
249
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
250
-		$query->execute();
251
-
252
-		$query = $builder->delete('external_config')
253
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
254
-		$query->execute();
255
-
256
-		$query = $builder->delete('external_options')
257
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
258
-		$query->execute();
259
-	}
260
-
261
-	/**
262
-	 * @param int $mountId
263
-	 * @param string $newMountPoint
264
-	 */
265
-	public function setMountPoint($mountId, $newMountPoint) {
266
-		$builder = $this->connection->getQueryBuilder();
267
-
268
-		$query = $builder->update('external_mounts')
269
-			->set('mount_point', $builder->createNamedParameter($newMountPoint))
270
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
271
-
272
-		$query->execute();
273
-	}
274
-
275
-	/**
276
-	 * @param int $mountId
277
-	 * @param string $newAuthBackend
278
-	 */
279
-	public function setAuthBackend($mountId, $newAuthBackend) {
280
-		$builder = $this->connection->getQueryBuilder();
281
-
282
-		$query = $builder->update('external_mounts')
283
-			->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
284
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
285
-
286
-		$query->execute();
287
-	}
288
-
289
-	/**
290
-	 * @param int $mountId
291
-	 * @param string $key
292
-	 * @param string $value
293
-	 */
294
-	public function setConfig($mountId, $key, $value) {
295
-		if ($key === 'password') {
296
-			$value = $this->encryptValue($value);
297
-		}
298
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
299
-			'mount_id' => $mountId,
300
-			'key' => $key,
301
-			'value' => $value
302
-		], ['mount_id', 'key']);
303
-		if ($count === 0) {
304
-			$builder = $this->connection->getQueryBuilder();
305
-			$query = $builder->update('external_config')
306
-				->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
307
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
308
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
309
-			$query->execute();
310
-		}
311
-	}
312
-
313
-	/**
314
-	 * @param int $mountId
315
-	 * @param string $key
316
-	 * @param string $value
317
-	 */
318
-	public function setOption($mountId, $key, $value) {
319
-
320
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
321
-			'mount_id' => $mountId,
322
-			'key' => $key,
323
-			'value' => json_encode($value)
324
-		], ['mount_id', 'key']);
325
-		if ($count === 0) {
326
-			$builder = $this->connection->getQueryBuilder();
327
-			$query = $builder->update('external_options')
328
-				->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
329
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
330
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
331
-			$query->execute();
332
-		}
333
-	}
334
-
335
-	public function addApplicable($mountId, $type, $value) {
336
-		$this->connection->insertIfNotExist('*PREFIX*external_applicable', [
337
-			'mount_id' => $mountId,
338
-			'type' => $type,
339
-			'value' => $value
340
-		], ['mount_id', 'type', 'value']);
341
-	}
342
-
343
-	public function removeApplicable($mountId, $type, $value) {
344
-		$builder = $this->connection->getQueryBuilder();
345
-		$query = $builder->delete('external_applicable')
346
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
347
-			->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
348
-
349
-		if (is_null($value)) {
350
-			$query = $query->andWhere($builder->expr()->isNull('value'));
351
-		} else {
352
-			$query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
353
-		}
354
-
355
-		$query->execute();
356
-	}
357
-
358
-	private function getMountsFromQuery(IQueryBuilder $query) {
359
-		$result = $query->execute();
360
-		$mounts = $result->fetchAll();
361
-		$uniqueMounts = [];
362
-		foreach ($mounts as $mount) {
363
-			$id = $mount['mount_id'];
364
-			if (!isset($uniqueMounts[$id])) {
365
-				$uniqueMounts[$id] = $mount;
366
-			}
367
-		}
368
-		$uniqueMounts = array_values($uniqueMounts);
369
-
370
-		$mountIds = array_map(function ($mount) {
371
-			return $mount['mount_id'];
372
-		}, $uniqueMounts);
373
-		$mountIds = array_values(array_unique($mountIds));
374
-
375
-		$applicable = $this->getApplicableForMounts($mountIds);
376
-		$config = $this->getConfigForMounts($mountIds);
377
-		$options = $this->getOptionsForMounts($mountIds);
378
-
379
-		return array_map(function ($mount, $applicable, $config, $options) {
380
-			$mount['type'] = (int)$mount['type'];
381
-			$mount['priority'] = (int)$mount['priority'];
382
-			$mount['applicable'] = $applicable;
383
-			$mount['config'] = $config;
384
-			$mount['options'] = $options;
385
-			return $mount;
386
-		}, $uniqueMounts, $applicable, $config, $options);
387
-	}
388
-
389
-	/**
390
-	 * Get mount options from a table grouped by mount id
391
-	 *
392
-	 * @param string $table
393
-	 * @param string[] $fields
394
-	 * @param int[] $mountIds
395
-	 * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
396
-	 */
397
-	private function selectForMounts($table, array $fields, array $mountIds) {
398
-		if (count($mountIds) === 0) {
399
-			return [];
400
-		}
401
-		$builder = $this->connection->getQueryBuilder();
402
-		$fields[] = 'mount_id';
403
-		$placeHolders = array_map(function ($id) use ($builder) {
404
-			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
405
-		}, $mountIds);
406
-		$query = $builder->select($fields)
407
-			->from($table)
408
-			->where($builder->expr()->in('mount_id', $placeHolders));
409
-		$rows = $query->execute()->fetchAll();
410
-
411
-		$result = [];
412
-		foreach ($mountIds as $mountId) {
413
-			$result[$mountId] = [];
414
-		}
415
-		foreach ($rows as $row) {
416
-			if (isset($row['type'])) {
417
-				$row['type'] = (int)$row['type'];
418
-			}
419
-			$result[$row['mount_id']][] = $row;
420
-		}
421
-		return $result;
422
-	}
423
-
424
-	/**
425
-	 * @param int[] $mountIds
426
-	 * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
427
-	 */
428
-	public function getApplicableForMounts($mountIds) {
429
-		return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
430
-	}
431
-
432
-	/**
433
-	 * @param int[] $mountIds
434
-	 * @return array [$id => ['key1' => $value1, ...], ...]
435
-	 */
436
-	public function getConfigForMounts($mountIds) {
437
-		$mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
438
-		return array_map([$this, 'createKeyValueMap'], $mountConfigs);
439
-	}
440
-
441
-	/**
442
-	 * @param int[] $mountIds
443
-	 * @return array [$id => ['key1' => $value1, ...], ...]
444
-	 */
445
-	public function getOptionsForMounts($mountIds) {
446
-		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
447
-		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
448
-		return array_map(function (array $options) {
449
-			return array_map(function ($option) {
450
-				return json_decode($option);
451
-			}, $options);
452
-		}, $optionsMap);
453
-	}
454
-
455
-	/**
456
-	 * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
457
-	 * @return array ['key1' => $value1, ...]
458
-	 */
459
-	private function createKeyValueMap(array $keyValuePairs) {
460
-		$decryptedPairts = array_map(function ($pair) {
461
-			if ($pair['key'] === 'password') {
462
-				$pair['value'] = $this->decryptValue($pair['value']);
463
-			}
464
-			return $pair;
465
-		}, $keyValuePairs);
466
-		$keys = array_map(function ($pair) {
467
-			return $pair['key'];
468
-		}, $decryptedPairts);
469
-		$values = array_map(function ($pair) {
470
-			return $pair['value'];
471
-		}, $decryptedPairts);
472
-
473
-		return array_combine($keys, $values);
474
-	}
475
-
476
-	private function encryptValue($value) {
477
-		return $this->crypto->encrypt($value);
478
-	}
479
-
480
-	private function decryptValue($value) {
481
-		try {
482
-			return $this->crypto->decrypt($value);
483
-		} catch (\Exception $e) {
484
-			return $value;
485
-		}
486
-	}
35
+    const MOUNT_TYPE_ADMIN = 1;
36
+    const MOUNT_TYPE_PERSONAl = 2;
37
+
38
+    const APPLICABLE_TYPE_GLOBAL = 1;
39
+    const APPLICABLE_TYPE_GROUP = 2;
40
+    const APPLICABLE_TYPE_USER = 3;
41
+
42
+    /**
43
+     * @var IDBConnection
44
+     */
45
+    private $connection;
46
+
47
+    /**
48
+     * @var ICrypto
49
+     */
50
+    private $crypto;
51
+
52
+    /**
53
+     * DBConfigService constructor.
54
+     *
55
+     * @param IDBConnection $connection
56
+     * @param ICrypto $crypto
57
+     */
58
+    public function __construct(IDBConnection $connection, ICrypto $crypto) {
59
+        $this->connection = $connection;
60
+        $this->crypto = $crypto;
61
+    }
62
+
63
+    /**
64
+     * @param int $mountId
65
+     * @return array
66
+     */
67
+    public function getMountById($mountId) {
68
+        $builder = $this->connection->getQueryBuilder();
69
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
70
+            ->from('external_mounts', 'm')
71
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
72
+        $mounts = $this->getMountsFromQuery($query);
73
+        if (count($mounts) > 0) {
74
+            return $mounts[0];
75
+        } else {
76
+            return null;
77
+        }
78
+    }
79
+
80
+    /**
81
+     * Get all configured mounts
82
+     *
83
+     * @return array
84
+     */
85
+    public function getAllMounts() {
86
+        $builder = $this->connection->getQueryBuilder();
87
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
88
+            ->from('external_mounts');
89
+        return $this->getMountsFromQuery($query);
90
+    }
91
+
92
+    public function getMountsForUser($userId, $groupIds) {
93
+        $builder = $this->connection->getQueryBuilder();
94
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
95
+            ->from('external_mounts', 'm')
96
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
97
+            ->where($builder->expr()->orX(
98
+                $builder->expr()->andX( // global mounts
99
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GLOBAL, IQueryBuilder::PARAM_INT)),
100
+                    $builder->expr()->isNull('a.value')
101
+                ),
102
+                $builder->expr()->andX( // mounts for user
103
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_USER, IQueryBuilder::PARAM_INT)),
104
+                    $builder->expr()->eq('a.value', $builder->createNamedParameter($userId))
105
+                ),
106
+                $builder->expr()->andX( // mounts for group
107
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GROUP, IQueryBuilder::PARAM_INT)),
108
+                    $builder->expr()->in('a.value', $builder->createNamedParameter($groupIds, IQueryBuilder::PARAM_INT_ARRAY))
109
+                )
110
+            ));
111
+
112
+        return $this->getMountsFromQuery($query);
113
+    }
114
+
115
+    /**
116
+     * Get admin defined mounts
117
+     *
118
+     * @return array
119
+     */
120
+    public function getAdminMounts() {
121
+        $builder = $this->connection->getQueryBuilder();
122
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
123
+            ->from('external_mounts')
124
+            ->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
125
+        return $this->getMountsFromQuery($query);
126
+    }
127
+
128
+    protected function getForQuery(IQueryBuilder $builder, $type, $value) {
129
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
130
+            ->from('external_mounts', 'm')
131
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
132
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
133
+
134
+        if (is_null($value)) {
135
+            $query = $query->andWhere($builder->expr()->isNull('a.value'));
136
+        } else {
137
+            $query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
138
+        }
139
+
140
+        return $query;
141
+    }
142
+
143
+    /**
144
+     * Get mounts by applicable
145
+     *
146
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
147
+     * @param string|null $value user_id, group_id or null for global mounts
148
+     * @return array
149
+     */
150
+    public function getMountsFor($type, $value) {
151
+        $builder = $this->connection->getQueryBuilder();
152
+        $query = $this->getForQuery($builder, $type, $value);
153
+
154
+        return $this->getMountsFromQuery($query);
155
+    }
156
+
157
+    /**
158
+     * Get admin defined mounts by applicable
159
+     *
160
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
161
+     * @param string|null $value user_id, group_id or null for global mounts
162
+     * @return array
163
+     */
164
+    public function getAdminMountsFor($type, $value) {
165
+        $builder = $this->connection->getQueryBuilder();
166
+        $query = $this->getForQuery($builder, $type, $value);
167
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
168
+
169
+        return $this->getMountsFromQuery($query);
170
+    }
171
+
172
+    /**
173
+     * Get admin defined mounts for multiple applicable
174
+     *
175
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
176
+     * @param string[] $values user_ids or group_ids
177
+     * @return array
178
+     */
179
+    public function getAdminMountsForMultiple($type, array $values) {
180
+        $builder = $this->connection->getQueryBuilder();
181
+        $params = array_map(function ($value) use ($builder) {
182
+            return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
183
+        }, $values);
184
+
185
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
186
+            ->from('external_mounts', 'm')
187
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
188
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
189
+            ->andWhere($builder->expr()->in('a.value', $params));
190
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
191
+
192
+        return $this->getMountsFromQuery($query);
193
+    }
194
+
195
+    /**
196
+     * Get user defined mounts by applicable
197
+     *
198
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
199
+     * @param string|null $value user_id, group_id or null for global mounts
200
+     * @return array
201
+     */
202
+    public function getUserMountsFor($type, $value) {
203
+        $builder = $this->connection->getQueryBuilder();
204
+        $query = $this->getForQuery($builder, $type, $value);
205
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
206
+
207
+        return $this->getMountsFromQuery($query);
208
+    }
209
+
210
+    /**
211
+     * Add a mount to the database
212
+     *
213
+     * @param string $mountPoint
214
+     * @param string $storageBackend
215
+     * @param string $authBackend
216
+     * @param int $priority
217
+     * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
218
+     * @return int the id of the new mount
219
+     */
220
+    public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
221
+        if (!$priority) {
222
+            $priority = 100;
223
+        }
224
+        $builder = $this->connection->getQueryBuilder();
225
+        $query = $builder->insert('external_mounts')
226
+            ->values([
227
+                'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
228
+                'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
229
+                'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
230
+                'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
231
+                'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
232
+            ]);
233
+        $query->execute();
234
+        return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
235
+    }
236
+
237
+    /**
238
+     * Remove a mount from the database
239
+     *
240
+     * @param int $mountId
241
+     */
242
+    public function removeMount($mountId) {
243
+        $builder = $this->connection->getQueryBuilder();
244
+        $query = $builder->delete('external_mounts')
245
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
246
+        $query->execute();
247
+
248
+        $query = $builder->delete('external_applicable')
249
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
250
+        $query->execute();
251
+
252
+        $query = $builder->delete('external_config')
253
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
254
+        $query->execute();
255
+
256
+        $query = $builder->delete('external_options')
257
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
258
+        $query->execute();
259
+    }
260
+
261
+    /**
262
+     * @param int $mountId
263
+     * @param string $newMountPoint
264
+     */
265
+    public function setMountPoint($mountId, $newMountPoint) {
266
+        $builder = $this->connection->getQueryBuilder();
267
+
268
+        $query = $builder->update('external_mounts')
269
+            ->set('mount_point', $builder->createNamedParameter($newMountPoint))
270
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
271
+
272
+        $query->execute();
273
+    }
274
+
275
+    /**
276
+     * @param int $mountId
277
+     * @param string $newAuthBackend
278
+     */
279
+    public function setAuthBackend($mountId, $newAuthBackend) {
280
+        $builder = $this->connection->getQueryBuilder();
281
+
282
+        $query = $builder->update('external_mounts')
283
+            ->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
284
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
285
+
286
+        $query->execute();
287
+    }
288
+
289
+    /**
290
+     * @param int $mountId
291
+     * @param string $key
292
+     * @param string $value
293
+     */
294
+    public function setConfig($mountId, $key, $value) {
295
+        if ($key === 'password') {
296
+            $value = $this->encryptValue($value);
297
+        }
298
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
299
+            'mount_id' => $mountId,
300
+            'key' => $key,
301
+            'value' => $value
302
+        ], ['mount_id', 'key']);
303
+        if ($count === 0) {
304
+            $builder = $this->connection->getQueryBuilder();
305
+            $query = $builder->update('external_config')
306
+                ->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
307
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
308
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
309
+            $query->execute();
310
+        }
311
+    }
312
+
313
+    /**
314
+     * @param int $mountId
315
+     * @param string $key
316
+     * @param string $value
317
+     */
318
+    public function setOption($mountId, $key, $value) {
319
+
320
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
321
+            'mount_id' => $mountId,
322
+            'key' => $key,
323
+            'value' => json_encode($value)
324
+        ], ['mount_id', 'key']);
325
+        if ($count === 0) {
326
+            $builder = $this->connection->getQueryBuilder();
327
+            $query = $builder->update('external_options')
328
+                ->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
329
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
330
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
331
+            $query->execute();
332
+        }
333
+    }
334
+
335
+    public function addApplicable($mountId, $type, $value) {
336
+        $this->connection->insertIfNotExist('*PREFIX*external_applicable', [
337
+            'mount_id' => $mountId,
338
+            'type' => $type,
339
+            'value' => $value
340
+        ], ['mount_id', 'type', 'value']);
341
+    }
342
+
343
+    public function removeApplicable($mountId, $type, $value) {
344
+        $builder = $this->connection->getQueryBuilder();
345
+        $query = $builder->delete('external_applicable')
346
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
347
+            ->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
348
+
349
+        if (is_null($value)) {
350
+            $query = $query->andWhere($builder->expr()->isNull('value'));
351
+        } else {
352
+            $query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
353
+        }
354
+
355
+        $query->execute();
356
+    }
357
+
358
+    private function getMountsFromQuery(IQueryBuilder $query) {
359
+        $result = $query->execute();
360
+        $mounts = $result->fetchAll();
361
+        $uniqueMounts = [];
362
+        foreach ($mounts as $mount) {
363
+            $id = $mount['mount_id'];
364
+            if (!isset($uniqueMounts[$id])) {
365
+                $uniqueMounts[$id] = $mount;
366
+            }
367
+        }
368
+        $uniqueMounts = array_values($uniqueMounts);
369
+
370
+        $mountIds = array_map(function ($mount) {
371
+            return $mount['mount_id'];
372
+        }, $uniqueMounts);
373
+        $mountIds = array_values(array_unique($mountIds));
374
+
375
+        $applicable = $this->getApplicableForMounts($mountIds);
376
+        $config = $this->getConfigForMounts($mountIds);
377
+        $options = $this->getOptionsForMounts($mountIds);
378
+
379
+        return array_map(function ($mount, $applicable, $config, $options) {
380
+            $mount['type'] = (int)$mount['type'];
381
+            $mount['priority'] = (int)$mount['priority'];
382
+            $mount['applicable'] = $applicable;
383
+            $mount['config'] = $config;
384
+            $mount['options'] = $options;
385
+            return $mount;
386
+        }, $uniqueMounts, $applicable, $config, $options);
387
+    }
388
+
389
+    /**
390
+     * Get mount options from a table grouped by mount id
391
+     *
392
+     * @param string $table
393
+     * @param string[] $fields
394
+     * @param int[] $mountIds
395
+     * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
396
+     */
397
+    private function selectForMounts($table, array $fields, array $mountIds) {
398
+        if (count($mountIds) === 0) {
399
+            return [];
400
+        }
401
+        $builder = $this->connection->getQueryBuilder();
402
+        $fields[] = 'mount_id';
403
+        $placeHolders = array_map(function ($id) use ($builder) {
404
+            return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
405
+        }, $mountIds);
406
+        $query = $builder->select($fields)
407
+            ->from($table)
408
+            ->where($builder->expr()->in('mount_id', $placeHolders));
409
+        $rows = $query->execute()->fetchAll();
410
+
411
+        $result = [];
412
+        foreach ($mountIds as $mountId) {
413
+            $result[$mountId] = [];
414
+        }
415
+        foreach ($rows as $row) {
416
+            if (isset($row['type'])) {
417
+                $row['type'] = (int)$row['type'];
418
+            }
419
+            $result[$row['mount_id']][] = $row;
420
+        }
421
+        return $result;
422
+    }
423
+
424
+    /**
425
+     * @param int[] $mountIds
426
+     * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
427
+     */
428
+    public function getApplicableForMounts($mountIds) {
429
+        return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
430
+    }
431
+
432
+    /**
433
+     * @param int[] $mountIds
434
+     * @return array [$id => ['key1' => $value1, ...], ...]
435
+     */
436
+    public function getConfigForMounts($mountIds) {
437
+        $mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
438
+        return array_map([$this, 'createKeyValueMap'], $mountConfigs);
439
+    }
440
+
441
+    /**
442
+     * @param int[] $mountIds
443
+     * @return array [$id => ['key1' => $value1, ...], ...]
444
+     */
445
+    public function getOptionsForMounts($mountIds) {
446
+        $mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
447
+        $optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
448
+        return array_map(function (array $options) {
449
+            return array_map(function ($option) {
450
+                return json_decode($option);
451
+            }, $options);
452
+        }, $optionsMap);
453
+    }
454
+
455
+    /**
456
+     * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
457
+     * @return array ['key1' => $value1, ...]
458
+     */
459
+    private function createKeyValueMap(array $keyValuePairs) {
460
+        $decryptedPairts = array_map(function ($pair) {
461
+            if ($pair['key'] === 'password') {
462
+                $pair['value'] = $this->decryptValue($pair['value']);
463
+            }
464
+            return $pair;
465
+        }, $keyValuePairs);
466
+        $keys = array_map(function ($pair) {
467
+            return $pair['key'];
468
+        }, $decryptedPairts);
469
+        $values = array_map(function ($pair) {
470
+            return $pair['value'];
471
+        }, $decryptedPairts);
472
+
473
+        return array_combine($keys, $values);
474
+    }
475
+
476
+    private function encryptValue($value) {
477
+        return $this->crypto->encrypt($value);
478
+    }
479
+
480
+    private function decryptValue($value) {
481
+        try {
482
+            return $this->crypto->decrypt($value);
483
+        } catch (\Exception $e) {
484
+            return $value;
485
+        }
486
+    }
487 487
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 	 */
179 179
 	public function getAdminMountsForMultiple($type, array $values) {
180 180
 		$builder = $this->connection->getQueryBuilder();
181
-		$params = array_map(function ($value) use ($builder) {
181
+		$params = array_map(function($value) use ($builder) {
182 182
 			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
183 183
 		}, $values);
184 184
 
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
232 232
 			]);
233 233
 		$query->execute();
234
-		return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
234
+		return (int) $this->connection->lastInsertId('*PREFIX*external_mounts');
235 235
 	}
236 236
 
237 237
 	/**
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 		}
368 368
 		$uniqueMounts = array_values($uniqueMounts);
369 369
 
370
-		$mountIds = array_map(function ($mount) {
370
+		$mountIds = array_map(function($mount) {
371 371
 			return $mount['mount_id'];
372 372
 		}, $uniqueMounts);
373 373
 		$mountIds = array_values(array_unique($mountIds));
@@ -376,9 +376,9 @@  discard block
 block discarded – undo
376 376
 		$config = $this->getConfigForMounts($mountIds);
377 377
 		$options = $this->getOptionsForMounts($mountIds);
378 378
 
379
-		return array_map(function ($mount, $applicable, $config, $options) {
380
-			$mount['type'] = (int)$mount['type'];
381
-			$mount['priority'] = (int)$mount['priority'];
379
+		return array_map(function($mount, $applicable, $config, $options) {
380
+			$mount['type'] = (int) $mount['type'];
381
+			$mount['priority'] = (int) $mount['priority'];
382 382
 			$mount['applicable'] = $applicable;
383 383
 			$mount['config'] = $config;
384 384
 			$mount['options'] = $options;
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
 		}
401 401
 		$builder = $this->connection->getQueryBuilder();
402 402
 		$fields[] = 'mount_id';
403
-		$placeHolders = array_map(function ($id) use ($builder) {
403
+		$placeHolders = array_map(function($id) use ($builder) {
404 404
 			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
405 405
 		}, $mountIds);
406 406
 		$query = $builder->select($fields)
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
 		}
415 415
 		foreach ($rows as $row) {
416 416
 			if (isset($row['type'])) {
417
-				$row['type'] = (int)$row['type'];
417
+				$row['type'] = (int) $row['type'];
418 418
 			}
419 419
 			$result[$row['mount_id']][] = $row;
420 420
 		}
@@ -445,8 +445,8 @@  discard block
 block discarded – undo
445 445
 	public function getOptionsForMounts($mountIds) {
446 446
 		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
447 447
 		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
448
-		return array_map(function (array $options) {
449
-			return array_map(function ($option) {
448
+		return array_map(function(array $options) {
449
+			return array_map(function($option) {
450 450
 				return json_decode($option);
451 451
 			}, $options);
452 452
 		}, $optionsMap);
@@ -457,16 +457,16 @@  discard block
 block discarded – undo
457 457
 	 * @return array ['key1' => $value1, ...]
458 458
 	 */
459 459
 	private function createKeyValueMap(array $keyValuePairs) {
460
-		$decryptedPairts = array_map(function ($pair) {
460
+		$decryptedPairts = array_map(function($pair) {
461 461
 			if ($pair['key'] === 'password') {
462 462
 				$pair['value'] = $this->decryptValue($pair['value']);
463 463
 			}
464 464
 			return $pair;
465 465
 		}, $keyValuePairs);
466
-		$keys = array_map(function ($pair) {
466
+		$keys = array_map(function($pair) {
467 467
 			return $pair['key'];
468 468
 		}, $decryptedPairts);
469
-		$values = array_map(function ($pair) {
469
+		$values = array_map(function($pair) {
470 470
 			return $pair['value'];
471 471
 		}, $decryptedPairts);
472 472
 
Please login to merge, or discard this patch.
apps/federation/lib/AppInfo/Application.php 3 patches
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -24,16 +24,13 @@
 block discarded – undo
24 24
 
25 25
 namespace OCA\Federation\AppInfo;
26 26
 
27
-use OCA\Federation\API\OCSAuthAPI;
28 27
 use OCA\Federation\Controller\SettingsController;
29 28
 use OCA\Federation\DAV\FedAuth;
30 29
 use OCA\Federation\DbHandler;
31 30
 use OCA\Federation\Hooks;
32 31
 use OCA\Federation\Middleware\AddServerMiddleware;
33 32
 use OCA\Federation\SyncFederationAddressBooks;
34
-use OCA\Federation\SyncJob;
35 33
 use OCA\Federation\TrustedServers;
36
-use OCP\API;
37 34
 use OCP\App;
38 35
 use OCP\AppFramework\IAppContainer;
39 36
 use OCP\SabrePluginEvent;
Please login to merge, or discard this patch.
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -42,100 +42,100 @@
 block discarded – undo
42 42
 
43 43
 class Application extends \OCP\AppFramework\App {
44 44
 
45
-	/**
46
-	 * @param array $urlParams
47
-	 */
48
-	public function __construct($urlParams = array()) {
49
-		parent::__construct('federation', $urlParams);
50
-		$this->registerService();
51
-		$this->registerMiddleware();
52
-	}
53
-
54
-	private function registerService() {
55
-		$container = $this->getContainer();
56
-
57
-		$container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
-			return new AddServerMiddleware(
59
-				$c->getAppName(),
60
-				\OC::$server->getL10N($c->getAppName()),
61
-				\OC::$server->getLogger()
62
-			);
63
-		});
64
-
65
-		$container->registerService('DbHandler', function(IAppContainer $c) {
66
-			return new DbHandler(
67
-				\OC::$server->getDatabaseConnection(),
68
-				\OC::$server->getL10N($c->getAppName())
69
-			);
70
-		});
71
-
72
-		$container->registerService('TrustedServers', function(IAppContainer $c) {
73
-			$server = $c->getServer();
74
-			return new TrustedServers(
75
-				$c->query('DbHandler'),
76
-				$server->getHTTPClientService(),
77
-				$server->getLogger(),
78
-				$server->getJobList(),
79
-				$server->getSecureRandom(),
80
-				$server->getConfig(),
81
-				$server->getEventDispatcher()
82
-			);
83
-		});
84
-
85
-		$container->registerService('SettingsController', function (IAppContainer $c) {
86
-			$server = $c->getServer();
87
-			return new SettingsController(
88
-				$c->getAppName(),
89
-				$server->getRequest(),
90
-				$server->getL10N($c->getAppName()),
91
-				$c->query('TrustedServers')
92
-			);
93
-		});
94
-
95
-	}
96
-
97
-	private function registerMiddleware() {
98
-		$container = $this->getContainer();
99
-		$container->registerMiddleware('addServerMiddleware');
100
-	}
101
-
102
-	/**
103
-	 * listen to federated_share_added hooks to auto-add new servers to the
104
-	 * list of trusted servers.
105
-	 */
106
-	public function registerHooks() {
107
-
108
-		$container = $this->getContainer();
109
-		$hooksManager = new Hooks($container->query('TrustedServers'));
110
-
111
-		Util::connectHook(
112
-				'OCP\Share',
113
-				'federated_share_added',
114
-				$hooksManager,
115
-				'addServerHook'
116
-		);
117
-
118
-		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
119
-		$dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
120
-			if ($event instanceof SabrePluginEvent) {
121
-				$authPlugin = $event->getServer()->getPlugin('auth');
122
-				if ($authPlugin instanceof Plugin) {
123
-					$h = new DbHandler($container->getServer()->getDatabaseConnection(),
124
-							$container->getServer()->getL10N('federation')
125
-					);
126
-					$authPlugin->addBackend(new FedAuth($h));
127
-				}
128
-			}
129
-		});
130
-	}
131
-
132
-	/**
133
-	 * @return SyncFederationAddressBooks
134
-	 */
135
-	public function getSyncService() {
136
-		$syncService = \OC::$server->query('CardDAVSyncService');
137
-		$dbHandler = $this->getContainer()->query('DbHandler');
138
-		return new SyncFederationAddressBooks($dbHandler, $syncService);
139
-	}
45
+    /**
46
+     * @param array $urlParams
47
+     */
48
+    public function __construct($urlParams = array()) {
49
+        parent::__construct('federation', $urlParams);
50
+        $this->registerService();
51
+        $this->registerMiddleware();
52
+    }
53
+
54
+    private function registerService() {
55
+        $container = $this->getContainer();
56
+
57
+        $container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
+            return new AddServerMiddleware(
59
+                $c->getAppName(),
60
+                \OC::$server->getL10N($c->getAppName()),
61
+                \OC::$server->getLogger()
62
+            );
63
+        });
64
+
65
+        $container->registerService('DbHandler', function(IAppContainer $c) {
66
+            return new DbHandler(
67
+                \OC::$server->getDatabaseConnection(),
68
+                \OC::$server->getL10N($c->getAppName())
69
+            );
70
+        });
71
+
72
+        $container->registerService('TrustedServers', function(IAppContainer $c) {
73
+            $server = $c->getServer();
74
+            return new TrustedServers(
75
+                $c->query('DbHandler'),
76
+                $server->getHTTPClientService(),
77
+                $server->getLogger(),
78
+                $server->getJobList(),
79
+                $server->getSecureRandom(),
80
+                $server->getConfig(),
81
+                $server->getEventDispatcher()
82
+            );
83
+        });
84
+
85
+        $container->registerService('SettingsController', function (IAppContainer $c) {
86
+            $server = $c->getServer();
87
+            return new SettingsController(
88
+                $c->getAppName(),
89
+                $server->getRequest(),
90
+                $server->getL10N($c->getAppName()),
91
+                $c->query('TrustedServers')
92
+            );
93
+        });
94
+
95
+    }
96
+
97
+    private function registerMiddleware() {
98
+        $container = $this->getContainer();
99
+        $container->registerMiddleware('addServerMiddleware');
100
+    }
101
+
102
+    /**
103
+     * listen to federated_share_added hooks to auto-add new servers to the
104
+     * list of trusted servers.
105
+     */
106
+    public function registerHooks() {
107
+
108
+        $container = $this->getContainer();
109
+        $hooksManager = new Hooks($container->query('TrustedServers'));
110
+
111
+        Util::connectHook(
112
+                'OCP\Share',
113
+                'federated_share_added',
114
+                $hooksManager,
115
+                'addServerHook'
116
+        );
117
+
118
+        $dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
119
+        $dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
120
+            if ($event instanceof SabrePluginEvent) {
121
+                $authPlugin = $event->getServer()->getPlugin('auth');
122
+                if ($authPlugin instanceof Plugin) {
123
+                    $h = new DbHandler($container->getServer()->getDatabaseConnection(),
124
+                            $container->getServer()->getL10N('federation')
125
+                    );
126
+                    $authPlugin->addBackend(new FedAuth($h));
127
+                }
128
+            }
129
+        });
130
+    }
131
+
132
+    /**
133
+     * @return SyncFederationAddressBooks
134
+     */
135
+    public function getSyncService() {
136
+        $syncService = \OC::$server->query('CardDAVSyncService');
137
+        $dbHandler = $this->getContainer()->query('DbHandler');
138
+        return new SyncFederationAddressBooks($dbHandler, $syncService);
139
+    }
140 140
 
141 141
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@
 block discarded – undo
82 82
 			);
83 83
 		});
84 84
 
85
-		$container->registerService('SettingsController', function (IAppContainer $c) {
85
+		$container->registerService('SettingsController', function(IAppContainer $c) {
86 86
 			$server = $c->getServer();
87 87
 			return new SettingsController(
88 88
 				$c->getAppName(),
Please login to merge, or discard this patch.
lib/private/AppFramework/OCS/BaseResponse.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@
 block discarded – undo
24 24
 	/**
25 25
 	 * BaseResponse constructor.
26 26
 	 *
27
-	 * @param DataResponse|null $dataResponse
27
+	 * @param DataResponse $dataResponse
28 28
 	 * @param string $format
29 29
 	 * @param string|null $statusMessage
30 30
 	 * @param int|null $itemsCount
Please login to merge, or discard this patch.
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -27,70 +27,70 @@
 block discarded – undo
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29 29
 abstract class BaseResponse extends Response   {
30
-	/** @var array */
31
-	protected $data;
30
+    /** @var array */
31
+    protected $data;
32 32
 
33
-	/** @var string */
34
-	protected $format;
33
+    /** @var string */
34
+    protected $format;
35 35
 
36
-	/** @var string */
37
-	protected $statusMessage;
36
+    /** @var string */
37
+    protected $statusMessage;
38 38
 
39
-	/** @var int */
40
-	protected $itemsCount;
39
+    /** @var int */
40
+    protected $itemsCount;
41 41
 
42
-	/** @var int */
43
-	protected $itemsPerPage;
42
+    /** @var int */
43
+    protected $itemsPerPage;
44 44
 
45
-	/**
46
-	 * BaseResponse constructor.
47
-	 *
48
-	 * @param DataResponse|null $dataResponse
49
-	 * @param string $format
50
-	 * @param string|null $statusMessage
51
-	 * @param int|null $itemsCount
52
-	 * @param int|null $itemsPerPage
53
-	 */
54
-	public function __construct(DataResponse $dataResponse,
55
-								$format = 'xml',
56
-								$statusMessage = null,
57
-								$itemsCount = null,
58
-								$itemsPerPage = null) {
59
-		$this->format = $format;
60
-		$this->statusMessage = $statusMessage;
61
-		$this->itemsCount = $itemsCount;
62
-		$this->itemsPerPage = $itemsPerPage;
45
+    /**
46
+     * BaseResponse constructor.
47
+     *
48
+     * @param DataResponse|null $dataResponse
49
+     * @param string $format
50
+     * @param string|null $statusMessage
51
+     * @param int|null $itemsCount
52
+     * @param int|null $itemsPerPage
53
+     */
54
+    public function __construct(DataResponse $dataResponse,
55
+                                $format = 'xml',
56
+                                $statusMessage = null,
57
+                                $itemsCount = null,
58
+                                $itemsPerPage = null) {
59
+        $this->format = $format;
60
+        $this->statusMessage = $statusMessage;
61
+        $this->itemsCount = $itemsCount;
62
+        $this->itemsPerPage = $itemsPerPage;
63 63
 
64
-		$this->data = $dataResponse->getData();
64
+        $this->data = $dataResponse->getData();
65 65
 
66
-		$this->setHeaders($dataResponse->getHeaders());
67
-		$this->setStatus($dataResponse->getStatus());
68
-		$this->setETag($dataResponse->getETag());
69
-		$this->setLastModified($dataResponse->getLastModified());
70
-		$this->setCookies($dataResponse->getCookies());
71
-		$this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
66
+        $this->setHeaders($dataResponse->getHeaders());
67
+        $this->setStatus($dataResponse->getStatus());
68
+        $this->setETag($dataResponse->getETag());
69
+        $this->setLastModified($dataResponse->getLastModified());
70
+        $this->setCookies($dataResponse->getCookies());
71
+        $this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
72 72
 
73
-		if ($format === 'json') {
74
-			$this->addHeader(
75
-				'Content-Type', 'application/json; charset=utf-8'
76
-			);
77
-		} else {
78
-			$this->addHeader(
79
-				'Content-Type', 'application/xml; charset=utf-8'
80
-			);
81
-		}
82
-	}
73
+        if ($format === 'json') {
74
+            $this->addHeader(
75
+                'Content-Type', 'application/json; charset=utf-8'
76
+            );
77
+        } else {
78
+            $this->addHeader(
79
+                'Content-Type', 'application/xml; charset=utf-8'
80
+            );
81
+        }
82
+    }
83 83
 
84
-	/**
85
-	 * @param string[] $meta
86
-	 * @return string
87
-	 */
88
-	protected function renderResult($meta) {
89
-		// TODO rewrite functions
90
-		return \OC_API::renderResult($this->format, $meta, $this->data);
91
-	}
84
+    /**
85
+     * @param string[] $meta
86
+     * @return string
87
+     */
88
+    protected function renderResult($meta) {
89
+        // TODO rewrite functions
90
+        return \OC_API::renderResult($this->format, $meta, $this->data);
91
+    }
92 92
 
93
-	public function getOCSStatus() {
94
-		return parent::getStatus();
95
-	}
93
+    public function getOCSStatus() {
94
+        return parent::getStatus();
95
+    }
96 96
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@
 block discarded – undo
26 26
 use OCP\AppFramework\Http\EmptyContentSecurityPolicy;
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29
-abstract class BaseResponse extends Response   {
29
+abstract class BaseResponse extends Response {
30 30
 	/** @var array */
31 31
 	protected $data;
32 32
 
Please login to merge, or discard this patch.
lib/private/Server.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1143,7 +1143,7 @@  discard block
 block discarded – undo
1143 1143
 	 * Get the certificate manager for the user
1144 1144
 	 *
1145 1145
 	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1146
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1146
+	 * @return null|CertificateManager | null if $uid is null and no user is logged in
1147 1147
 	 */
1148 1148
 	public function getCertificateManager($userId = '') {
1149 1149
 		if ($userId === '') {
@@ -1464,6 +1464,7 @@  discard block
 block discarded – undo
1464 1464
 	}
1465 1465
 
1466 1466
 	/**
1467
+	 * @param string $app
1467 1468
 	 * @return \OCP\Files\IAppData
1468 1469
 	 */
1469 1470
 	public function getAppDataDir($app) {
Please login to merge, or discard this patch.
Indentation   +1470 added lines, -1470 removed lines patch added patch discarded remove patch
@@ -108,1479 +108,1479 @@
 block discarded – undo
108 108
  * TODO: hookup all manager classes
109 109
  */
110 110
 class Server extends ServerContainer implements IServerContainer {
111
-	/** @var string */
112
-	private $webRoot;
113
-
114
-	/**
115
-	 * @param string $webRoot
116
-	 * @param \OC\Config $config
117
-	 */
118
-	public function __construct($webRoot, \OC\Config $config) {
119
-		parent::__construct();
120
-		$this->webRoot = $webRoot;
121
-
122
-		$this->registerService('ContactsManager', function ($c) {
123
-			return new ContactsManager();
124
-		});
125
-
126
-		$this->registerService('PreviewManager', function (Server $c) {
127
-			return new PreviewManager(
128
-				$c->getConfig(),
129
-				$c->getRootFolder(),
130
-				$c->getAppDataDir('preview'),
131
-				$c->getEventDispatcher(),
132
-				$c->getSession()->get('user_id')
133
-			);
134
-		});
135
-
136
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
137
-			return new \OC\Preview\Watcher(
138
-				$c->getAppDataDir('preview')
139
-			);
140
-		});
141
-
142
-		$this->registerService('EncryptionManager', function (Server $c) {
143
-			$view = new View();
144
-			$util = new Encryption\Util(
145
-				$view,
146
-				$c->getUserManager(),
147
-				$c->getGroupManager(),
148
-				$c->getConfig()
149
-			);
150
-			return new Encryption\Manager(
151
-				$c->getConfig(),
152
-				$c->getLogger(),
153
-				$c->getL10N('core'),
154
-				new View(),
155
-				$util,
156
-				new ArrayCache()
157
-			);
158
-		});
159
-
160
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
161
-			$util = new Encryption\Util(
162
-				new View(),
163
-				$c->getUserManager(),
164
-				$c->getGroupManager(),
165
-				$c->getConfig()
166
-			);
167
-			return new Encryption\File($util);
168
-		});
169
-
170
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
171
-			$view = new View();
172
-			$util = new Encryption\Util(
173
-				$view,
174
-				$c->getUserManager(),
175
-				$c->getGroupManager(),
176
-				$c->getConfig()
177
-			);
178
-
179
-			return new Encryption\Keys\Storage($view, $util);
180
-		});
181
-		$this->registerService('TagMapper', function (Server $c) {
182
-			return new TagMapper($c->getDatabaseConnection());
183
-		});
184
-		$this->registerService('TagManager', function (Server $c) {
185
-			$tagMapper = $c->query('TagMapper');
186
-			return new TagManager($tagMapper, $c->getUserSession());
187
-		});
188
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
189
-			$config = $c->getConfig();
190
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
191
-			/** @var \OC\SystemTag\ManagerFactory $factory */
192
-			$factory = new $factoryClass($this);
193
-			return $factory;
194
-		});
195
-		$this->registerService('SystemTagManager', function (Server $c) {
196
-			return $c->query('SystemTagManagerFactory')->getManager();
197
-		});
198
-		$this->registerService('SystemTagObjectMapper', function (Server $c) {
199
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
200
-		});
201
-		$this->registerService('RootFolder', function (Server $c) {
202
-			$manager = \OC\Files\Filesystem::getMountManager(null);
203
-			$view = new View();
204
-			$root = new Root(
205
-				$manager,
206
-				$view,
207
-				null,
208
-				$c->getUserMountCache(),
209
-				$this->getLogger(),
210
-				$this->getUserManager()
211
-			);
212
-			$connector = new HookConnector($root, $view);
213
-			$connector->viewToNode();
214
-
215
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
216
-			$previewConnector->connectWatcher();
217
-
218
-			return $root;
219
-		});
220
-		$this->registerService('LazyRootFolder', function(Server $c) {
221
-			return new LazyRoot(function() use ($c) {
222
-				return $c->query('RootFolder');
223
-			});
224
-		});
225
-		$this->registerService('UserManager', function (Server $c) {
226
-			$config = $c->getConfig();
227
-			return new \OC\User\Manager($config);
228
-		});
229
-		$this->registerService('GroupManager', function (Server $c) {
230
-			$groupManager = new \OC\Group\Manager($this->getUserManager());
231
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
232
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
233
-			});
234
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
235
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
236
-			});
237
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
238
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
239
-			});
240
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
241
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
242
-			});
243
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
244
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
245
-			});
246
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
247
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
248
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
249
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
250
-			});
251
-			return $groupManager;
252
-		});
253
-		$this->registerService(Store::class, function(Server $c) {
254
-			$session = $c->getSession();
255
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
256
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
257
-			} else {
258
-				$tokenProvider = null;
259
-			}
260
-			$logger = $c->getLogger();
261
-			return new Store($session, $logger, $tokenProvider);
262
-		});
263
-		$this->registerAlias(IStore::class, Store::class);
264
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
265
-			$dbConnection = $c->getDatabaseConnection();
266
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
267
-		});
268
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
269
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
270
-			$crypto = $c->getCrypto();
271
-			$config = $c->getConfig();
272
-			$logger = $c->getLogger();
273
-			$timeFactory = new TimeFactory();
274
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
275
-		});
276
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
277
-		$this->registerService('UserSession', function (Server $c) {
278
-			$manager = $c->getUserManager();
279
-			$session = new \OC\Session\Memory('');
280
-			$timeFactory = new TimeFactory();
281
-			// Token providers might require a working database. This code
282
-			// might however be called when ownCloud is not yet setup.
283
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
284
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
285
-			} else {
286
-				$defaultTokenProvider = null;
287
-			}
288
-
289
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom());
290
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
291
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
292
-			});
293
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
294
-				/** @var $user \OC\User\User */
295
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
296
-			});
297
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
298
-				/** @var $user \OC\User\User */
299
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
300
-			});
301
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
302
-				/** @var $user \OC\User\User */
303
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
304
-			});
305
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
306
-				/** @var $user \OC\User\User */
307
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
308
-			});
309
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
310
-				/** @var $user \OC\User\User */
311
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
312
-			});
313
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
314
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
315
-			});
316
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
317
-				/** @var $user \OC\User\User */
318
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
319
-			});
320
-			$userSession->listen('\OC\User', 'logout', function () {
321
-				\OC_Hook::emit('OC_User', 'logout', array());
322
-			});
323
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
324
-				/** @var $user \OC\User\User */
325
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
326
-			});
327
-			return $userSession;
328
-		});
329
-
330
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
331
-			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
332
-		});
333
-
334
-		$this->registerService('NavigationManager', function (Server $c) {
335
-			return new \OC\NavigationManager($c->getAppManager(),
336
-				$c->getURLGenerator(),
337
-				$c->getL10NFactory(),
338
-				$c->getUserSession(),
339
-				$c->getGroupManager());
340
-		});
341
-		$this->registerService('AllConfig', function (Server $c) {
342
-			return new \OC\AllConfig(
343
-				$c->getSystemConfig()
344
-			);
345
-		});
346
-		$this->registerService('SystemConfig', function ($c) use ($config) {
347
-			return new \OC\SystemConfig($config);
348
-		});
349
-		$this->registerService('AppConfig', function (Server $c) {
350
-			return new \OC\AppConfig($c->getDatabaseConnection());
351
-		});
352
-		$this->registerService('L10NFactory', function (Server $c) {
353
-			return new \OC\L10N\Factory(
354
-				$c->getConfig(),
355
-				$c->getRequest(),
356
-				$c->getUserSession(),
357
-				\OC::$SERVERROOT
358
-			);
359
-		});
360
-		$this->registerService('URLGenerator', function (Server $c) {
361
-			$config = $c->getConfig();
362
-			$cacheFactory = $c->getMemCacheFactory();
363
-			return new \OC\URLGenerator(
364
-				$config,
365
-				$cacheFactory
366
-			);
367
-		});
368
-		$this->registerService('AppHelper', function ($c) {
369
-			return new \OC\AppHelper();
370
-		});
371
-		$this->registerService('AppFetcher', function ($c) {
372
-			return new AppFetcher(
373
-				$this->getAppDataDir('appstore'),
374
-				$this->getHTTPClientService(),
375
-				$this->query(TimeFactory::class),
376
-				$this->getConfig()
377
-			);
378
-		});
379
-		$this->registerService('CategoryFetcher', function ($c) {
380
-			return new CategoryFetcher(
381
-				$this->getAppDataDir('appstore'),
382
-				$this->getHTTPClientService(),
383
-				$this->query(TimeFactory::class),
384
-				$this->getConfig()
385
-			);
386
-		});
387
-		$this->registerService('UserCache', function ($c) {
388
-			return new Cache\File();
389
-		});
390
-		$this->registerService('MemCacheFactory', function (Server $c) {
391
-			$config = $c->getConfig();
392
-
393
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
394
-				$v = \OC_App::getAppVersions();
395
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
396
-				$version = implode(',', $v);
397
-				$instanceId = \OC_Util::getInstanceId();
398
-				$path = \OC::$SERVERROOT;
399
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
400
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
401
-					$config->getSystemValue('memcache.local', null),
402
-					$config->getSystemValue('memcache.distributed', null),
403
-					$config->getSystemValue('memcache.locking', null)
404
-				);
405
-			}
406
-
407
-			return new \OC\Memcache\Factory('', $c->getLogger(),
408
-				'\\OC\\Memcache\\ArrayCache',
409
-				'\\OC\\Memcache\\ArrayCache',
410
-				'\\OC\\Memcache\\ArrayCache'
411
-			);
412
-		});
413
-		$this->registerService('RedisFactory', function (Server $c) {
414
-			$systemConfig = $c->getSystemConfig();
415
-			return new RedisFactory($systemConfig);
416
-		});
417
-		$this->registerService('ActivityManager', function (Server $c) {
418
-			return new \OC\Activity\Manager(
419
-				$c->getRequest(),
420
-				$c->getUserSession(),
421
-				$c->getConfig(),
422
-				$c->query(IValidator::class)
423
-			);
424
-		});
425
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
426
-			return new \OC\Activity\EventMerger(
427
-				$c->getL10N('lib')
428
-			);
429
-		});
430
-		$this->registerAlias(IValidator::class, Validator::class);
431
-		$this->registerService('AvatarManager', function (Server $c) {
432
-			return new AvatarManager(
433
-				$c->getUserManager(),
434
-				$c->getAppDataDir('avatar'),
435
-				$c->getL10N('lib'),
436
-				$c->getLogger(),
437
-				$c->getConfig()
438
-			);
439
-		});
440
-		$this->registerService('Logger', function (Server $c) {
441
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
442
-			$logger = Log::getLogClass($logType);
443
-			call_user_func(array($logger, 'init'));
444
-
445
-			return new Log($logger);
446
-		});
447
-		$this->registerService('JobList', function (Server $c) {
448
-			$config = $c->getConfig();
449
-			return new \OC\BackgroundJob\JobList(
450
-				$c->getDatabaseConnection(),
451
-				$config,
452
-				new TimeFactory()
453
-			);
454
-		});
455
-		$this->registerService('Router', function (Server $c) {
456
-			$cacheFactory = $c->getMemCacheFactory();
457
-			$logger = $c->getLogger();
458
-			if ($cacheFactory->isAvailable()) {
459
-				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
460
-			} else {
461
-				$router = new \OC\Route\Router($logger);
462
-			}
463
-			return $router;
464
-		});
465
-		$this->registerService('Search', function ($c) {
466
-			return new Search();
467
-		});
468
-		$this->registerService('SecureRandom', function ($c) {
469
-			return new SecureRandom();
470
-		});
471
-		$this->registerService('Crypto', function (Server $c) {
472
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
473
-		});
474
-		$this->registerService('Hasher', function (Server $c) {
475
-			return new Hasher($c->getConfig());
476
-		});
477
-		$this->registerService('CredentialsManager', function (Server $c) {
478
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
479
-		});
480
-		$this->registerService('DatabaseConnection', function (Server $c) {
481
-			$systemConfig = $c->getSystemConfig();
482
-			$factory = new \OC\DB\ConnectionFactory($c->getConfig());
483
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
484
-			if (!$factory->isValidType($type)) {
485
-				throw new \OC\DatabaseException('Invalid database type');
486
-			}
487
-			$connectionParams = $factory->createConnectionParams($systemConfig);
488
-			$connection = $factory->getConnection($type, $connectionParams);
489
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
490
-			return $connection;
491
-		});
492
-		$this->registerService('HTTPHelper', function (Server $c) {
493
-			$config = $c->getConfig();
494
-			return new HTTPHelper(
495
-				$config,
496
-				$c->getHTTPClientService()
497
-			);
498
-		});
499
-		$this->registerService('HttpClientService', function (Server $c) {
500
-			$user = \OC_User::getUser();
501
-			$uid = $user ? $user : null;
502
-			return new ClientService(
503
-				$c->getConfig(),
504
-				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
505
-			);
506
-		});
507
-		$this->registerService('EventLogger', function (Server $c) {
508
-			if ($c->getSystemConfig()->getValue('debug', false)) {
509
-				return new EventLogger();
510
-			} else {
511
-				return new NullEventLogger();
512
-			}
513
-		});
514
-		$this->registerService('QueryLogger', function (Server $c) {
515
-			if ($c->getSystemConfig()->getValue('debug', false)) {
516
-				return new QueryLogger();
517
-			} else {
518
-				return new NullQueryLogger();
519
-			}
520
-		});
521
-		$this->registerService('TempManager', function (Server $c) {
522
-			return new TempManager(
523
-				$c->getLogger(),
524
-				$c->getConfig()
525
-			);
526
-		});
527
-		$this->registerService('AppManager', function (Server $c) {
528
-			return new \OC\App\AppManager(
529
-				$c->getUserSession(),
530
-				$c->getAppConfig(),
531
-				$c->getGroupManager(),
532
-				$c->getMemCacheFactory(),
533
-				$c->getEventDispatcher()
534
-			);
535
-		});
536
-		$this->registerService('DateTimeZone', function (Server $c) {
537
-			return new DateTimeZone(
538
-				$c->getConfig(),
539
-				$c->getSession()
540
-			);
541
-		});
542
-		$this->registerService('DateTimeFormatter', function (Server $c) {
543
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
544
-
545
-			return new DateTimeFormatter(
546
-				$c->getDateTimeZone()->getTimeZone(),
547
-				$c->getL10N('lib', $language)
548
-			);
549
-		});
550
-		$this->registerService('UserMountCache', function (Server $c) {
551
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
552
-			$listener = new UserMountCacheListener($mountCache);
553
-			$listener->listen($c->getUserManager());
554
-			return $mountCache;
555
-		});
556
-		$this->registerService('MountConfigManager', function (Server $c) {
557
-			$loader = \OC\Files\Filesystem::getLoader();
558
-			$mountCache = $c->query('UserMountCache');
559
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
560
-
561
-			// builtin providers
562
-
563
-			$config = $c->getConfig();
564
-			$manager->registerProvider(new CacheMountProvider($config));
565
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
566
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
567
-
568
-			return $manager;
569
-		});
570
-		$this->registerService('IniWrapper', function ($c) {
571
-			return new IniGetWrapper();
572
-		});
573
-		$this->registerService('AsyncCommandBus', function (Server $c) {
574
-			$jobList = $c->getJobList();
575
-			return new AsyncBus($jobList);
576
-		});
577
-		$this->registerService('TrustedDomainHelper', function ($c) {
578
-			return new TrustedDomainHelper($this->getConfig());
579
-		});
580
-		$this->registerService('Throttler', function(Server $c) {
581
-			return new Throttler(
582
-				$c->getDatabaseConnection(),
583
-				new TimeFactory(),
584
-				$c->getLogger(),
585
-				$c->getConfig()
586
-			);
587
-		});
588
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
589
-			// IConfig and IAppManager requires a working database. This code
590
-			// might however be called when ownCloud is not yet setup.
591
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
592
-				$config = $c->getConfig();
593
-				$appManager = $c->getAppManager();
594
-			} else {
595
-				$config = null;
596
-				$appManager = null;
597
-			}
598
-
599
-			return new Checker(
600
-					new EnvironmentHelper(),
601
-					new FileAccessHelper(),
602
-					new AppLocator(),
603
-					$config,
604
-					$c->getMemCacheFactory(),
605
-					$appManager,
606
-					$c->getTempManager()
607
-			);
608
-		});
609
-		$this->registerService('Request', function ($c) {
610
-			if (isset($this['urlParams'])) {
611
-				$urlParams = $this['urlParams'];
612
-			} else {
613
-				$urlParams = [];
614
-			}
615
-
616
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
617
-				&& in_array('fakeinput', stream_get_wrappers())
618
-			) {
619
-				$stream = 'fakeinput://data';
620
-			} else {
621
-				$stream = 'php://input';
622
-			}
623
-
624
-			return new Request(
625
-				[
626
-					'get' => $_GET,
627
-					'post' => $_POST,
628
-					'files' => $_FILES,
629
-					'server' => $_SERVER,
630
-					'env' => $_ENV,
631
-					'cookies' => $_COOKIE,
632
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
633
-						? $_SERVER['REQUEST_METHOD']
634
-						: null,
635
-					'urlParams' => $urlParams,
636
-				],
637
-				$this->getSecureRandom(),
638
-				$this->getConfig(),
639
-				$this->getCsrfTokenManager(),
640
-				$stream
641
-			);
642
-		});
643
-		$this->registerService('Mailer', function (Server $c) {
644
-			return new Mailer(
645
-				$c->getConfig(),
646
-				$c->getLogger(),
647
-				$c->getThemingDefaults()
648
-			);
649
-		});
650
-		$this->registerService('LDAPProvider', function(Server $c) {
651
-			$config = $c->getConfig();
652
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
653
-			if(is_null($factoryClass)) {
654
-				throw new \Exception('ldapProviderFactory not set');
655
-			}
656
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
657
-			$factory = new $factoryClass($this);
658
-			return $factory->getLDAPProvider();
659
-		});
660
-		$this->registerService('LockingProvider', function (Server $c) {
661
-			$ini = $c->getIniWrapper();
662
-			$config = $c->getConfig();
663
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
664
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
665
-				/** @var \OC\Memcache\Factory $memcacheFactory */
666
-				$memcacheFactory = $c->getMemCacheFactory();
667
-				$memcache = $memcacheFactory->createLocking('lock');
668
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
669
-					return new MemcacheLockingProvider($memcache, $ttl);
670
-				}
671
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
672
-			}
673
-			return new NoopLockingProvider();
674
-		});
675
-		$this->registerService('MountManager', function () {
676
-			return new \OC\Files\Mount\Manager();
677
-		});
678
-		$this->registerService('MimeTypeDetector', function (Server $c) {
679
-			return new \OC\Files\Type\Detection(
680
-				$c->getURLGenerator(),
681
-				\OC::$configDir,
682
-				\OC::$SERVERROOT . '/resources/config/'
683
-			);
684
-		});
685
-		$this->registerService('MimeTypeLoader', function (Server $c) {
686
-			return new \OC\Files\Type\Loader(
687
-				$c->getDatabaseConnection()
688
-			);
689
-		});
690
-		$this->registerService('NotificationManager', function (Server $c) {
691
-			return new Manager(
692
-				$c->query(IValidator::class)
693
-			);
694
-		});
695
-		$this->registerService('CapabilitiesManager', function (Server $c) {
696
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
697
-			$manager->registerCapability(function () use ($c) {
698
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
699
-			});
700
-			return $manager;
701
-		});
702
-		$this->registerService('CommentsManager', function(Server $c) {
703
-			$config = $c->getConfig();
704
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
705
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
706
-			$factory = new $factoryClass($this);
707
-			return $factory->getManager();
708
-		});
709
-		$this->registerService('ThemingDefaults', function(Server $c) {
710
-			/*
111
+    /** @var string */
112
+    private $webRoot;
113
+
114
+    /**
115
+     * @param string $webRoot
116
+     * @param \OC\Config $config
117
+     */
118
+    public function __construct($webRoot, \OC\Config $config) {
119
+        parent::__construct();
120
+        $this->webRoot = $webRoot;
121
+
122
+        $this->registerService('ContactsManager', function ($c) {
123
+            return new ContactsManager();
124
+        });
125
+
126
+        $this->registerService('PreviewManager', function (Server $c) {
127
+            return new PreviewManager(
128
+                $c->getConfig(),
129
+                $c->getRootFolder(),
130
+                $c->getAppDataDir('preview'),
131
+                $c->getEventDispatcher(),
132
+                $c->getSession()->get('user_id')
133
+            );
134
+        });
135
+
136
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
137
+            return new \OC\Preview\Watcher(
138
+                $c->getAppDataDir('preview')
139
+            );
140
+        });
141
+
142
+        $this->registerService('EncryptionManager', function (Server $c) {
143
+            $view = new View();
144
+            $util = new Encryption\Util(
145
+                $view,
146
+                $c->getUserManager(),
147
+                $c->getGroupManager(),
148
+                $c->getConfig()
149
+            );
150
+            return new Encryption\Manager(
151
+                $c->getConfig(),
152
+                $c->getLogger(),
153
+                $c->getL10N('core'),
154
+                new View(),
155
+                $util,
156
+                new ArrayCache()
157
+            );
158
+        });
159
+
160
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
161
+            $util = new Encryption\Util(
162
+                new View(),
163
+                $c->getUserManager(),
164
+                $c->getGroupManager(),
165
+                $c->getConfig()
166
+            );
167
+            return new Encryption\File($util);
168
+        });
169
+
170
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
171
+            $view = new View();
172
+            $util = new Encryption\Util(
173
+                $view,
174
+                $c->getUserManager(),
175
+                $c->getGroupManager(),
176
+                $c->getConfig()
177
+            );
178
+
179
+            return new Encryption\Keys\Storage($view, $util);
180
+        });
181
+        $this->registerService('TagMapper', function (Server $c) {
182
+            return new TagMapper($c->getDatabaseConnection());
183
+        });
184
+        $this->registerService('TagManager', function (Server $c) {
185
+            $tagMapper = $c->query('TagMapper');
186
+            return new TagManager($tagMapper, $c->getUserSession());
187
+        });
188
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
189
+            $config = $c->getConfig();
190
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
191
+            /** @var \OC\SystemTag\ManagerFactory $factory */
192
+            $factory = new $factoryClass($this);
193
+            return $factory;
194
+        });
195
+        $this->registerService('SystemTagManager', function (Server $c) {
196
+            return $c->query('SystemTagManagerFactory')->getManager();
197
+        });
198
+        $this->registerService('SystemTagObjectMapper', function (Server $c) {
199
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
200
+        });
201
+        $this->registerService('RootFolder', function (Server $c) {
202
+            $manager = \OC\Files\Filesystem::getMountManager(null);
203
+            $view = new View();
204
+            $root = new Root(
205
+                $manager,
206
+                $view,
207
+                null,
208
+                $c->getUserMountCache(),
209
+                $this->getLogger(),
210
+                $this->getUserManager()
211
+            );
212
+            $connector = new HookConnector($root, $view);
213
+            $connector->viewToNode();
214
+
215
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
216
+            $previewConnector->connectWatcher();
217
+
218
+            return $root;
219
+        });
220
+        $this->registerService('LazyRootFolder', function(Server $c) {
221
+            return new LazyRoot(function() use ($c) {
222
+                return $c->query('RootFolder');
223
+            });
224
+        });
225
+        $this->registerService('UserManager', function (Server $c) {
226
+            $config = $c->getConfig();
227
+            return new \OC\User\Manager($config);
228
+        });
229
+        $this->registerService('GroupManager', function (Server $c) {
230
+            $groupManager = new \OC\Group\Manager($this->getUserManager());
231
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
232
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
233
+            });
234
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
235
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
236
+            });
237
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
238
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
239
+            });
240
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
241
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
242
+            });
243
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
244
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
245
+            });
246
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
247
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
248
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
249
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
250
+            });
251
+            return $groupManager;
252
+        });
253
+        $this->registerService(Store::class, function(Server $c) {
254
+            $session = $c->getSession();
255
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
256
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
257
+            } else {
258
+                $tokenProvider = null;
259
+            }
260
+            $logger = $c->getLogger();
261
+            return new Store($session, $logger, $tokenProvider);
262
+        });
263
+        $this->registerAlias(IStore::class, Store::class);
264
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
265
+            $dbConnection = $c->getDatabaseConnection();
266
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
267
+        });
268
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
269
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
270
+            $crypto = $c->getCrypto();
271
+            $config = $c->getConfig();
272
+            $logger = $c->getLogger();
273
+            $timeFactory = new TimeFactory();
274
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
275
+        });
276
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
277
+        $this->registerService('UserSession', function (Server $c) {
278
+            $manager = $c->getUserManager();
279
+            $session = new \OC\Session\Memory('');
280
+            $timeFactory = new TimeFactory();
281
+            // Token providers might require a working database. This code
282
+            // might however be called when ownCloud is not yet setup.
283
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
284
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
285
+            } else {
286
+                $defaultTokenProvider = null;
287
+            }
288
+
289
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom());
290
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
291
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
292
+            });
293
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
294
+                /** @var $user \OC\User\User */
295
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
296
+            });
297
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
298
+                /** @var $user \OC\User\User */
299
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
300
+            });
301
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
302
+                /** @var $user \OC\User\User */
303
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
304
+            });
305
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
306
+                /** @var $user \OC\User\User */
307
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
308
+            });
309
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
310
+                /** @var $user \OC\User\User */
311
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
312
+            });
313
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
314
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
315
+            });
316
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
317
+                /** @var $user \OC\User\User */
318
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
319
+            });
320
+            $userSession->listen('\OC\User', 'logout', function () {
321
+                \OC_Hook::emit('OC_User', 'logout', array());
322
+            });
323
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
324
+                /** @var $user \OC\User\User */
325
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
326
+            });
327
+            return $userSession;
328
+        });
329
+
330
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
331
+            return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
332
+        });
333
+
334
+        $this->registerService('NavigationManager', function (Server $c) {
335
+            return new \OC\NavigationManager($c->getAppManager(),
336
+                $c->getURLGenerator(),
337
+                $c->getL10NFactory(),
338
+                $c->getUserSession(),
339
+                $c->getGroupManager());
340
+        });
341
+        $this->registerService('AllConfig', function (Server $c) {
342
+            return new \OC\AllConfig(
343
+                $c->getSystemConfig()
344
+            );
345
+        });
346
+        $this->registerService('SystemConfig', function ($c) use ($config) {
347
+            return new \OC\SystemConfig($config);
348
+        });
349
+        $this->registerService('AppConfig', function (Server $c) {
350
+            return new \OC\AppConfig($c->getDatabaseConnection());
351
+        });
352
+        $this->registerService('L10NFactory', function (Server $c) {
353
+            return new \OC\L10N\Factory(
354
+                $c->getConfig(),
355
+                $c->getRequest(),
356
+                $c->getUserSession(),
357
+                \OC::$SERVERROOT
358
+            );
359
+        });
360
+        $this->registerService('URLGenerator', function (Server $c) {
361
+            $config = $c->getConfig();
362
+            $cacheFactory = $c->getMemCacheFactory();
363
+            return new \OC\URLGenerator(
364
+                $config,
365
+                $cacheFactory
366
+            );
367
+        });
368
+        $this->registerService('AppHelper', function ($c) {
369
+            return new \OC\AppHelper();
370
+        });
371
+        $this->registerService('AppFetcher', function ($c) {
372
+            return new AppFetcher(
373
+                $this->getAppDataDir('appstore'),
374
+                $this->getHTTPClientService(),
375
+                $this->query(TimeFactory::class),
376
+                $this->getConfig()
377
+            );
378
+        });
379
+        $this->registerService('CategoryFetcher', function ($c) {
380
+            return new CategoryFetcher(
381
+                $this->getAppDataDir('appstore'),
382
+                $this->getHTTPClientService(),
383
+                $this->query(TimeFactory::class),
384
+                $this->getConfig()
385
+            );
386
+        });
387
+        $this->registerService('UserCache', function ($c) {
388
+            return new Cache\File();
389
+        });
390
+        $this->registerService('MemCacheFactory', function (Server $c) {
391
+            $config = $c->getConfig();
392
+
393
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
394
+                $v = \OC_App::getAppVersions();
395
+                $v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
396
+                $version = implode(',', $v);
397
+                $instanceId = \OC_Util::getInstanceId();
398
+                $path = \OC::$SERVERROOT;
399
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
400
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
401
+                    $config->getSystemValue('memcache.local', null),
402
+                    $config->getSystemValue('memcache.distributed', null),
403
+                    $config->getSystemValue('memcache.locking', null)
404
+                );
405
+            }
406
+
407
+            return new \OC\Memcache\Factory('', $c->getLogger(),
408
+                '\\OC\\Memcache\\ArrayCache',
409
+                '\\OC\\Memcache\\ArrayCache',
410
+                '\\OC\\Memcache\\ArrayCache'
411
+            );
412
+        });
413
+        $this->registerService('RedisFactory', function (Server $c) {
414
+            $systemConfig = $c->getSystemConfig();
415
+            return new RedisFactory($systemConfig);
416
+        });
417
+        $this->registerService('ActivityManager', function (Server $c) {
418
+            return new \OC\Activity\Manager(
419
+                $c->getRequest(),
420
+                $c->getUserSession(),
421
+                $c->getConfig(),
422
+                $c->query(IValidator::class)
423
+            );
424
+        });
425
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
426
+            return new \OC\Activity\EventMerger(
427
+                $c->getL10N('lib')
428
+            );
429
+        });
430
+        $this->registerAlias(IValidator::class, Validator::class);
431
+        $this->registerService('AvatarManager', function (Server $c) {
432
+            return new AvatarManager(
433
+                $c->getUserManager(),
434
+                $c->getAppDataDir('avatar'),
435
+                $c->getL10N('lib'),
436
+                $c->getLogger(),
437
+                $c->getConfig()
438
+            );
439
+        });
440
+        $this->registerService('Logger', function (Server $c) {
441
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
442
+            $logger = Log::getLogClass($logType);
443
+            call_user_func(array($logger, 'init'));
444
+
445
+            return new Log($logger);
446
+        });
447
+        $this->registerService('JobList', function (Server $c) {
448
+            $config = $c->getConfig();
449
+            return new \OC\BackgroundJob\JobList(
450
+                $c->getDatabaseConnection(),
451
+                $config,
452
+                new TimeFactory()
453
+            );
454
+        });
455
+        $this->registerService('Router', function (Server $c) {
456
+            $cacheFactory = $c->getMemCacheFactory();
457
+            $logger = $c->getLogger();
458
+            if ($cacheFactory->isAvailable()) {
459
+                $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
460
+            } else {
461
+                $router = new \OC\Route\Router($logger);
462
+            }
463
+            return $router;
464
+        });
465
+        $this->registerService('Search', function ($c) {
466
+            return new Search();
467
+        });
468
+        $this->registerService('SecureRandom', function ($c) {
469
+            return new SecureRandom();
470
+        });
471
+        $this->registerService('Crypto', function (Server $c) {
472
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
473
+        });
474
+        $this->registerService('Hasher', function (Server $c) {
475
+            return new Hasher($c->getConfig());
476
+        });
477
+        $this->registerService('CredentialsManager', function (Server $c) {
478
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
479
+        });
480
+        $this->registerService('DatabaseConnection', function (Server $c) {
481
+            $systemConfig = $c->getSystemConfig();
482
+            $factory = new \OC\DB\ConnectionFactory($c->getConfig());
483
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
484
+            if (!$factory->isValidType($type)) {
485
+                throw new \OC\DatabaseException('Invalid database type');
486
+            }
487
+            $connectionParams = $factory->createConnectionParams($systemConfig);
488
+            $connection = $factory->getConnection($type, $connectionParams);
489
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
490
+            return $connection;
491
+        });
492
+        $this->registerService('HTTPHelper', function (Server $c) {
493
+            $config = $c->getConfig();
494
+            return new HTTPHelper(
495
+                $config,
496
+                $c->getHTTPClientService()
497
+            );
498
+        });
499
+        $this->registerService('HttpClientService', function (Server $c) {
500
+            $user = \OC_User::getUser();
501
+            $uid = $user ? $user : null;
502
+            return new ClientService(
503
+                $c->getConfig(),
504
+                new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
505
+            );
506
+        });
507
+        $this->registerService('EventLogger', function (Server $c) {
508
+            if ($c->getSystemConfig()->getValue('debug', false)) {
509
+                return new EventLogger();
510
+            } else {
511
+                return new NullEventLogger();
512
+            }
513
+        });
514
+        $this->registerService('QueryLogger', function (Server $c) {
515
+            if ($c->getSystemConfig()->getValue('debug', false)) {
516
+                return new QueryLogger();
517
+            } else {
518
+                return new NullQueryLogger();
519
+            }
520
+        });
521
+        $this->registerService('TempManager', function (Server $c) {
522
+            return new TempManager(
523
+                $c->getLogger(),
524
+                $c->getConfig()
525
+            );
526
+        });
527
+        $this->registerService('AppManager', function (Server $c) {
528
+            return new \OC\App\AppManager(
529
+                $c->getUserSession(),
530
+                $c->getAppConfig(),
531
+                $c->getGroupManager(),
532
+                $c->getMemCacheFactory(),
533
+                $c->getEventDispatcher()
534
+            );
535
+        });
536
+        $this->registerService('DateTimeZone', function (Server $c) {
537
+            return new DateTimeZone(
538
+                $c->getConfig(),
539
+                $c->getSession()
540
+            );
541
+        });
542
+        $this->registerService('DateTimeFormatter', function (Server $c) {
543
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
544
+
545
+            return new DateTimeFormatter(
546
+                $c->getDateTimeZone()->getTimeZone(),
547
+                $c->getL10N('lib', $language)
548
+            );
549
+        });
550
+        $this->registerService('UserMountCache', function (Server $c) {
551
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
552
+            $listener = new UserMountCacheListener($mountCache);
553
+            $listener->listen($c->getUserManager());
554
+            return $mountCache;
555
+        });
556
+        $this->registerService('MountConfigManager', function (Server $c) {
557
+            $loader = \OC\Files\Filesystem::getLoader();
558
+            $mountCache = $c->query('UserMountCache');
559
+            $manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
560
+
561
+            // builtin providers
562
+
563
+            $config = $c->getConfig();
564
+            $manager->registerProvider(new CacheMountProvider($config));
565
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
566
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
567
+
568
+            return $manager;
569
+        });
570
+        $this->registerService('IniWrapper', function ($c) {
571
+            return new IniGetWrapper();
572
+        });
573
+        $this->registerService('AsyncCommandBus', function (Server $c) {
574
+            $jobList = $c->getJobList();
575
+            return new AsyncBus($jobList);
576
+        });
577
+        $this->registerService('TrustedDomainHelper', function ($c) {
578
+            return new TrustedDomainHelper($this->getConfig());
579
+        });
580
+        $this->registerService('Throttler', function(Server $c) {
581
+            return new Throttler(
582
+                $c->getDatabaseConnection(),
583
+                new TimeFactory(),
584
+                $c->getLogger(),
585
+                $c->getConfig()
586
+            );
587
+        });
588
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
589
+            // IConfig and IAppManager requires a working database. This code
590
+            // might however be called when ownCloud is not yet setup.
591
+            if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
592
+                $config = $c->getConfig();
593
+                $appManager = $c->getAppManager();
594
+            } else {
595
+                $config = null;
596
+                $appManager = null;
597
+            }
598
+
599
+            return new Checker(
600
+                    new EnvironmentHelper(),
601
+                    new FileAccessHelper(),
602
+                    new AppLocator(),
603
+                    $config,
604
+                    $c->getMemCacheFactory(),
605
+                    $appManager,
606
+                    $c->getTempManager()
607
+            );
608
+        });
609
+        $this->registerService('Request', function ($c) {
610
+            if (isset($this['urlParams'])) {
611
+                $urlParams = $this['urlParams'];
612
+            } else {
613
+                $urlParams = [];
614
+            }
615
+
616
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
617
+                && in_array('fakeinput', stream_get_wrappers())
618
+            ) {
619
+                $stream = 'fakeinput://data';
620
+            } else {
621
+                $stream = 'php://input';
622
+            }
623
+
624
+            return new Request(
625
+                [
626
+                    'get' => $_GET,
627
+                    'post' => $_POST,
628
+                    'files' => $_FILES,
629
+                    'server' => $_SERVER,
630
+                    'env' => $_ENV,
631
+                    'cookies' => $_COOKIE,
632
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
633
+                        ? $_SERVER['REQUEST_METHOD']
634
+                        : null,
635
+                    'urlParams' => $urlParams,
636
+                ],
637
+                $this->getSecureRandom(),
638
+                $this->getConfig(),
639
+                $this->getCsrfTokenManager(),
640
+                $stream
641
+            );
642
+        });
643
+        $this->registerService('Mailer', function (Server $c) {
644
+            return new Mailer(
645
+                $c->getConfig(),
646
+                $c->getLogger(),
647
+                $c->getThemingDefaults()
648
+            );
649
+        });
650
+        $this->registerService('LDAPProvider', function(Server $c) {
651
+            $config = $c->getConfig();
652
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
653
+            if(is_null($factoryClass)) {
654
+                throw new \Exception('ldapProviderFactory not set');
655
+            }
656
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
657
+            $factory = new $factoryClass($this);
658
+            return $factory->getLDAPProvider();
659
+        });
660
+        $this->registerService('LockingProvider', function (Server $c) {
661
+            $ini = $c->getIniWrapper();
662
+            $config = $c->getConfig();
663
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
664
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
665
+                /** @var \OC\Memcache\Factory $memcacheFactory */
666
+                $memcacheFactory = $c->getMemCacheFactory();
667
+                $memcache = $memcacheFactory->createLocking('lock');
668
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
669
+                    return new MemcacheLockingProvider($memcache, $ttl);
670
+                }
671
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
672
+            }
673
+            return new NoopLockingProvider();
674
+        });
675
+        $this->registerService('MountManager', function () {
676
+            return new \OC\Files\Mount\Manager();
677
+        });
678
+        $this->registerService('MimeTypeDetector', function (Server $c) {
679
+            return new \OC\Files\Type\Detection(
680
+                $c->getURLGenerator(),
681
+                \OC::$configDir,
682
+                \OC::$SERVERROOT . '/resources/config/'
683
+            );
684
+        });
685
+        $this->registerService('MimeTypeLoader', function (Server $c) {
686
+            return new \OC\Files\Type\Loader(
687
+                $c->getDatabaseConnection()
688
+            );
689
+        });
690
+        $this->registerService('NotificationManager', function (Server $c) {
691
+            return new Manager(
692
+                $c->query(IValidator::class)
693
+            );
694
+        });
695
+        $this->registerService('CapabilitiesManager', function (Server $c) {
696
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
697
+            $manager->registerCapability(function () use ($c) {
698
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
699
+            });
700
+            return $manager;
701
+        });
702
+        $this->registerService('CommentsManager', function(Server $c) {
703
+            $config = $c->getConfig();
704
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
705
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
706
+            $factory = new $factoryClass($this);
707
+            return $factory->getManager();
708
+        });
709
+        $this->registerService('ThemingDefaults', function(Server $c) {
710
+            /*
711 711
 			 * Dark magic for autoloader.
712 712
 			 * If we do a class_exists it will try to load the class which will
713 713
 			 * make composer cache the result. Resulting in errors when enabling
714 714
 			 * the theming app.
715 715
 			 */
716
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
717
-			if (isset($prefixes['OCA\\Theming\\'])) {
718
-				$classExists = true;
719
-			} else {
720
-				$classExists = false;
721
-			}
722
-
723
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
724
-				return new ThemingDefaults(
725
-					$c->getConfig(),
726
-					$c->getL10N('theming'),
727
-					$c->getURLGenerator(),
728
-					new \OC_Defaults(),
729
-					$c->getLazyRootFolder(),
730
-					$c->getMemCacheFactory()
731
-				);
732
-			}
733
-			return new \OC_Defaults();
734
-		});
735
-		$this->registerService('EventDispatcher', function () {
736
-			return new EventDispatcher();
737
-		});
738
-		$this->registerService('CryptoWrapper', function (Server $c) {
739
-			// FIXME: Instantiiated here due to cyclic dependency
740
-			$request = new Request(
741
-				[
742
-					'get' => $_GET,
743
-					'post' => $_POST,
744
-					'files' => $_FILES,
745
-					'server' => $_SERVER,
746
-					'env' => $_ENV,
747
-					'cookies' => $_COOKIE,
748
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
749
-						? $_SERVER['REQUEST_METHOD']
750
-						: null,
751
-				],
752
-				$c->getSecureRandom(),
753
-				$c->getConfig()
754
-			);
755
-
756
-			return new CryptoWrapper(
757
-				$c->getConfig(),
758
-				$c->getCrypto(),
759
-				$c->getSecureRandom(),
760
-				$request
761
-			);
762
-		});
763
-		$this->registerService('CsrfTokenManager', function (Server $c) {
764
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
765
-
766
-			return new CsrfTokenManager(
767
-				$tokenGenerator,
768
-				$c->query(SessionStorage::class)
769
-			);
770
-		});
771
-		$this->registerService(SessionStorage::class, function (Server $c) {
772
-			return new SessionStorage($c->getSession());
773
-		});
774
-		$this->registerService('ContentSecurityPolicyManager', function (Server $c) {
775
-			return new ContentSecurityPolicyManager();
776
-		});
777
-		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
778
-			return new ContentSecurityPolicyNonceManager(
779
-				$c->getCsrfTokenManager(),
780
-				$c->getRequest()
781
-			);
782
-		});
783
-		$this->registerService('ShareManager', function(Server $c) {
784
-			$config = $c->getConfig();
785
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
786
-			/** @var \OCP\Share\IProviderFactory $factory */
787
-			$factory = new $factoryClass($this);
788
-
789
-			$manager = new \OC\Share20\Manager(
790
-				$c->getLogger(),
791
-				$c->getConfig(),
792
-				$c->getSecureRandom(),
793
-				$c->getHasher(),
794
-				$c->getMountManager(),
795
-				$c->getGroupManager(),
796
-				$c->getL10N('core'),
797
-				$factory,
798
-				$c->getUserManager(),
799
-				$c->getLazyRootFolder(),
800
-				$c->getEventDispatcher()
801
-			);
802
-
803
-			return $manager;
804
-		});
805
-		$this->registerService('SettingsManager', function(Server $c) {
806
-			$manager = new \OC\Settings\Manager(
807
-				$c->getLogger(),
808
-				$c->getDatabaseConnection(),
809
-				$c->getL10N('lib'),
810
-				$c->getConfig(),
811
-				$c->getEncryptionManager(),
812
-				$c->getUserManager(),
813
-				$c->getLockingProvider(),
814
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
815
-				$c->getURLGenerator()
816
-			);
817
-			return $manager;
818
-		});
819
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
820
-			return new \OC\Files\AppData\Factory(
821
-				$c->getRootFolder(),
822
-				$c->getSystemConfig()
823
-			);
824
-		});
825
-
826
-		$this->registerService('LockdownManager', function (Server $c) {
827
-			return new LockdownManager();
828
-		});
829
-
830
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
831
-			return new CloudIdManager();
832
-		});
833
-
834
-		/* To trick DI since we don't extend the DIContainer here */
835
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
836
-			return new CleanPreviewsBackgroundJob(
837
-				$c->getRootFolder(),
838
-				$c->getLogger(),
839
-				$c->getJobList(),
840
-				new TimeFactory()
841
-			);
842
-		});
843
-	}
844
-
845
-	/**
846
-	 * @return \OCP\Contacts\IManager
847
-	 */
848
-	public function getContactsManager() {
849
-		return $this->query('ContactsManager');
850
-	}
851
-
852
-	/**
853
-	 * @return \OC\Encryption\Manager
854
-	 */
855
-	public function getEncryptionManager() {
856
-		return $this->query('EncryptionManager');
857
-	}
858
-
859
-	/**
860
-	 * @return \OC\Encryption\File
861
-	 */
862
-	public function getEncryptionFilesHelper() {
863
-		return $this->query('EncryptionFileHelper');
864
-	}
865
-
866
-	/**
867
-	 * @return \OCP\Encryption\Keys\IStorage
868
-	 */
869
-	public function getEncryptionKeyStorage() {
870
-		return $this->query('EncryptionKeyStorage');
871
-	}
872
-
873
-	/**
874
-	 * The current request object holding all information about the request
875
-	 * currently being processed is returned from this method.
876
-	 * In case the current execution was not initiated by a web request null is returned
877
-	 *
878
-	 * @return \OCP\IRequest
879
-	 */
880
-	public function getRequest() {
881
-		return $this->query('Request');
882
-	}
883
-
884
-	/**
885
-	 * Returns the preview manager which can create preview images for a given file
886
-	 *
887
-	 * @return \OCP\IPreview
888
-	 */
889
-	public function getPreviewManager() {
890
-		return $this->query('PreviewManager');
891
-	}
892
-
893
-	/**
894
-	 * Returns the tag manager which can get and set tags for different object types
895
-	 *
896
-	 * @see \OCP\ITagManager::load()
897
-	 * @return \OCP\ITagManager
898
-	 */
899
-	public function getTagManager() {
900
-		return $this->query('TagManager');
901
-	}
902
-
903
-	/**
904
-	 * Returns the system-tag manager
905
-	 *
906
-	 * @return \OCP\SystemTag\ISystemTagManager
907
-	 *
908
-	 * @since 9.0.0
909
-	 */
910
-	public function getSystemTagManager() {
911
-		return $this->query('SystemTagManager');
912
-	}
913
-
914
-	/**
915
-	 * Returns the system-tag object mapper
916
-	 *
917
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
918
-	 *
919
-	 * @since 9.0.0
920
-	 */
921
-	public function getSystemTagObjectMapper() {
922
-		return $this->query('SystemTagObjectMapper');
923
-	}
924
-
925
-	/**
926
-	 * Returns the avatar manager, used for avatar functionality
927
-	 *
928
-	 * @return \OCP\IAvatarManager
929
-	 */
930
-	public function getAvatarManager() {
931
-		return $this->query('AvatarManager');
932
-	}
933
-
934
-	/**
935
-	 * Returns the root folder of ownCloud's data directory
936
-	 *
937
-	 * @return \OCP\Files\IRootFolder
938
-	 */
939
-	public function getRootFolder() {
940
-		return $this->query('LazyRootFolder');
941
-	}
942
-
943
-	/**
944
-	 * Returns the root folder of ownCloud's data directory
945
-	 * This is the lazy variant so this gets only initialized once it
946
-	 * is actually used.
947
-	 *
948
-	 * @return \OCP\Files\IRootFolder
949
-	 */
950
-	public function getLazyRootFolder() {
951
-		return $this->query('LazyRootFolder');
952
-	}
953
-
954
-	/**
955
-	 * Returns a view to ownCloud's files folder
956
-	 *
957
-	 * @param string $userId user ID
958
-	 * @return \OCP\Files\Folder|null
959
-	 */
960
-	public function getUserFolder($userId = null) {
961
-		if ($userId === null) {
962
-			$user = $this->getUserSession()->getUser();
963
-			if (!$user) {
964
-				return null;
965
-			}
966
-			$userId = $user->getUID();
967
-		}
968
-		$root = $this->getRootFolder();
969
-		return $root->getUserFolder($userId);
970
-	}
971
-
972
-	/**
973
-	 * Returns an app-specific view in ownClouds data directory
974
-	 *
975
-	 * @return \OCP\Files\Folder
976
-	 * @deprecated since 9.2.0 use IAppData
977
-	 */
978
-	public function getAppFolder() {
979
-		$dir = '/' . \OC_App::getCurrentApp();
980
-		$root = $this->getRootFolder();
981
-		if (!$root->nodeExists($dir)) {
982
-			$folder = $root->newFolder($dir);
983
-		} else {
984
-			$folder = $root->get($dir);
985
-		}
986
-		return $folder;
987
-	}
988
-
989
-	/**
990
-	 * @return \OC\User\Manager
991
-	 */
992
-	public function getUserManager() {
993
-		return $this->query('UserManager');
994
-	}
995
-
996
-	/**
997
-	 * @return \OC\Group\Manager
998
-	 */
999
-	public function getGroupManager() {
1000
-		return $this->query('GroupManager');
1001
-	}
1002
-
1003
-	/**
1004
-	 * @return \OC\User\Session
1005
-	 */
1006
-	public function getUserSession() {
1007
-		return $this->query('UserSession');
1008
-	}
1009
-
1010
-	/**
1011
-	 * @return \OCP\ISession
1012
-	 */
1013
-	public function getSession() {
1014
-		return $this->query('UserSession')->getSession();
1015
-	}
1016
-
1017
-	/**
1018
-	 * @param \OCP\ISession $session
1019
-	 */
1020
-	public function setSession(\OCP\ISession $session) {
1021
-		$this->query(SessionStorage::class)->setSession($session);
1022
-		$this->query('UserSession')->setSession($session);
1023
-		$this->query(Store::class)->setSession($session);
1024
-	}
1025
-
1026
-	/**
1027
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1028
-	 */
1029
-	public function getTwoFactorAuthManager() {
1030
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1031
-	}
1032
-
1033
-	/**
1034
-	 * @return \OC\NavigationManager
1035
-	 */
1036
-	public function getNavigationManager() {
1037
-		return $this->query('NavigationManager');
1038
-	}
1039
-
1040
-	/**
1041
-	 * @return \OCP\IConfig
1042
-	 */
1043
-	public function getConfig() {
1044
-		return $this->query('AllConfig');
1045
-	}
1046
-
1047
-	/**
1048
-	 * @internal For internal use only
1049
-	 * @return \OC\SystemConfig
1050
-	 */
1051
-	public function getSystemConfig() {
1052
-		return $this->query('SystemConfig');
1053
-	}
1054
-
1055
-	/**
1056
-	 * Returns the app config manager
1057
-	 *
1058
-	 * @return \OCP\IAppConfig
1059
-	 */
1060
-	public function getAppConfig() {
1061
-		return $this->query('AppConfig');
1062
-	}
1063
-
1064
-	/**
1065
-	 * @return \OCP\L10N\IFactory
1066
-	 */
1067
-	public function getL10NFactory() {
1068
-		return $this->query('L10NFactory');
1069
-	}
1070
-
1071
-	/**
1072
-	 * get an L10N instance
1073
-	 *
1074
-	 * @param string $app appid
1075
-	 * @param string $lang
1076
-	 * @return IL10N
1077
-	 */
1078
-	public function getL10N($app, $lang = null) {
1079
-		return $this->getL10NFactory()->get($app, $lang);
1080
-	}
1081
-
1082
-	/**
1083
-	 * @return \OCP\IURLGenerator
1084
-	 */
1085
-	public function getURLGenerator() {
1086
-		return $this->query('URLGenerator');
1087
-	}
1088
-
1089
-	/**
1090
-	 * @return \OCP\IHelper
1091
-	 */
1092
-	public function getHelper() {
1093
-		return $this->query('AppHelper');
1094
-	}
1095
-
1096
-	/**
1097
-	 * @return AppFetcher
1098
-	 */
1099
-	public function getAppFetcher() {
1100
-		return $this->query('AppFetcher');
1101
-	}
1102
-
1103
-	/**
1104
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1105
-	 * getMemCacheFactory() instead.
1106
-	 *
1107
-	 * @return \OCP\ICache
1108
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1109
-	 */
1110
-	public function getCache() {
1111
-		return $this->query('UserCache');
1112
-	}
1113
-
1114
-	/**
1115
-	 * Returns an \OCP\CacheFactory instance
1116
-	 *
1117
-	 * @return \OCP\ICacheFactory
1118
-	 */
1119
-	public function getMemCacheFactory() {
1120
-		return $this->query('MemCacheFactory');
1121
-	}
1122
-
1123
-	/**
1124
-	 * Returns an \OC\RedisFactory instance
1125
-	 *
1126
-	 * @return \OC\RedisFactory
1127
-	 */
1128
-	public function getGetRedisFactory() {
1129
-		return $this->query('RedisFactory');
1130
-	}
1131
-
1132
-
1133
-	/**
1134
-	 * Returns the current session
1135
-	 *
1136
-	 * @return \OCP\IDBConnection
1137
-	 */
1138
-	public function getDatabaseConnection() {
1139
-		return $this->query('DatabaseConnection');
1140
-	}
1141
-
1142
-	/**
1143
-	 * Returns the activity manager
1144
-	 *
1145
-	 * @return \OCP\Activity\IManager
1146
-	 */
1147
-	public function getActivityManager() {
1148
-		return $this->query('ActivityManager');
1149
-	}
1150
-
1151
-	/**
1152
-	 * Returns an job list for controlling background jobs
1153
-	 *
1154
-	 * @return \OCP\BackgroundJob\IJobList
1155
-	 */
1156
-	public function getJobList() {
1157
-		return $this->query('JobList');
1158
-	}
1159
-
1160
-	/**
1161
-	 * Returns a logger instance
1162
-	 *
1163
-	 * @return \OCP\ILogger
1164
-	 */
1165
-	public function getLogger() {
1166
-		return $this->query('Logger');
1167
-	}
1168
-
1169
-	/**
1170
-	 * Returns a router for generating and matching urls
1171
-	 *
1172
-	 * @return \OCP\Route\IRouter
1173
-	 */
1174
-	public function getRouter() {
1175
-		return $this->query('Router');
1176
-	}
1177
-
1178
-	/**
1179
-	 * Returns a search instance
1180
-	 *
1181
-	 * @return \OCP\ISearch
1182
-	 */
1183
-	public function getSearch() {
1184
-		return $this->query('Search');
1185
-	}
1186
-
1187
-	/**
1188
-	 * Returns a SecureRandom instance
1189
-	 *
1190
-	 * @return \OCP\Security\ISecureRandom
1191
-	 */
1192
-	public function getSecureRandom() {
1193
-		return $this->query('SecureRandom');
1194
-	}
1195
-
1196
-	/**
1197
-	 * Returns a Crypto instance
1198
-	 *
1199
-	 * @return \OCP\Security\ICrypto
1200
-	 */
1201
-	public function getCrypto() {
1202
-		return $this->query('Crypto');
1203
-	}
1204
-
1205
-	/**
1206
-	 * Returns a Hasher instance
1207
-	 *
1208
-	 * @return \OCP\Security\IHasher
1209
-	 */
1210
-	public function getHasher() {
1211
-		return $this->query('Hasher');
1212
-	}
1213
-
1214
-	/**
1215
-	 * Returns a CredentialsManager instance
1216
-	 *
1217
-	 * @return \OCP\Security\ICredentialsManager
1218
-	 */
1219
-	public function getCredentialsManager() {
1220
-		return $this->query('CredentialsManager');
1221
-	}
1222
-
1223
-	/**
1224
-	 * Returns an instance of the HTTP helper class
1225
-	 *
1226
-	 * @deprecated Use getHTTPClientService()
1227
-	 * @return \OC\HTTPHelper
1228
-	 */
1229
-	public function getHTTPHelper() {
1230
-		return $this->query('HTTPHelper');
1231
-	}
1232
-
1233
-	/**
1234
-	 * Get the certificate manager for the user
1235
-	 *
1236
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1237
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1238
-	 */
1239
-	public function getCertificateManager($userId = '') {
1240
-		if ($userId === '') {
1241
-			$userSession = $this->getUserSession();
1242
-			$user = $userSession->getUser();
1243
-			if (is_null($user)) {
1244
-				return null;
1245
-			}
1246
-			$userId = $user->getUID();
1247
-		}
1248
-		return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1249
-	}
1250
-
1251
-	/**
1252
-	 * Returns an instance of the HTTP client service
1253
-	 *
1254
-	 * @return \OCP\Http\Client\IClientService
1255
-	 */
1256
-	public function getHTTPClientService() {
1257
-		return $this->query('HttpClientService');
1258
-	}
1259
-
1260
-	/**
1261
-	 * Create a new event source
1262
-	 *
1263
-	 * @return \OCP\IEventSource
1264
-	 */
1265
-	public function createEventSource() {
1266
-		return new \OC_EventSource();
1267
-	}
1268
-
1269
-	/**
1270
-	 * Get the active event logger
1271
-	 *
1272
-	 * The returned logger only logs data when debug mode is enabled
1273
-	 *
1274
-	 * @return \OCP\Diagnostics\IEventLogger
1275
-	 */
1276
-	public function getEventLogger() {
1277
-		return $this->query('EventLogger');
1278
-	}
1279
-
1280
-	/**
1281
-	 * Get the active query logger
1282
-	 *
1283
-	 * The returned logger only logs data when debug mode is enabled
1284
-	 *
1285
-	 * @return \OCP\Diagnostics\IQueryLogger
1286
-	 */
1287
-	public function getQueryLogger() {
1288
-		return $this->query('QueryLogger');
1289
-	}
1290
-
1291
-	/**
1292
-	 * Get the manager for temporary files and folders
1293
-	 *
1294
-	 * @return \OCP\ITempManager
1295
-	 */
1296
-	public function getTempManager() {
1297
-		return $this->query('TempManager');
1298
-	}
1299
-
1300
-	/**
1301
-	 * Get the app manager
1302
-	 *
1303
-	 * @return \OCP\App\IAppManager
1304
-	 */
1305
-	public function getAppManager() {
1306
-		return $this->query('AppManager');
1307
-	}
1308
-
1309
-	/**
1310
-	 * Creates a new mailer
1311
-	 *
1312
-	 * @return \OCP\Mail\IMailer
1313
-	 */
1314
-	public function getMailer() {
1315
-		return $this->query('Mailer');
1316
-	}
1317
-
1318
-	/**
1319
-	 * Get the webroot
1320
-	 *
1321
-	 * @return string
1322
-	 */
1323
-	public function getWebRoot() {
1324
-		return $this->webRoot;
1325
-	}
1326
-
1327
-	/**
1328
-	 * @return \OC\OCSClient
1329
-	 */
1330
-	public function getOcsClient() {
1331
-		return $this->query('OcsClient');
1332
-	}
1333
-
1334
-	/**
1335
-	 * @return \OCP\IDateTimeZone
1336
-	 */
1337
-	public function getDateTimeZone() {
1338
-		return $this->query('DateTimeZone');
1339
-	}
1340
-
1341
-	/**
1342
-	 * @return \OCP\IDateTimeFormatter
1343
-	 */
1344
-	public function getDateTimeFormatter() {
1345
-		return $this->query('DateTimeFormatter');
1346
-	}
1347
-
1348
-	/**
1349
-	 * @return \OCP\Files\Config\IMountProviderCollection
1350
-	 */
1351
-	public function getMountProviderCollection() {
1352
-		return $this->query('MountConfigManager');
1353
-	}
1354
-
1355
-	/**
1356
-	 * Get the IniWrapper
1357
-	 *
1358
-	 * @return IniGetWrapper
1359
-	 */
1360
-	public function getIniWrapper() {
1361
-		return $this->query('IniWrapper');
1362
-	}
1363
-
1364
-	/**
1365
-	 * @return \OCP\Command\IBus
1366
-	 */
1367
-	public function getCommandBus() {
1368
-		return $this->query('AsyncCommandBus');
1369
-	}
1370
-
1371
-	/**
1372
-	 * Get the trusted domain helper
1373
-	 *
1374
-	 * @return TrustedDomainHelper
1375
-	 */
1376
-	public function getTrustedDomainHelper() {
1377
-		return $this->query('TrustedDomainHelper');
1378
-	}
1379
-
1380
-	/**
1381
-	 * Get the locking provider
1382
-	 *
1383
-	 * @return \OCP\Lock\ILockingProvider
1384
-	 * @since 8.1.0
1385
-	 */
1386
-	public function getLockingProvider() {
1387
-		return $this->query('LockingProvider');
1388
-	}
1389
-
1390
-	/**
1391
-	 * @return \OCP\Files\Mount\IMountManager
1392
-	 **/
1393
-	function getMountManager() {
1394
-		return $this->query('MountManager');
1395
-	}
1396
-
1397
-	/** @return \OCP\Files\Config\IUserMountCache */
1398
-	function getUserMountCache() {
1399
-		return $this->query('UserMountCache');
1400
-	}
1401
-
1402
-	/**
1403
-	 * Get the MimeTypeDetector
1404
-	 *
1405
-	 * @return \OCP\Files\IMimeTypeDetector
1406
-	 */
1407
-	public function getMimeTypeDetector() {
1408
-		return $this->query('MimeTypeDetector');
1409
-	}
1410
-
1411
-	/**
1412
-	 * Get the MimeTypeLoader
1413
-	 *
1414
-	 * @return \OCP\Files\IMimeTypeLoader
1415
-	 */
1416
-	public function getMimeTypeLoader() {
1417
-		return $this->query('MimeTypeLoader');
1418
-	}
1419
-
1420
-	/**
1421
-	 * Get the manager of all the capabilities
1422
-	 *
1423
-	 * @return \OC\CapabilitiesManager
1424
-	 */
1425
-	public function getCapabilitiesManager() {
1426
-		return $this->query('CapabilitiesManager');
1427
-	}
1428
-
1429
-	/**
1430
-	 * Get the EventDispatcher
1431
-	 *
1432
-	 * @return EventDispatcherInterface
1433
-	 * @since 8.2.0
1434
-	 */
1435
-	public function getEventDispatcher() {
1436
-		return $this->query('EventDispatcher');
1437
-	}
1438
-
1439
-	/**
1440
-	 * Get the Notification Manager
1441
-	 *
1442
-	 * @return \OCP\Notification\IManager
1443
-	 * @since 8.2.0
1444
-	 */
1445
-	public function getNotificationManager() {
1446
-		return $this->query('NotificationManager');
1447
-	}
1448
-
1449
-	/**
1450
-	 * @return \OCP\Comments\ICommentsManager
1451
-	 */
1452
-	public function getCommentsManager() {
1453
-		return $this->query('CommentsManager');
1454
-	}
1455
-
1456
-	/**
1457
-	 * @return \OC_Defaults
1458
-	 */
1459
-	public function getThemingDefaults() {
1460
-		return $this->query('ThemingDefaults');
1461
-	}
1462
-
1463
-	/**
1464
-	 * @return \OC\IntegrityCheck\Checker
1465
-	 */
1466
-	public function getIntegrityCodeChecker() {
1467
-		return $this->query('IntegrityCodeChecker');
1468
-	}
1469
-
1470
-	/**
1471
-	 * @return \OC\Session\CryptoWrapper
1472
-	 */
1473
-	public function getSessionCryptoWrapper() {
1474
-		return $this->query('CryptoWrapper');
1475
-	}
1476
-
1477
-	/**
1478
-	 * @return CsrfTokenManager
1479
-	 */
1480
-	public function getCsrfTokenManager() {
1481
-		return $this->query('CsrfTokenManager');
1482
-	}
1483
-
1484
-	/**
1485
-	 * @return Throttler
1486
-	 */
1487
-	public function getBruteForceThrottler() {
1488
-		return $this->query('Throttler');
1489
-	}
1490
-
1491
-	/**
1492
-	 * @return IContentSecurityPolicyManager
1493
-	 */
1494
-	public function getContentSecurityPolicyManager() {
1495
-		return $this->query('ContentSecurityPolicyManager');
1496
-	}
1497
-
1498
-	/**
1499
-	 * @return ContentSecurityPolicyNonceManager
1500
-	 */
1501
-	public function getContentSecurityPolicyNonceManager() {
1502
-		return $this->query('ContentSecurityPolicyNonceManager');
1503
-	}
1504
-
1505
-	/**
1506
-	 * Not a public API as of 8.2, wait for 9.0
1507
-	 *
1508
-	 * @return \OCA\Files_External\Service\BackendService
1509
-	 */
1510
-	public function getStoragesBackendService() {
1511
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1512
-	}
1513
-
1514
-	/**
1515
-	 * Not a public API as of 8.2, wait for 9.0
1516
-	 *
1517
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1518
-	 */
1519
-	public function getGlobalStoragesService() {
1520
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1521
-	}
1522
-
1523
-	/**
1524
-	 * Not a public API as of 8.2, wait for 9.0
1525
-	 *
1526
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1527
-	 */
1528
-	public function getUserGlobalStoragesService() {
1529
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1530
-	}
1531
-
1532
-	/**
1533
-	 * Not a public API as of 8.2, wait for 9.0
1534
-	 *
1535
-	 * @return \OCA\Files_External\Service\UserStoragesService
1536
-	 */
1537
-	public function getUserStoragesService() {
1538
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1539
-	}
1540
-
1541
-	/**
1542
-	 * @return \OCP\Share\IManager
1543
-	 */
1544
-	public function getShareManager() {
1545
-		return $this->query('ShareManager');
1546
-	}
1547
-
1548
-	/**
1549
-	 * Returns the LDAP Provider
1550
-	 *
1551
-	 * @return \OCP\LDAP\ILDAPProvider
1552
-	 */
1553
-	public function getLDAPProvider() {
1554
-		return $this->query('LDAPProvider');
1555
-	}
1556
-
1557
-	/**
1558
-	 * @return \OCP\Settings\IManager
1559
-	 */
1560
-	public function getSettingsManager() {
1561
-		return $this->query('SettingsManager');
1562
-	}
1563
-
1564
-	/**
1565
-	 * @return \OCP\Files\IAppData
1566
-	 */
1567
-	public function getAppDataDir($app) {
1568
-		/** @var \OC\Files\AppData\Factory $factory */
1569
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1570
-		return $factory->get($app);
1571
-	}
1572
-
1573
-	/**
1574
-	 * @return \OCP\Lockdown\ILockdownManager
1575
-	 */
1576
-	public function getLockdownManager() {
1577
-		return $this->query('LockdownManager');
1578
-	}
1579
-
1580
-	/**
1581
-	 * @return \OCP\Federation\ICloudIdManager
1582
-	 */
1583
-	public function getCloudIdManager() {
1584
-		return $this->query(ICloudIdManager::class);
1585
-	}
716
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
717
+            if (isset($prefixes['OCA\\Theming\\'])) {
718
+                $classExists = true;
719
+            } else {
720
+                $classExists = false;
721
+            }
722
+
723
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
724
+                return new ThemingDefaults(
725
+                    $c->getConfig(),
726
+                    $c->getL10N('theming'),
727
+                    $c->getURLGenerator(),
728
+                    new \OC_Defaults(),
729
+                    $c->getLazyRootFolder(),
730
+                    $c->getMemCacheFactory()
731
+                );
732
+            }
733
+            return new \OC_Defaults();
734
+        });
735
+        $this->registerService('EventDispatcher', function () {
736
+            return new EventDispatcher();
737
+        });
738
+        $this->registerService('CryptoWrapper', function (Server $c) {
739
+            // FIXME: Instantiiated here due to cyclic dependency
740
+            $request = new Request(
741
+                [
742
+                    'get' => $_GET,
743
+                    'post' => $_POST,
744
+                    'files' => $_FILES,
745
+                    'server' => $_SERVER,
746
+                    'env' => $_ENV,
747
+                    'cookies' => $_COOKIE,
748
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
749
+                        ? $_SERVER['REQUEST_METHOD']
750
+                        : null,
751
+                ],
752
+                $c->getSecureRandom(),
753
+                $c->getConfig()
754
+            );
755
+
756
+            return new CryptoWrapper(
757
+                $c->getConfig(),
758
+                $c->getCrypto(),
759
+                $c->getSecureRandom(),
760
+                $request
761
+            );
762
+        });
763
+        $this->registerService('CsrfTokenManager', function (Server $c) {
764
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
765
+
766
+            return new CsrfTokenManager(
767
+                $tokenGenerator,
768
+                $c->query(SessionStorage::class)
769
+            );
770
+        });
771
+        $this->registerService(SessionStorage::class, function (Server $c) {
772
+            return new SessionStorage($c->getSession());
773
+        });
774
+        $this->registerService('ContentSecurityPolicyManager', function (Server $c) {
775
+            return new ContentSecurityPolicyManager();
776
+        });
777
+        $this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
778
+            return new ContentSecurityPolicyNonceManager(
779
+                $c->getCsrfTokenManager(),
780
+                $c->getRequest()
781
+            );
782
+        });
783
+        $this->registerService('ShareManager', function(Server $c) {
784
+            $config = $c->getConfig();
785
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
786
+            /** @var \OCP\Share\IProviderFactory $factory */
787
+            $factory = new $factoryClass($this);
788
+
789
+            $manager = new \OC\Share20\Manager(
790
+                $c->getLogger(),
791
+                $c->getConfig(),
792
+                $c->getSecureRandom(),
793
+                $c->getHasher(),
794
+                $c->getMountManager(),
795
+                $c->getGroupManager(),
796
+                $c->getL10N('core'),
797
+                $factory,
798
+                $c->getUserManager(),
799
+                $c->getLazyRootFolder(),
800
+                $c->getEventDispatcher()
801
+            );
802
+
803
+            return $manager;
804
+        });
805
+        $this->registerService('SettingsManager', function(Server $c) {
806
+            $manager = new \OC\Settings\Manager(
807
+                $c->getLogger(),
808
+                $c->getDatabaseConnection(),
809
+                $c->getL10N('lib'),
810
+                $c->getConfig(),
811
+                $c->getEncryptionManager(),
812
+                $c->getUserManager(),
813
+                $c->getLockingProvider(),
814
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
815
+                $c->getURLGenerator()
816
+            );
817
+            return $manager;
818
+        });
819
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
820
+            return new \OC\Files\AppData\Factory(
821
+                $c->getRootFolder(),
822
+                $c->getSystemConfig()
823
+            );
824
+        });
825
+
826
+        $this->registerService('LockdownManager', function (Server $c) {
827
+            return new LockdownManager();
828
+        });
829
+
830
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
831
+            return new CloudIdManager();
832
+        });
833
+
834
+        /* To trick DI since we don't extend the DIContainer here */
835
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
836
+            return new CleanPreviewsBackgroundJob(
837
+                $c->getRootFolder(),
838
+                $c->getLogger(),
839
+                $c->getJobList(),
840
+                new TimeFactory()
841
+            );
842
+        });
843
+    }
844
+
845
+    /**
846
+     * @return \OCP\Contacts\IManager
847
+     */
848
+    public function getContactsManager() {
849
+        return $this->query('ContactsManager');
850
+    }
851
+
852
+    /**
853
+     * @return \OC\Encryption\Manager
854
+     */
855
+    public function getEncryptionManager() {
856
+        return $this->query('EncryptionManager');
857
+    }
858
+
859
+    /**
860
+     * @return \OC\Encryption\File
861
+     */
862
+    public function getEncryptionFilesHelper() {
863
+        return $this->query('EncryptionFileHelper');
864
+    }
865
+
866
+    /**
867
+     * @return \OCP\Encryption\Keys\IStorage
868
+     */
869
+    public function getEncryptionKeyStorage() {
870
+        return $this->query('EncryptionKeyStorage');
871
+    }
872
+
873
+    /**
874
+     * The current request object holding all information about the request
875
+     * currently being processed is returned from this method.
876
+     * In case the current execution was not initiated by a web request null is returned
877
+     *
878
+     * @return \OCP\IRequest
879
+     */
880
+    public function getRequest() {
881
+        return $this->query('Request');
882
+    }
883
+
884
+    /**
885
+     * Returns the preview manager which can create preview images for a given file
886
+     *
887
+     * @return \OCP\IPreview
888
+     */
889
+    public function getPreviewManager() {
890
+        return $this->query('PreviewManager');
891
+    }
892
+
893
+    /**
894
+     * Returns the tag manager which can get and set tags for different object types
895
+     *
896
+     * @see \OCP\ITagManager::load()
897
+     * @return \OCP\ITagManager
898
+     */
899
+    public function getTagManager() {
900
+        return $this->query('TagManager');
901
+    }
902
+
903
+    /**
904
+     * Returns the system-tag manager
905
+     *
906
+     * @return \OCP\SystemTag\ISystemTagManager
907
+     *
908
+     * @since 9.0.0
909
+     */
910
+    public function getSystemTagManager() {
911
+        return $this->query('SystemTagManager');
912
+    }
913
+
914
+    /**
915
+     * Returns the system-tag object mapper
916
+     *
917
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
918
+     *
919
+     * @since 9.0.0
920
+     */
921
+    public function getSystemTagObjectMapper() {
922
+        return $this->query('SystemTagObjectMapper');
923
+    }
924
+
925
+    /**
926
+     * Returns the avatar manager, used for avatar functionality
927
+     *
928
+     * @return \OCP\IAvatarManager
929
+     */
930
+    public function getAvatarManager() {
931
+        return $this->query('AvatarManager');
932
+    }
933
+
934
+    /**
935
+     * Returns the root folder of ownCloud's data directory
936
+     *
937
+     * @return \OCP\Files\IRootFolder
938
+     */
939
+    public function getRootFolder() {
940
+        return $this->query('LazyRootFolder');
941
+    }
942
+
943
+    /**
944
+     * Returns the root folder of ownCloud's data directory
945
+     * This is the lazy variant so this gets only initialized once it
946
+     * is actually used.
947
+     *
948
+     * @return \OCP\Files\IRootFolder
949
+     */
950
+    public function getLazyRootFolder() {
951
+        return $this->query('LazyRootFolder');
952
+    }
953
+
954
+    /**
955
+     * Returns a view to ownCloud's files folder
956
+     *
957
+     * @param string $userId user ID
958
+     * @return \OCP\Files\Folder|null
959
+     */
960
+    public function getUserFolder($userId = null) {
961
+        if ($userId === null) {
962
+            $user = $this->getUserSession()->getUser();
963
+            if (!$user) {
964
+                return null;
965
+            }
966
+            $userId = $user->getUID();
967
+        }
968
+        $root = $this->getRootFolder();
969
+        return $root->getUserFolder($userId);
970
+    }
971
+
972
+    /**
973
+     * Returns an app-specific view in ownClouds data directory
974
+     *
975
+     * @return \OCP\Files\Folder
976
+     * @deprecated since 9.2.0 use IAppData
977
+     */
978
+    public function getAppFolder() {
979
+        $dir = '/' . \OC_App::getCurrentApp();
980
+        $root = $this->getRootFolder();
981
+        if (!$root->nodeExists($dir)) {
982
+            $folder = $root->newFolder($dir);
983
+        } else {
984
+            $folder = $root->get($dir);
985
+        }
986
+        return $folder;
987
+    }
988
+
989
+    /**
990
+     * @return \OC\User\Manager
991
+     */
992
+    public function getUserManager() {
993
+        return $this->query('UserManager');
994
+    }
995
+
996
+    /**
997
+     * @return \OC\Group\Manager
998
+     */
999
+    public function getGroupManager() {
1000
+        return $this->query('GroupManager');
1001
+    }
1002
+
1003
+    /**
1004
+     * @return \OC\User\Session
1005
+     */
1006
+    public function getUserSession() {
1007
+        return $this->query('UserSession');
1008
+    }
1009
+
1010
+    /**
1011
+     * @return \OCP\ISession
1012
+     */
1013
+    public function getSession() {
1014
+        return $this->query('UserSession')->getSession();
1015
+    }
1016
+
1017
+    /**
1018
+     * @param \OCP\ISession $session
1019
+     */
1020
+    public function setSession(\OCP\ISession $session) {
1021
+        $this->query(SessionStorage::class)->setSession($session);
1022
+        $this->query('UserSession')->setSession($session);
1023
+        $this->query(Store::class)->setSession($session);
1024
+    }
1025
+
1026
+    /**
1027
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1028
+     */
1029
+    public function getTwoFactorAuthManager() {
1030
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1031
+    }
1032
+
1033
+    /**
1034
+     * @return \OC\NavigationManager
1035
+     */
1036
+    public function getNavigationManager() {
1037
+        return $this->query('NavigationManager');
1038
+    }
1039
+
1040
+    /**
1041
+     * @return \OCP\IConfig
1042
+     */
1043
+    public function getConfig() {
1044
+        return $this->query('AllConfig');
1045
+    }
1046
+
1047
+    /**
1048
+     * @internal For internal use only
1049
+     * @return \OC\SystemConfig
1050
+     */
1051
+    public function getSystemConfig() {
1052
+        return $this->query('SystemConfig');
1053
+    }
1054
+
1055
+    /**
1056
+     * Returns the app config manager
1057
+     *
1058
+     * @return \OCP\IAppConfig
1059
+     */
1060
+    public function getAppConfig() {
1061
+        return $this->query('AppConfig');
1062
+    }
1063
+
1064
+    /**
1065
+     * @return \OCP\L10N\IFactory
1066
+     */
1067
+    public function getL10NFactory() {
1068
+        return $this->query('L10NFactory');
1069
+    }
1070
+
1071
+    /**
1072
+     * get an L10N instance
1073
+     *
1074
+     * @param string $app appid
1075
+     * @param string $lang
1076
+     * @return IL10N
1077
+     */
1078
+    public function getL10N($app, $lang = null) {
1079
+        return $this->getL10NFactory()->get($app, $lang);
1080
+    }
1081
+
1082
+    /**
1083
+     * @return \OCP\IURLGenerator
1084
+     */
1085
+    public function getURLGenerator() {
1086
+        return $this->query('URLGenerator');
1087
+    }
1088
+
1089
+    /**
1090
+     * @return \OCP\IHelper
1091
+     */
1092
+    public function getHelper() {
1093
+        return $this->query('AppHelper');
1094
+    }
1095
+
1096
+    /**
1097
+     * @return AppFetcher
1098
+     */
1099
+    public function getAppFetcher() {
1100
+        return $this->query('AppFetcher');
1101
+    }
1102
+
1103
+    /**
1104
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1105
+     * getMemCacheFactory() instead.
1106
+     *
1107
+     * @return \OCP\ICache
1108
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1109
+     */
1110
+    public function getCache() {
1111
+        return $this->query('UserCache');
1112
+    }
1113
+
1114
+    /**
1115
+     * Returns an \OCP\CacheFactory instance
1116
+     *
1117
+     * @return \OCP\ICacheFactory
1118
+     */
1119
+    public function getMemCacheFactory() {
1120
+        return $this->query('MemCacheFactory');
1121
+    }
1122
+
1123
+    /**
1124
+     * Returns an \OC\RedisFactory instance
1125
+     *
1126
+     * @return \OC\RedisFactory
1127
+     */
1128
+    public function getGetRedisFactory() {
1129
+        return $this->query('RedisFactory');
1130
+    }
1131
+
1132
+
1133
+    /**
1134
+     * Returns the current session
1135
+     *
1136
+     * @return \OCP\IDBConnection
1137
+     */
1138
+    public function getDatabaseConnection() {
1139
+        return $this->query('DatabaseConnection');
1140
+    }
1141
+
1142
+    /**
1143
+     * Returns the activity manager
1144
+     *
1145
+     * @return \OCP\Activity\IManager
1146
+     */
1147
+    public function getActivityManager() {
1148
+        return $this->query('ActivityManager');
1149
+    }
1150
+
1151
+    /**
1152
+     * Returns an job list for controlling background jobs
1153
+     *
1154
+     * @return \OCP\BackgroundJob\IJobList
1155
+     */
1156
+    public function getJobList() {
1157
+        return $this->query('JobList');
1158
+    }
1159
+
1160
+    /**
1161
+     * Returns a logger instance
1162
+     *
1163
+     * @return \OCP\ILogger
1164
+     */
1165
+    public function getLogger() {
1166
+        return $this->query('Logger');
1167
+    }
1168
+
1169
+    /**
1170
+     * Returns a router for generating and matching urls
1171
+     *
1172
+     * @return \OCP\Route\IRouter
1173
+     */
1174
+    public function getRouter() {
1175
+        return $this->query('Router');
1176
+    }
1177
+
1178
+    /**
1179
+     * Returns a search instance
1180
+     *
1181
+     * @return \OCP\ISearch
1182
+     */
1183
+    public function getSearch() {
1184
+        return $this->query('Search');
1185
+    }
1186
+
1187
+    /**
1188
+     * Returns a SecureRandom instance
1189
+     *
1190
+     * @return \OCP\Security\ISecureRandom
1191
+     */
1192
+    public function getSecureRandom() {
1193
+        return $this->query('SecureRandom');
1194
+    }
1195
+
1196
+    /**
1197
+     * Returns a Crypto instance
1198
+     *
1199
+     * @return \OCP\Security\ICrypto
1200
+     */
1201
+    public function getCrypto() {
1202
+        return $this->query('Crypto');
1203
+    }
1204
+
1205
+    /**
1206
+     * Returns a Hasher instance
1207
+     *
1208
+     * @return \OCP\Security\IHasher
1209
+     */
1210
+    public function getHasher() {
1211
+        return $this->query('Hasher');
1212
+    }
1213
+
1214
+    /**
1215
+     * Returns a CredentialsManager instance
1216
+     *
1217
+     * @return \OCP\Security\ICredentialsManager
1218
+     */
1219
+    public function getCredentialsManager() {
1220
+        return $this->query('CredentialsManager');
1221
+    }
1222
+
1223
+    /**
1224
+     * Returns an instance of the HTTP helper class
1225
+     *
1226
+     * @deprecated Use getHTTPClientService()
1227
+     * @return \OC\HTTPHelper
1228
+     */
1229
+    public function getHTTPHelper() {
1230
+        return $this->query('HTTPHelper');
1231
+    }
1232
+
1233
+    /**
1234
+     * Get the certificate manager for the user
1235
+     *
1236
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1237
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1238
+     */
1239
+    public function getCertificateManager($userId = '') {
1240
+        if ($userId === '') {
1241
+            $userSession = $this->getUserSession();
1242
+            $user = $userSession->getUser();
1243
+            if (is_null($user)) {
1244
+                return null;
1245
+            }
1246
+            $userId = $user->getUID();
1247
+        }
1248
+        return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1249
+    }
1250
+
1251
+    /**
1252
+     * Returns an instance of the HTTP client service
1253
+     *
1254
+     * @return \OCP\Http\Client\IClientService
1255
+     */
1256
+    public function getHTTPClientService() {
1257
+        return $this->query('HttpClientService');
1258
+    }
1259
+
1260
+    /**
1261
+     * Create a new event source
1262
+     *
1263
+     * @return \OCP\IEventSource
1264
+     */
1265
+    public function createEventSource() {
1266
+        return new \OC_EventSource();
1267
+    }
1268
+
1269
+    /**
1270
+     * Get the active event logger
1271
+     *
1272
+     * The returned logger only logs data when debug mode is enabled
1273
+     *
1274
+     * @return \OCP\Diagnostics\IEventLogger
1275
+     */
1276
+    public function getEventLogger() {
1277
+        return $this->query('EventLogger');
1278
+    }
1279
+
1280
+    /**
1281
+     * Get the active query logger
1282
+     *
1283
+     * The returned logger only logs data when debug mode is enabled
1284
+     *
1285
+     * @return \OCP\Diagnostics\IQueryLogger
1286
+     */
1287
+    public function getQueryLogger() {
1288
+        return $this->query('QueryLogger');
1289
+    }
1290
+
1291
+    /**
1292
+     * Get the manager for temporary files and folders
1293
+     *
1294
+     * @return \OCP\ITempManager
1295
+     */
1296
+    public function getTempManager() {
1297
+        return $this->query('TempManager');
1298
+    }
1299
+
1300
+    /**
1301
+     * Get the app manager
1302
+     *
1303
+     * @return \OCP\App\IAppManager
1304
+     */
1305
+    public function getAppManager() {
1306
+        return $this->query('AppManager');
1307
+    }
1308
+
1309
+    /**
1310
+     * Creates a new mailer
1311
+     *
1312
+     * @return \OCP\Mail\IMailer
1313
+     */
1314
+    public function getMailer() {
1315
+        return $this->query('Mailer');
1316
+    }
1317
+
1318
+    /**
1319
+     * Get the webroot
1320
+     *
1321
+     * @return string
1322
+     */
1323
+    public function getWebRoot() {
1324
+        return $this->webRoot;
1325
+    }
1326
+
1327
+    /**
1328
+     * @return \OC\OCSClient
1329
+     */
1330
+    public function getOcsClient() {
1331
+        return $this->query('OcsClient');
1332
+    }
1333
+
1334
+    /**
1335
+     * @return \OCP\IDateTimeZone
1336
+     */
1337
+    public function getDateTimeZone() {
1338
+        return $this->query('DateTimeZone');
1339
+    }
1340
+
1341
+    /**
1342
+     * @return \OCP\IDateTimeFormatter
1343
+     */
1344
+    public function getDateTimeFormatter() {
1345
+        return $this->query('DateTimeFormatter');
1346
+    }
1347
+
1348
+    /**
1349
+     * @return \OCP\Files\Config\IMountProviderCollection
1350
+     */
1351
+    public function getMountProviderCollection() {
1352
+        return $this->query('MountConfigManager');
1353
+    }
1354
+
1355
+    /**
1356
+     * Get the IniWrapper
1357
+     *
1358
+     * @return IniGetWrapper
1359
+     */
1360
+    public function getIniWrapper() {
1361
+        return $this->query('IniWrapper');
1362
+    }
1363
+
1364
+    /**
1365
+     * @return \OCP\Command\IBus
1366
+     */
1367
+    public function getCommandBus() {
1368
+        return $this->query('AsyncCommandBus');
1369
+    }
1370
+
1371
+    /**
1372
+     * Get the trusted domain helper
1373
+     *
1374
+     * @return TrustedDomainHelper
1375
+     */
1376
+    public function getTrustedDomainHelper() {
1377
+        return $this->query('TrustedDomainHelper');
1378
+    }
1379
+
1380
+    /**
1381
+     * Get the locking provider
1382
+     *
1383
+     * @return \OCP\Lock\ILockingProvider
1384
+     * @since 8.1.0
1385
+     */
1386
+    public function getLockingProvider() {
1387
+        return $this->query('LockingProvider');
1388
+    }
1389
+
1390
+    /**
1391
+     * @return \OCP\Files\Mount\IMountManager
1392
+     **/
1393
+    function getMountManager() {
1394
+        return $this->query('MountManager');
1395
+    }
1396
+
1397
+    /** @return \OCP\Files\Config\IUserMountCache */
1398
+    function getUserMountCache() {
1399
+        return $this->query('UserMountCache');
1400
+    }
1401
+
1402
+    /**
1403
+     * Get the MimeTypeDetector
1404
+     *
1405
+     * @return \OCP\Files\IMimeTypeDetector
1406
+     */
1407
+    public function getMimeTypeDetector() {
1408
+        return $this->query('MimeTypeDetector');
1409
+    }
1410
+
1411
+    /**
1412
+     * Get the MimeTypeLoader
1413
+     *
1414
+     * @return \OCP\Files\IMimeTypeLoader
1415
+     */
1416
+    public function getMimeTypeLoader() {
1417
+        return $this->query('MimeTypeLoader');
1418
+    }
1419
+
1420
+    /**
1421
+     * Get the manager of all the capabilities
1422
+     *
1423
+     * @return \OC\CapabilitiesManager
1424
+     */
1425
+    public function getCapabilitiesManager() {
1426
+        return $this->query('CapabilitiesManager');
1427
+    }
1428
+
1429
+    /**
1430
+     * Get the EventDispatcher
1431
+     *
1432
+     * @return EventDispatcherInterface
1433
+     * @since 8.2.0
1434
+     */
1435
+    public function getEventDispatcher() {
1436
+        return $this->query('EventDispatcher');
1437
+    }
1438
+
1439
+    /**
1440
+     * Get the Notification Manager
1441
+     *
1442
+     * @return \OCP\Notification\IManager
1443
+     * @since 8.2.0
1444
+     */
1445
+    public function getNotificationManager() {
1446
+        return $this->query('NotificationManager');
1447
+    }
1448
+
1449
+    /**
1450
+     * @return \OCP\Comments\ICommentsManager
1451
+     */
1452
+    public function getCommentsManager() {
1453
+        return $this->query('CommentsManager');
1454
+    }
1455
+
1456
+    /**
1457
+     * @return \OC_Defaults
1458
+     */
1459
+    public function getThemingDefaults() {
1460
+        return $this->query('ThemingDefaults');
1461
+    }
1462
+
1463
+    /**
1464
+     * @return \OC\IntegrityCheck\Checker
1465
+     */
1466
+    public function getIntegrityCodeChecker() {
1467
+        return $this->query('IntegrityCodeChecker');
1468
+    }
1469
+
1470
+    /**
1471
+     * @return \OC\Session\CryptoWrapper
1472
+     */
1473
+    public function getSessionCryptoWrapper() {
1474
+        return $this->query('CryptoWrapper');
1475
+    }
1476
+
1477
+    /**
1478
+     * @return CsrfTokenManager
1479
+     */
1480
+    public function getCsrfTokenManager() {
1481
+        return $this->query('CsrfTokenManager');
1482
+    }
1483
+
1484
+    /**
1485
+     * @return Throttler
1486
+     */
1487
+    public function getBruteForceThrottler() {
1488
+        return $this->query('Throttler');
1489
+    }
1490
+
1491
+    /**
1492
+     * @return IContentSecurityPolicyManager
1493
+     */
1494
+    public function getContentSecurityPolicyManager() {
1495
+        return $this->query('ContentSecurityPolicyManager');
1496
+    }
1497
+
1498
+    /**
1499
+     * @return ContentSecurityPolicyNonceManager
1500
+     */
1501
+    public function getContentSecurityPolicyNonceManager() {
1502
+        return $this->query('ContentSecurityPolicyNonceManager');
1503
+    }
1504
+
1505
+    /**
1506
+     * Not a public API as of 8.2, wait for 9.0
1507
+     *
1508
+     * @return \OCA\Files_External\Service\BackendService
1509
+     */
1510
+    public function getStoragesBackendService() {
1511
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1512
+    }
1513
+
1514
+    /**
1515
+     * Not a public API as of 8.2, wait for 9.0
1516
+     *
1517
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1518
+     */
1519
+    public function getGlobalStoragesService() {
1520
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1521
+    }
1522
+
1523
+    /**
1524
+     * Not a public API as of 8.2, wait for 9.0
1525
+     *
1526
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1527
+     */
1528
+    public function getUserGlobalStoragesService() {
1529
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1530
+    }
1531
+
1532
+    /**
1533
+     * Not a public API as of 8.2, wait for 9.0
1534
+     *
1535
+     * @return \OCA\Files_External\Service\UserStoragesService
1536
+     */
1537
+    public function getUserStoragesService() {
1538
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1539
+    }
1540
+
1541
+    /**
1542
+     * @return \OCP\Share\IManager
1543
+     */
1544
+    public function getShareManager() {
1545
+        return $this->query('ShareManager');
1546
+    }
1547
+
1548
+    /**
1549
+     * Returns the LDAP Provider
1550
+     *
1551
+     * @return \OCP\LDAP\ILDAPProvider
1552
+     */
1553
+    public function getLDAPProvider() {
1554
+        return $this->query('LDAPProvider');
1555
+    }
1556
+
1557
+    /**
1558
+     * @return \OCP\Settings\IManager
1559
+     */
1560
+    public function getSettingsManager() {
1561
+        return $this->query('SettingsManager');
1562
+    }
1563
+
1564
+    /**
1565
+     * @return \OCP\Files\IAppData
1566
+     */
1567
+    public function getAppDataDir($app) {
1568
+        /** @var \OC\Files\AppData\Factory $factory */
1569
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1570
+        return $factory->get($app);
1571
+    }
1572
+
1573
+    /**
1574
+     * @return \OCP\Lockdown\ILockdownManager
1575
+     */
1576
+    public function getLockdownManager() {
1577
+        return $this->query('LockdownManager');
1578
+    }
1579
+
1580
+    /**
1581
+     * @return \OCP\Federation\ICloudIdManager
1582
+     */
1583
+    public function getCloudIdManager() {
1584
+        return $this->query(ICloudIdManager::class);
1585
+    }
1586 1586
 }
Please login to merge, or discard this patch.
Spacing   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -119,11 +119,11 @@  discard block
 block discarded – undo
119 119
 		parent::__construct();
120 120
 		$this->webRoot = $webRoot;
121 121
 
122
-		$this->registerService('ContactsManager', function ($c) {
122
+		$this->registerService('ContactsManager', function($c) {
123 123
 			return new ContactsManager();
124 124
 		});
125 125
 
126
-		$this->registerService('PreviewManager', function (Server $c) {
126
+		$this->registerService('PreviewManager', function(Server $c) {
127 127
 			return new PreviewManager(
128 128
 				$c->getConfig(),
129 129
 				$c->getRootFolder(),
@@ -133,13 +133,13 @@  discard block
 block discarded – undo
133 133
 			);
134 134
 		});
135 135
 
136
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
136
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
137 137
 			return new \OC\Preview\Watcher(
138 138
 				$c->getAppDataDir('preview')
139 139
 			);
140 140
 		});
141 141
 
142
-		$this->registerService('EncryptionManager', function (Server $c) {
142
+		$this->registerService('EncryptionManager', function(Server $c) {
143 143
 			$view = new View();
144 144
 			$util = new Encryption\Util(
145 145
 				$view,
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 			);
158 158
 		});
159 159
 
160
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
160
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
161 161
 			$util = new Encryption\Util(
162 162
 				new View(),
163 163
 				$c->getUserManager(),
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 			return new Encryption\File($util);
168 168
 		});
169 169
 
170
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
170
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
171 171
 			$view = new View();
172 172
 			$util = new Encryption\Util(
173 173
 				$view,
@@ -178,27 +178,27 @@  discard block
 block discarded – undo
178 178
 
179 179
 			return new Encryption\Keys\Storage($view, $util);
180 180
 		});
181
-		$this->registerService('TagMapper', function (Server $c) {
181
+		$this->registerService('TagMapper', function(Server $c) {
182 182
 			return new TagMapper($c->getDatabaseConnection());
183 183
 		});
184
-		$this->registerService('TagManager', function (Server $c) {
184
+		$this->registerService('TagManager', function(Server $c) {
185 185
 			$tagMapper = $c->query('TagMapper');
186 186
 			return new TagManager($tagMapper, $c->getUserSession());
187 187
 		});
188
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
188
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
189 189
 			$config = $c->getConfig();
190 190
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
191 191
 			/** @var \OC\SystemTag\ManagerFactory $factory */
192 192
 			$factory = new $factoryClass($this);
193 193
 			return $factory;
194 194
 		});
195
-		$this->registerService('SystemTagManager', function (Server $c) {
195
+		$this->registerService('SystemTagManager', function(Server $c) {
196 196
 			return $c->query('SystemTagManagerFactory')->getManager();
197 197
 		});
198
-		$this->registerService('SystemTagObjectMapper', function (Server $c) {
198
+		$this->registerService('SystemTagObjectMapper', function(Server $c) {
199 199
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
200 200
 		});
201
-		$this->registerService('RootFolder', function (Server $c) {
201
+		$this->registerService('RootFolder', function(Server $c) {
202 202
 			$manager = \OC\Files\Filesystem::getMountManager(null);
203 203
 			$view = new View();
204 204
 			$root = new Root(
@@ -222,28 +222,28 @@  discard block
 block discarded – undo
222 222
 				return $c->query('RootFolder');
223 223
 			});
224 224
 		});
225
-		$this->registerService('UserManager', function (Server $c) {
225
+		$this->registerService('UserManager', function(Server $c) {
226 226
 			$config = $c->getConfig();
227 227
 			return new \OC\User\Manager($config);
228 228
 		});
229
-		$this->registerService('GroupManager', function (Server $c) {
229
+		$this->registerService('GroupManager', function(Server $c) {
230 230
 			$groupManager = new \OC\Group\Manager($this->getUserManager());
231
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
231
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
232 232
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
233 233
 			});
234
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
234
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
235 235
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
236 236
 			});
237
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
237
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
238 238
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
239 239
 			});
240
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
240
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
241 241
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
242 242
 			});
243
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
243
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
244 244
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
245 245
 			});
246
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
246
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
247 247
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
248 248
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
249 249
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -261,11 +261,11 @@  discard block
 block discarded – undo
261 261
 			return new Store($session, $logger, $tokenProvider);
262 262
 		});
263 263
 		$this->registerAlias(IStore::class, Store::class);
264
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
264
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
265 265
 			$dbConnection = $c->getDatabaseConnection();
266 266
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
267 267
 		});
268
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
268
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
269 269
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
270 270
 			$crypto = $c->getCrypto();
271 271
 			$config = $c->getConfig();
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
 			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
275 275
 		});
276 276
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
277
-		$this->registerService('UserSession', function (Server $c) {
277
+		$this->registerService('UserSession', function(Server $c) {
278 278
 			$manager = $c->getUserManager();
279 279
 			$session = new \OC\Session\Memory('');
280 280
 			$timeFactory = new TimeFactory();
@@ -287,69 +287,69 @@  discard block
 block discarded – undo
287 287
 			}
288 288
 
289 289
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom());
290
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
290
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
291 291
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
292 292
 			});
293
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
293
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
294 294
 				/** @var $user \OC\User\User */
295 295
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
296 296
 			});
297
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
297
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
298 298
 				/** @var $user \OC\User\User */
299 299
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
300 300
 			});
301
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
301
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
302 302
 				/** @var $user \OC\User\User */
303 303
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
304 304
 			});
305
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
305
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
306 306
 				/** @var $user \OC\User\User */
307 307
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
308 308
 			});
309
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
309
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
310 310
 				/** @var $user \OC\User\User */
311 311
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
312 312
 			});
313
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
313
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
314 314
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
315 315
 			});
316
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
316
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
317 317
 				/** @var $user \OC\User\User */
318 318
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
319 319
 			});
320
-			$userSession->listen('\OC\User', 'logout', function () {
320
+			$userSession->listen('\OC\User', 'logout', function() {
321 321
 				\OC_Hook::emit('OC_User', 'logout', array());
322 322
 			});
323
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
323
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value) {
324 324
 				/** @var $user \OC\User\User */
325 325
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
326 326
 			});
327 327
 			return $userSession;
328 328
 		});
329 329
 
330
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
330
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
331 331
 			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
332 332
 		});
333 333
 
334
-		$this->registerService('NavigationManager', function (Server $c) {
334
+		$this->registerService('NavigationManager', function(Server $c) {
335 335
 			return new \OC\NavigationManager($c->getAppManager(),
336 336
 				$c->getURLGenerator(),
337 337
 				$c->getL10NFactory(),
338 338
 				$c->getUserSession(),
339 339
 				$c->getGroupManager());
340 340
 		});
341
-		$this->registerService('AllConfig', function (Server $c) {
341
+		$this->registerService('AllConfig', function(Server $c) {
342 342
 			return new \OC\AllConfig(
343 343
 				$c->getSystemConfig()
344 344
 			);
345 345
 		});
346
-		$this->registerService('SystemConfig', function ($c) use ($config) {
346
+		$this->registerService('SystemConfig', function($c) use ($config) {
347 347
 			return new \OC\SystemConfig($config);
348 348
 		});
349
-		$this->registerService('AppConfig', function (Server $c) {
349
+		$this->registerService('AppConfig', function(Server $c) {
350 350
 			return new \OC\AppConfig($c->getDatabaseConnection());
351 351
 		});
352
-		$this->registerService('L10NFactory', function (Server $c) {
352
+		$this->registerService('L10NFactory', function(Server $c) {
353 353
 			return new \OC\L10N\Factory(
354 354
 				$c->getConfig(),
355 355
 				$c->getRequest(),
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 				\OC::$SERVERROOT
358 358
 			);
359 359
 		});
360
-		$this->registerService('URLGenerator', function (Server $c) {
360
+		$this->registerService('URLGenerator', function(Server $c) {
361 361
 			$config = $c->getConfig();
362 362
 			$cacheFactory = $c->getMemCacheFactory();
363 363
 			return new \OC\URLGenerator(
@@ -365,10 +365,10 @@  discard block
 block discarded – undo
365 365
 				$cacheFactory
366 366
 			);
367 367
 		});
368
-		$this->registerService('AppHelper', function ($c) {
368
+		$this->registerService('AppHelper', function($c) {
369 369
 			return new \OC\AppHelper();
370 370
 		});
371
-		$this->registerService('AppFetcher', function ($c) {
371
+		$this->registerService('AppFetcher', function($c) {
372 372
 			return new AppFetcher(
373 373
 				$this->getAppDataDir('appstore'),
374 374
 				$this->getHTTPClientService(),
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
 				$this->getConfig()
377 377
 			);
378 378
 		});
379
-		$this->registerService('CategoryFetcher', function ($c) {
379
+		$this->registerService('CategoryFetcher', function($c) {
380 380
 			return new CategoryFetcher(
381 381
 				$this->getAppDataDir('appstore'),
382 382
 				$this->getHTTPClientService(),
@@ -384,19 +384,19 @@  discard block
 block discarded – undo
384 384
 				$this->getConfig()
385 385
 			);
386 386
 		});
387
-		$this->registerService('UserCache', function ($c) {
387
+		$this->registerService('UserCache', function($c) {
388 388
 			return new Cache\File();
389 389
 		});
390
-		$this->registerService('MemCacheFactory', function (Server $c) {
390
+		$this->registerService('MemCacheFactory', function(Server $c) {
391 391
 			$config = $c->getConfig();
392 392
 
393 393
 			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
394 394
 				$v = \OC_App::getAppVersions();
395
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
395
+				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT.'/version.php'));
396 396
 				$version = implode(',', $v);
397 397
 				$instanceId = \OC_Util::getInstanceId();
398 398
 				$path = \OC::$SERVERROOT;
399
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
399
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.\OC::$WEBROOT);
400 400
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
401 401
 					$config->getSystemValue('memcache.local', null),
402 402
 					$config->getSystemValue('memcache.distributed', null),
@@ -410,11 +410,11 @@  discard block
 block discarded – undo
410 410
 				'\\OC\\Memcache\\ArrayCache'
411 411
 			);
412 412
 		});
413
-		$this->registerService('RedisFactory', function (Server $c) {
413
+		$this->registerService('RedisFactory', function(Server $c) {
414 414
 			$systemConfig = $c->getSystemConfig();
415 415
 			return new RedisFactory($systemConfig);
416 416
 		});
417
-		$this->registerService('ActivityManager', function (Server $c) {
417
+		$this->registerService('ActivityManager', function(Server $c) {
418 418
 			return new \OC\Activity\Manager(
419 419
 				$c->getRequest(),
420 420
 				$c->getUserSession(),
@@ -422,13 +422,13 @@  discard block
 block discarded – undo
422 422
 				$c->query(IValidator::class)
423 423
 			);
424 424
 		});
425
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
425
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
426 426
 			return new \OC\Activity\EventMerger(
427 427
 				$c->getL10N('lib')
428 428
 			);
429 429
 		});
430 430
 		$this->registerAlias(IValidator::class, Validator::class);
431
-		$this->registerService('AvatarManager', function (Server $c) {
431
+		$this->registerService('AvatarManager', function(Server $c) {
432 432
 			return new AvatarManager(
433 433
 				$c->getUserManager(),
434 434
 				$c->getAppDataDir('avatar'),
@@ -437,14 +437,14 @@  discard block
 block discarded – undo
437 437
 				$c->getConfig()
438 438
 			);
439 439
 		});
440
-		$this->registerService('Logger', function (Server $c) {
440
+		$this->registerService('Logger', function(Server $c) {
441 441
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
442 442
 			$logger = Log::getLogClass($logType);
443 443
 			call_user_func(array($logger, 'init'));
444 444
 
445 445
 			return new Log($logger);
446 446
 		});
447
-		$this->registerService('JobList', function (Server $c) {
447
+		$this->registerService('JobList', function(Server $c) {
448 448
 			$config = $c->getConfig();
449 449
 			return new \OC\BackgroundJob\JobList(
450 450
 				$c->getDatabaseConnection(),
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
 				new TimeFactory()
453 453
 			);
454 454
 		});
455
-		$this->registerService('Router', function (Server $c) {
455
+		$this->registerService('Router', function(Server $c) {
456 456
 			$cacheFactory = $c->getMemCacheFactory();
457 457
 			$logger = $c->getLogger();
458 458
 			if ($cacheFactory->isAvailable()) {
@@ -462,22 +462,22 @@  discard block
 block discarded – undo
462 462
 			}
463 463
 			return $router;
464 464
 		});
465
-		$this->registerService('Search', function ($c) {
465
+		$this->registerService('Search', function($c) {
466 466
 			return new Search();
467 467
 		});
468
-		$this->registerService('SecureRandom', function ($c) {
468
+		$this->registerService('SecureRandom', function($c) {
469 469
 			return new SecureRandom();
470 470
 		});
471
-		$this->registerService('Crypto', function (Server $c) {
471
+		$this->registerService('Crypto', function(Server $c) {
472 472
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
473 473
 		});
474
-		$this->registerService('Hasher', function (Server $c) {
474
+		$this->registerService('Hasher', function(Server $c) {
475 475
 			return new Hasher($c->getConfig());
476 476
 		});
477
-		$this->registerService('CredentialsManager', function (Server $c) {
477
+		$this->registerService('CredentialsManager', function(Server $c) {
478 478
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
479 479
 		});
480
-		$this->registerService('DatabaseConnection', function (Server $c) {
480
+		$this->registerService('DatabaseConnection', function(Server $c) {
481 481
 			$systemConfig = $c->getSystemConfig();
482 482
 			$factory = new \OC\DB\ConnectionFactory($c->getConfig());
483 483
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -489,14 +489,14 @@  discard block
 block discarded – undo
489 489
 			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
490 490
 			return $connection;
491 491
 		});
492
-		$this->registerService('HTTPHelper', function (Server $c) {
492
+		$this->registerService('HTTPHelper', function(Server $c) {
493 493
 			$config = $c->getConfig();
494 494
 			return new HTTPHelper(
495 495
 				$config,
496 496
 				$c->getHTTPClientService()
497 497
 			);
498 498
 		});
499
-		$this->registerService('HttpClientService', function (Server $c) {
499
+		$this->registerService('HttpClientService', function(Server $c) {
500 500
 			$user = \OC_User::getUser();
501 501
 			$uid = $user ? $user : null;
502 502
 			return new ClientService(
@@ -504,27 +504,27 @@  discard block
 block discarded – undo
504 504
 				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
505 505
 			);
506 506
 		});
507
-		$this->registerService('EventLogger', function (Server $c) {
507
+		$this->registerService('EventLogger', function(Server $c) {
508 508
 			if ($c->getSystemConfig()->getValue('debug', false)) {
509 509
 				return new EventLogger();
510 510
 			} else {
511 511
 				return new NullEventLogger();
512 512
 			}
513 513
 		});
514
-		$this->registerService('QueryLogger', function (Server $c) {
514
+		$this->registerService('QueryLogger', function(Server $c) {
515 515
 			if ($c->getSystemConfig()->getValue('debug', false)) {
516 516
 				return new QueryLogger();
517 517
 			} else {
518 518
 				return new NullQueryLogger();
519 519
 			}
520 520
 		});
521
-		$this->registerService('TempManager', function (Server $c) {
521
+		$this->registerService('TempManager', function(Server $c) {
522 522
 			return new TempManager(
523 523
 				$c->getLogger(),
524 524
 				$c->getConfig()
525 525
 			);
526 526
 		});
527
-		$this->registerService('AppManager', function (Server $c) {
527
+		$this->registerService('AppManager', function(Server $c) {
528 528
 			return new \OC\App\AppManager(
529 529
 				$c->getUserSession(),
530 530
 				$c->getAppConfig(),
@@ -533,13 +533,13 @@  discard block
 block discarded – undo
533 533
 				$c->getEventDispatcher()
534 534
 			);
535 535
 		});
536
-		$this->registerService('DateTimeZone', function (Server $c) {
536
+		$this->registerService('DateTimeZone', function(Server $c) {
537 537
 			return new DateTimeZone(
538 538
 				$c->getConfig(),
539 539
 				$c->getSession()
540 540
 			);
541 541
 		});
542
-		$this->registerService('DateTimeFormatter', function (Server $c) {
542
+		$this->registerService('DateTimeFormatter', function(Server $c) {
543 543
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
544 544
 
545 545
 			return new DateTimeFormatter(
@@ -547,16 +547,16 @@  discard block
 block discarded – undo
547 547
 				$c->getL10N('lib', $language)
548 548
 			);
549 549
 		});
550
-		$this->registerService('UserMountCache', function (Server $c) {
550
+		$this->registerService('UserMountCache', function(Server $c) {
551 551
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
552 552
 			$listener = new UserMountCacheListener($mountCache);
553 553
 			$listener->listen($c->getUserManager());
554 554
 			return $mountCache;
555 555
 		});
556
-		$this->registerService('MountConfigManager', function (Server $c) {
556
+		$this->registerService('MountConfigManager', function(Server $c) {
557 557
 			$loader = \OC\Files\Filesystem::getLoader();
558 558
 			$mountCache = $c->query('UserMountCache');
559
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
559
+			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
560 560
 
561 561
 			// builtin providers
562 562
 
@@ -567,14 +567,14 @@  discard block
 block discarded – undo
567 567
 
568 568
 			return $manager;
569 569
 		});
570
-		$this->registerService('IniWrapper', function ($c) {
570
+		$this->registerService('IniWrapper', function($c) {
571 571
 			return new IniGetWrapper();
572 572
 		});
573
-		$this->registerService('AsyncCommandBus', function (Server $c) {
573
+		$this->registerService('AsyncCommandBus', function(Server $c) {
574 574
 			$jobList = $c->getJobList();
575 575
 			return new AsyncBus($jobList);
576 576
 		});
577
-		$this->registerService('TrustedDomainHelper', function ($c) {
577
+		$this->registerService('TrustedDomainHelper', function($c) {
578 578
 			return new TrustedDomainHelper($this->getConfig());
579 579
 		});
580 580
 		$this->registerService('Throttler', function(Server $c) {
@@ -585,10 +585,10 @@  discard block
 block discarded – undo
585 585
 				$c->getConfig()
586 586
 			);
587 587
 		});
588
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
588
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
589 589
 			// IConfig and IAppManager requires a working database. This code
590 590
 			// might however be called when ownCloud is not yet setup.
591
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
591
+			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
592 592
 				$config = $c->getConfig();
593 593
 				$appManager = $c->getAppManager();
594 594
 			} else {
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
 					$c->getTempManager()
607 607
 			);
608 608
 		});
609
-		$this->registerService('Request', function ($c) {
609
+		$this->registerService('Request', function($c) {
610 610
 			if (isset($this['urlParams'])) {
611 611
 				$urlParams = $this['urlParams'];
612 612
 			} else {
@@ -640,7 +640,7 @@  discard block
 block discarded – undo
640 640
 				$stream
641 641
 			);
642 642
 		});
643
-		$this->registerService('Mailer', function (Server $c) {
643
+		$this->registerService('Mailer', function(Server $c) {
644 644
 			return new Mailer(
645 645
 				$c->getConfig(),
646 646
 				$c->getLogger(),
@@ -650,14 +650,14 @@  discard block
 block discarded – undo
650 650
 		$this->registerService('LDAPProvider', function(Server $c) {
651 651
 			$config = $c->getConfig();
652 652
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
653
-			if(is_null($factoryClass)) {
653
+			if (is_null($factoryClass)) {
654 654
 				throw new \Exception('ldapProviderFactory not set');
655 655
 			}
656 656
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
657 657
 			$factory = new $factoryClass($this);
658 658
 			return $factory->getLDAPProvider();
659 659
 		});
660
-		$this->registerService('LockingProvider', function (Server $c) {
660
+		$this->registerService('LockingProvider', function(Server $c) {
661 661
 			$ini = $c->getIniWrapper();
662 662
 			$config = $c->getConfig();
663 663
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -672,29 +672,29 @@  discard block
 block discarded – undo
672 672
 			}
673 673
 			return new NoopLockingProvider();
674 674
 		});
675
-		$this->registerService('MountManager', function () {
675
+		$this->registerService('MountManager', function() {
676 676
 			return new \OC\Files\Mount\Manager();
677 677
 		});
678
-		$this->registerService('MimeTypeDetector', function (Server $c) {
678
+		$this->registerService('MimeTypeDetector', function(Server $c) {
679 679
 			return new \OC\Files\Type\Detection(
680 680
 				$c->getURLGenerator(),
681 681
 				\OC::$configDir,
682
-				\OC::$SERVERROOT . '/resources/config/'
682
+				\OC::$SERVERROOT.'/resources/config/'
683 683
 			);
684 684
 		});
685
-		$this->registerService('MimeTypeLoader', function (Server $c) {
685
+		$this->registerService('MimeTypeLoader', function(Server $c) {
686 686
 			return new \OC\Files\Type\Loader(
687 687
 				$c->getDatabaseConnection()
688 688
 			);
689 689
 		});
690
-		$this->registerService('NotificationManager', function (Server $c) {
690
+		$this->registerService('NotificationManager', function(Server $c) {
691 691
 			return new Manager(
692 692
 				$c->query(IValidator::class)
693 693
 			);
694 694
 		});
695
-		$this->registerService('CapabilitiesManager', function (Server $c) {
695
+		$this->registerService('CapabilitiesManager', function(Server $c) {
696 696
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
697
-			$manager->registerCapability(function () use ($c) {
697
+			$manager->registerCapability(function() use ($c) {
698 698
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
699 699
 			});
700 700
 			return $manager;
@@ -732,10 +732,10 @@  discard block
 block discarded – undo
732 732
 			}
733 733
 			return new \OC_Defaults();
734 734
 		});
735
-		$this->registerService('EventDispatcher', function () {
735
+		$this->registerService('EventDispatcher', function() {
736 736
 			return new EventDispatcher();
737 737
 		});
738
-		$this->registerService('CryptoWrapper', function (Server $c) {
738
+		$this->registerService('CryptoWrapper', function(Server $c) {
739 739
 			// FIXME: Instantiiated here due to cyclic dependency
740 740
 			$request = new Request(
741 741
 				[
@@ -760,7 +760,7 @@  discard block
 block discarded – undo
760 760
 				$request
761 761
 			);
762 762
 		});
763
-		$this->registerService('CsrfTokenManager', function (Server $c) {
763
+		$this->registerService('CsrfTokenManager', function(Server $c) {
764 764
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
765 765
 
766 766
 			return new CsrfTokenManager(
@@ -768,10 +768,10 @@  discard block
 block discarded – undo
768 768
 				$c->query(SessionStorage::class)
769 769
 			);
770 770
 		});
771
-		$this->registerService(SessionStorage::class, function (Server $c) {
771
+		$this->registerService(SessionStorage::class, function(Server $c) {
772 772
 			return new SessionStorage($c->getSession());
773 773
 		});
774
-		$this->registerService('ContentSecurityPolicyManager', function (Server $c) {
774
+		$this->registerService('ContentSecurityPolicyManager', function(Server $c) {
775 775
 			return new ContentSecurityPolicyManager();
776 776
 		});
777 777
 		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
@@ -816,23 +816,23 @@  discard block
 block discarded – undo
816 816
 			);
817 817
 			return $manager;
818 818
 		});
819
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
819
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
820 820
 			return new \OC\Files\AppData\Factory(
821 821
 				$c->getRootFolder(),
822 822
 				$c->getSystemConfig()
823 823
 			);
824 824
 		});
825 825
 
826
-		$this->registerService('LockdownManager', function (Server $c) {
826
+		$this->registerService('LockdownManager', function(Server $c) {
827 827
 			return new LockdownManager();
828 828
 		});
829 829
 
830
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
830
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
831 831
 			return new CloudIdManager();
832 832
 		});
833 833
 
834 834
 		/* To trick DI since we don't extend the DIContainer here */
835
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
835
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
836 836
 			return new CleanPreviewsBackgroundJob(
837 837
 				$c->getRootFolder(),
838 838
 				$c->getLogger(),
@@ -976,7 +976,7 @@  discard block
 block discarded – undo
976 976
 	 * @deprecated since 9.2.0 use IAppData
977 977
 	 */
978 978
 	public function getAppFolder() {
979
-		$dir = '/' . \OC_App::getCurrentApp();
979
+		$dir = '/'.\OC_App::getCurrentApp();
980 980
 		$root = $this->getRootFolder();
981 981
 		if (!$root->nodeExists($dir)) {
982 982
 			$folder = $root->newFolder($dir);
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/Response.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 
227 227
 	/**
228 228
 	 * By default renders no output
229
-	 * @return null
229
+	 * @return string
230 230
 	 * @since 6.0.0
231 231
 	 */
232 232
 	public function render() {
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 
260 260
 	/**
261 261
 	 * Get the currently used Content-Security-Policy
262
-	 * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
262
+	 * @return ContentSecurityPolicy|null Used Content-Security-Policy or null if
263 263
 	 *                                    none specified.
264 264
 	 * @since 8.1.0
265 265
 	 */
Please login to merge, or discard this patch.
Indentation   +279 added lines, -279 removed lines patch added patch discarded remove patch
@@ -42,285 +42,285 @@
 block discarded – undo
42 42
  */
43 43
 class Response {
44 44
 
45
-	/**
46
-	 * Headers - defaults to ['Cache-Control' => 'no-cache, no-store, must-revalidate']
47
-	 * @var array
48
-	 */
49
-	private $headers = array(
50
-		'Cache-Control' => 'no-cache, no-store, must-revalidate'
51
-	);
52
-
53
-
54
-	/**
55
-	 * Cookies that will be need to be constructed as header
56
-	 * @var array
57
-	 */
58
-	private $cookies = array();
59
-
60
-
61
-	/**
62
-	 * HTTP status code - defaults to STATUS OK
63
-	 * @var int
64
-	 */
65
-	private $status = Http::STATUS_OK;
66
-
67
-
68
-	/**
69
-	 * Last modified date
70
-	 * @var \DateTime
71
-	 */
72
-	private $lastModified;
73
-
74
-
75
-	/**
76
-	 * ETag
77
-	 * @var string
78
-	 */
79
-	private $ETag;
80
-
81
-	/** @var ContentSecurityPolicy|null Used Content-Security-Policy */
82
-	private $contentSecurityPolicy = null;
83
-
84
-
85
-	/**
86
-	 * Caches the response
87
-	 * @param int $cacheSeconds the amount of seconds that should be cached
88
-	 * if 0 then caching will be disabled
89
-	 * @return $this
90
-	 * @since 6.0.0 - return value was added in 7.0.0
91
-	 */
92
-	public function cacheFor($cacheSeconds) {
93
-
94
-		if($cacheSeconds > 0) {
95
-			$this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
96
-		} else {
97
-			$this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
98
-		}
99
-
100
-		return $this;
101
-	}
102
-
103
-	/**
104
-	 * Adds a new cookie to the response
105
-	 * @param string $name The name of the cookie
106
-	 * @param string $value The value of the cookie
107
-	 * @param \DateTime|null $expireDate Date on that the cookie should expire, if set
108
-	 * 									to null cookie will be considered as session
109
-	 * 									cookie.
110
-	 * @return $this
111
-	 * @since 8.0.0
112
-	 */
113
-	public function addCookie($name, $value, \DateTime $expireDate = null) {
114
-		$this->cookies[$name] = array('value' => $value, 'expireDate' => $expireDate);
115
-		return $this;
116
-	}
117
-
118
-
119
-	/**
120
-	 * Set the specified cookies
121
-	 * @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
122
-	 * @return $this
123
-	 * @since 8.0.0
124
-	 */
125
-	public function setCookies(array $cookies) {
126
-		$this->cookies = $cookies;
127
-		return $this;
128
-	}
129
-
130
-
131
-	/**
132
-	 * Invalidates the specified cookie
133
-	 * @param string $name
134
-	 * @return $this
135
-	 * @since 8.0.0
136
-	 */
137
-	public function invalidateCookie($name) {
138
-		$this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
139
-		return $this;
140
-	}
141
-
142
-	/**
143
-	 * Invalidates the specified cookies
144
-	 * @param array $cookieNames array('foo', 'bar')
145
-	 * @return $this
146
-	 * @since 8.0.0
147
-	 */
148
-	public function invalidateCookies(array $cookieNames) {
149
-		foreach($cookieNames as $cookieName) {
150
-			$this->invalidateCookie($cookieName);
151
-		}
152
-		return $this;
153
-	}
154
-
155
-	/**
156
-	 * Returns the cookies
157
-	 * @return array
158
-	 * @since 8.0.0
159
-	 */
160
-	public function getCookies() {
161
-		return $this->cookies;
162
-	}
163
-
164
-	/**
165
-	 * Adds a new header to the response that will be called before the render
166
-	 * function
167
-	 * @param string $name The name of the HTTP header
168
-	 * @param string $value The value, null will delete it
169
-	 * @return $this
170
-	 * @since 6.0.0 - return value was added in 7.0.0
171
-	 */
172
-	public function addHeader($name, $value) {
173
-		$name = trim($name);  // always remove leading and trailing whitespace
174
-		                      // to be able to reliably check for security
175
-		                      // headers
176
-
177
-		if(is_null($value)) {
178
-			unset($this->headers[$name]);
179
-		} else {
180
-			$this->headers[$name] = $value;
181
-		}
182
-
183
-		return $this;
184
-	}
185
-
186
-
187
-	/**
188
-	 * Set the headers
189
-	 * @param array $headers value header pairs
190
-	 * @return $this
191
-	 * @since 8.0.0
192
-	 */
193
-	public function setHeaders(array $headers) {
194
-		$this->headers = $headers;
195
-
196
-		return $this;
197
-	}
198
-
199
-
200
-	/**
201
-	 * Returns the set headers
202
-	 * @return array the headers
203
-	 * @since 6.0.0
204
-	 */
205
-	public function getHeaders() {
206
-		$mergeWith = [];
207
-
208
-		if($this->lastModified) {
209
-			$mergeWith['Last-Modified'] =
210
-				$this->lastModified->format(\DateTime::RFC2822);
211
-		}
212
-
213
-		// Build Content-Security-Policy and use default if none has been specified
214
-		if(is_null($this->contentSecurityPolicy)) {
215
-			$this->setContentSecurityPolicy(new ContentSecurityPolicy());
216
-		}
217
-		$this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
218
-
219
-		if($this->ETag) {
220
-			$mergeWith['ETag'] = '"' . $this->ETag . '"';
221
-		}
222
-
223
-		return array_merge($mergeWith, $this->headers);
224
-	}
225
-
226
-
227
-	/**
228
-	 * By default renders no output
229
-	 * @return null
230
-	 * @since 6.0.0
231
-	 */
232
-	public function render() {
233
-		return null;
234
-	}
235
-
236
-
237
-	/**
238
-	 * Set response status
239
-	 * @param int $status a HTTP status code, see also the STATUS constants
240
-	 * @return Response Reference to this object
241
-	 * @since 6.0.0 - return value was added in 7.0.0
242
-	 */
243
-	public function setStatus($status) {
244
-		$this->status = $status;
245
-
246
-		return $this;
247
-	}
248
-
249
-	/**
250
-	 * Set a Content-Security-Policy
251
-	 * @param EmptyContentSecurityPolicy $csp Policy to set for the response object
252
-	 * @return $this
253
-	 * @since 8.1.0
254
-	 */
255
-	public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
256
-		$this->contentSecurityPolicy = $csp;
257
-		return $this;
258
-	}
259
-
260
-	/**
261
-	 * Get the currently used Content-Security-Policy
262
-	 * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
263
-	 *                                    none specified.
264
-	 * @since 8.1.0
265
-	 */
266
-	public function getContentSecurityPolicy() {
267
-		return $this->contentSecurityPolicy;
268
-	}
269
-
270
-
271
-	/**
272
-	 * Get response status
273
-	 * @since 6.0.0
274
-	 */
275
-	public function getStatus() {
276
-		return $this->status;
277
-	}
278
-
279
-
280
-	/**
281
-	 * Get the ETag
282
-	 * @return string the etag
283
-	 * @since 6.0.0
284
-	 */
285
-	public function getETag() {
286
-		return $this->ETag;
287
-	}
288
-
289
-
290
-	/**
291
-	 * Get "last modified" date
292
-	 * @return \DateTime RFC2822 formatted last modified date
293
-	 * @since 6.0.0
294
-	 */
295
-	public function getLastModified() {
296
-		return $this->lastModified;
297
-	}
298
-
299
-
300
-	/**
301
-	 * Set the ETag
302
-	 * @param string $ETag
303
-	 * @return Response Reference to this object
304
-	 * @since 6.0.0 - return value was added in 7.0.0
305
-	 */
306
-	public function setETag($ETag) {
307
-		$this->ETag = $ETag;
308
-
309
-		return $this;
310
-	}
311
-
312
-
313
-	/**
314
-	 * Set "last modified" date
315
-	 * @param \DateTime $lastModified
316
-	 * @return Response Reference to this object
317
-	 * @since 6.0.0 - return value was added in 7.0.0
318
-	 */
319
-	public function setLastModified($lastModified) {
320
-		$this->lastModified = $lastModified;
321
-
322
-		return $this;
323
-	}
45
+    /**
46
+     * Headers - defaults to ['Cache-Control' => 'no-cache, no-store, must-revalidate']
47
+     * @var array
48
+     */
49
+    private $headers = array(
50
+        'Cache-Control' => 'no-cache, no-store, must-revalidate'
51
+    );
52
+
53
+
54
+    /**
55
+     * Cookies that will be need to be constructed as header
56
+     * @var array
57
+     */
58
+    private $cookies = array();
59
+
60
+
61
+    /**
62
+     * HTTP status code - defaults to STATUS OK
63
+     * @var int
64
+     */
65
+    private $status = Http::STATUS_OK;
66
+
67
+
68
+    /**
69
+     * Last modified date
70
+     * @var \DateTime
71
+     */
72
+    private $lastModified;
73
+
74
+
75
+    /**
76
+     * ETag
77
+     * @var string
78
+     */
79
+    private $ETag;
80
+
81
+    /** @var ContentSecurityPolicy|null Used Content-Security-Policy */
82
+    private $contentSecurityPolicy = null;
83
+
84
+
85
+    /**
86
+     * Caches the response
87
+     * @param int $cacheSeconds the amount of seconds that should be cached
88
+     * if 0 then caching will be disabled
89
+     * @return $this
90
+     * @since 6.0.0 - return value was added in 7.0.0
91
+     */
92
+    public function cacheFor($cacheSeconds) {
93
+
94
+        if($cacheSeconds > 0) {
95
+            $this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
96
+        } else {
97
+            $this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
98
+        }
99
+
100
+        return $this;
101
+    }
102
+
103
+    /**
104
+     * Adds a new cookie to the response
105
+     * @param string $name The name of the cookie
106
+     * @param string $value The value of the cookie
107
+     * @param \DateTime|null $expireDate Date on that the cookie should expire, if set
108
+     * 									to null cookie will be considered as session
109
+     * 									cookie.
110
+     * @return $this
111
+     * @since 8.0.0
112
+     */
113
+    public function addCookie($name, $value, \DateTime $expireDate = null) {
114
+        $this->cookies[$name] = array('value' => $value, 'expireDate' => $expireDate);
115
+        return $this;
116
+    }
117
+
118
+
119
+    /**
120
+     * Set the specified cookies
121
+     * @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
122
+     * @return $this
123
+     * @since 8.0.0
124
+     */
125
+    public function setCookies(array $cookies) {
126
+        $this->cookies = $cookies;
127
+        return $this;
128
+    }
129
+
130
+
131
+    /**
132
+     * Invalidates the specified cookie
133
+     * @param string $name
134
+     * @return $this
135
+     * @since 8.0.0
136
+     */
137
+    public function invalidateCookie($name) {
138
+        $this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
139
+        return $this;
140
+    }
141
+
142
+    /**
143
+     * Invalidates the specified cookies
144
+     * @param array $cookieNames array('foo', 'bar')
145
+     * @return $this
146
+     * @since 8.0.0
147
+     */
148
+    public function invalidateCookies(array $cookieNames) {
149
+        foreach($cookieNames as $cookieName) {
150
+            $this->invalidateCookie($cookieName);
151
+        }
152
+        return $this;
153
+    }
154
+
155
+    /**
156
+     * Returns the cookies
157
+     * @return array
158
+     * @since 8.0.0
159
+     */
160
+    public function getCookies() {
161
+        return $this->cookies;
162
+    }
163
+
164
+    /**
165
+     * Adds a new header to the response that will be called before the render
166
+     * function
167
+     * @param string $name The name of the HTTP header
168
+     * @param string $value The value, null will delete it
169
+     * @return $this
170
+     * @since 6.0.0 - return value was added in 7.0.0
171
+     */
172
+    public function addHeader($name, $value) {
173
+        $name = trim($name);  // always remove leading and trailing whitespace
174
+                                // to be able to reliably check for security
175
+                                // headers
176
+
177
+        if(is_null($value)) {
178
+            unset($this->headers[$name]);
179
+        } else {
180
+            $this->headers[$name] = $value;
181
+        }
182
+
183
+        return $this;
184
+    }
185
+
186
+
187
+    /**
188
+     * Set the headers
189
+     * @param array $headers value header pairs
190
+     * @return $this
191
+     * @since 8.0.0
192
+     */
193
+    public function setHeaders(array $headers) {
194
+        $this->headers = $headers;
195
+
196
+        return $this;
197
+    }
198
+
199
+
200
+    /**
201
+     * Returns the set headers
202
+     * @return array the headers
203
+     * @since 6.0.0
204
+     */
205
+    public function getHeaders() {
206
+        $mergeWith = [];
207
+
208
+        if($this->lastModified) {
209
+            $mergeWith['Last-Modified'] =
210
+                $this->lastModified->format(\DateTime::RFC2822);
211
+        }
212
+
213
+        // Build Content-Security-Policy and use default if none has been specified
214
+        if(is_null($this->contentSecurityPolicy)) {
215
+            $this->setContentSecurityPolicy(new ContentSecurityPolicy());
216
+        }
217
+        $this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
218
+
219
+        if($this->ETag) {
220
+            $mergeWith['ETag'] = '"' . $this->ETag . '"';
221
+        }
222
+
223
+        return array_merge($mergeWith, $this->headers);
224
+    }
225
+
226
+
227
+    /**
228
+     * By default renders no output
229
+     * @return null
230
+     * @since 6.0.0
231
+     */
232
+    public function render() {
233
+        return null;
234
+    }
235
+
236
+
237
+    /**
238
+     * Set response status
239
+     * @param int $status a HTTP status code, see also the STATUS constants
240
+     * @return Response Reference to this object
241
+     * @since 6.0.0 - return value was added in 7.0.0
242
+     */
243
+    public function setStatus($status) {
244
+        $this->status = $status;
245
+
246
+        return $this;
247
+    }
248
+
249
+    /**
250
+     * Set a Content-Security-Policy
251
+     * @param EmptyContentSecurityPolicy $csp Policy to set for the response object
252
+     * @return $this
253
+     * @since 8.1.0
254
+     */
255
+    public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
256
+        $this->contentSecurityPolicy = $csp;
257
+        return $this;
258
+    }
259
+
260
+    /**
261
+     * Get the currently used Content-Security-Policy
262
+     * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
263
+     *                                    none specified.
264
+     * @since 8.1.0
265
+     */
266
+    public function getContentSecurityPolicy() {
267
+        return $this->contentSecurityPolicy;
268
+    }
269
+
270
+
271
+    /**
272
+     * Get response status
273
+     * @since 6.0.0
274
+     */
275
+    public function getStatus() {
276
+        return $this->status;
277
+    }
278
+
279
+
280
+    /**
281
+     * Get the ETag
282
+     * @return string the etag
283
+     * @since 6.0.0
284
+     */
285
+    public function getETag() {
286
+        return $this->ETag;
287
+    }
288
+
289
+
290
+    /**
291
+     * Get "last modified" date
292
+     * @return \DateTime RFC2822 formatted last modified date
293
+     * @since 6.0.0
294
+     */
295
+    public function getLastModified() {
296
+        return $this->lastModified;
297
+    }
298
+
299
+
300
+    /**
301
+     * Set the ETag
302
+     * @param string $ETag
303
+     * @return Response Reference to this object
304
+     * @since 6.0.0 - return value was added in 7.0.0
305
+     */
306
+    public function setETag($ETag) {
307
+        $this->ETag = $ETag;
308
+
309
+        return $this;
310
+    }
311
+
312
+
313
+    /**
314
+     * Set "last modified" date
315
+     * @param \DateTime $lastModified
316
+     * @return Response Reference to this object
317
+     * @since 6.0.0 - return value was added in 7.0.0
318
+     */
319
+    public function setLastModified($lastModified) {
320
+        $this->lastModified = $lastModified;
321
+
322
+        return $this;
323
+    }
324 324
 
325 325
 
326 326
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -91,8 +91,8 @@  discard block
 block discarded – undo
91 91
 	 */
92 92
 	public function cacheFor($cacheSeconds) {
93 93
 
94
-		if($cacheSeconds > 0) {
95
-			$this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
94
+		if ($cacheSeconds > 0) {
95
+			$this->addHeader('Cache-Control', 'max-age='.$cacheSeconds.', must-revalidate');
96 96
 		} else {
97 97
 			$this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
98 98
 		}
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 	 * @since 8.0.0
147 147
 	 */
148 148
 	public function invalidateCookies(array $cookieNames) {
149
-		foreach($cookieNames as $cookieName) {
149
+		foreach ($cookieNames as $cookieName) {
150 150
 			$this->invalidateCookie($cookieName);
151 151
 		}
152 152
 		return $this;
@@ -170,11 +170,11 @@  discard block
 block discarded – undo
170 170
 	 * @since 6.0.0 - return value was added in 7.0.0
171 171
 	 */
172 172
 	public function addHeader($name, $value) {
173
-		$name = trim($name);  // always remove leading and trailing whitespace
173
+		$name = trim($name); // always remove leading and trailing whitespace
174 174
 		                      // to be able to reliably check for security
175 175
 		                      // headers
176 176
 
177
-		if(is_null($value)) {
177
+		if (is_null($value)) {
178 178
 			unset($this->headers[$name]);
179 179
 		} else {
180 180
 			$this->headers[$name] = $value;
@@ -205,19 +205,19 @@  discard block
 block discarded – undo
205 205
 	public function getHeaders() {
206 206
 		$mergeWith = [];
207 207
 
208
-		if($this->lastModified) {
208
+		if ($this->lastModified) {
209 209
 			$mergeWith['Last-Modified'] =
210 210
 				$this->lastModified->format(\DateTime::RFC2822);
211 211
 		}
212 212
 
213 213
 		// Build Content-Security-Policy and use default if none has been specified
214
-		if(is_null($this->contentSecurityPolicy)) {
214
+		if (is_null($this->contentSecurityPolicy)) {
215 215
 			$this->setContentSecurityPolicy(new ContentSecurityPolicy());
216 216
 		}
217 217
 		$this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
218 218
 
219
-		if($this->ETag) {
220
-			$mergeWith['ETag'] = '"' . $this->ETag . '"';
219
+		if ($this->ETag) {
220
+			$mergeWith['ETag'] = '"'.$this->ETag.'"';
221 221
 		}
222 222
 
223 223
 		return array_merge($mergeWith, $this->headers);
Please login to merge, or discard this patch.