Completed
Pull Request — master (#7479)
by Morris
27:25 queued 11:48
created
apps/user_ldap/lib/Access.php 2 patches
Indentation   +1869 added lines, -1869 removed lines patch added patch discarded remove patch
@@ -58,1630 +58,1630 @@  discard block
 block discarded – undo
58 58
  * @package OCA\User_LDAP
59 59
  */
60 60
 class Access extends LDAPUtility implements IUserTools {
61
-	const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
62
-
63
-	/** @var \OCA\User_LDAP\Connection */
64
-	public $connection;
65
-	/** @var Manager */
66
-	public $userManager;
67
-	//never ever check this var directly, always use getPagedSearchResultState
68
-	protected $pagedSearchedSuccessful;
69
-
70
-	/**
71
-	 * @var string[] $cookies an array of returned Paged Result cookies
72
-	 */
73
-	protected $cookies = array();
74
-
75
-	/**
76
-	 * @var string $lastCookie the last cookie returned from a Paged Results
77
-	 * operation, defaults to an empty string
78
-	 */
79
-	protected $lastCookie = '';
80
-
81
-	/**
82
-	 * @var AbstractMapping $userMapper
83
-	 */
84
-	protected $userMapper;
85
-
86
-	/**
87
-	* @var AbstractMapping $userMapper
88
-	*/
89
-	protected $groupMapper;
90
-
91
-	/**
92
-	 * @var \OCA\User_LDAP\Helper
93
-	 */
94
-	private $helper;
95
-	/** @var IConfig */
96
-	private $config;
97
-
98
-	public function __construct(
99
-		Connection $connection,
100
-		ILDAPWrapper $ldap,
101
-		Manager $userManager,
102
-		Helper $helper,
103
-		IConfig $config
104
-	) {
105
-		parent::__construct($ldap);
106
-		$this->connection = $connection;
107
-		$this->userManager = $userManager;
108
-		$this->userManager->setLdapAccess($this);
109
-		$this->helper = $helper;
110
-		$this->config = $config;
111
-	}
112
-
113
-	/**
114
-	 * sets the User Mapper
115
-	 * @param AbstractMapping $mapper
116
-	 */
117
-	public function setUserMapper(AbstractMapping $mapper) {
118
-		$this->userMapper = $mapper;
119
-	}
120
-
121
-	/**
122
-	 * returns the User Mapper
123
-	 * @throws \Exception
124
-	 * @return AbstractMapping
125
-	 */
126
-	public function getUserMapper() {
127
-		if(is_null($this->userMapper)) {
128
-			throw new \Exception('UserMapper was not assigned to this Access instance.');
129
-		}
130
-		return $this->userMapper;
131
-	}
132
-
133
-	/**
134
-	 * sets the Group Mapper
135
-	 * @param AbstractMapping $mapper
136
-	 */
137
-	public function setGroupMapper(AbstractMapping $mapper) {
138
-		$this->groupMapper = $mapper;
139
-	}
140
-
141
-	/**
142
-	 * returns the Group Mapper
143
-	 * @throws \Exception
144
-	 * @return AbstractMapping
145
-	 */
146
-	public function getGroupMapper() {
147
-		if(is_null($this->groupMapper)) {
148
-			throw new \Exception('GroupMapper was not assigned to this Access instance.');
149
-		}
150
-		return $this->groupMapper;
151
-	}
152
-
153
-	/**
154
-	 * @return bool
155
-	 */
156
-	private function checkConnection() {
157
-		return ($this->connection instanceof Connection);
158
-	}
159
-
160
-	/**
161
-	 * returns the Connection instance
162
-	 * @return \OCA\User_LDAP\Connection
163
-	 */
164
-	public function getConnection() {
165
-		return $this->connection;
166
-	}
167
-
168
-	/**
169
-	 * reads a given attribute for an LDAP record identified by a DN
170
-	 * @param string $dn the record in question
171
-	 * @param string $attr the attribute that shall be retrieved
172
-	 *        if empty, just check the record's existence
173
-	 * @param string $filter
174
-	 * @return array|false an array of values on success or an empty
175
-	 *          array if $attr is empty, false otherwise
176
-	 */
177
-	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
178
-		if(!$this->checkConnection()) {
179
-			\OCP\Util::writeLog('user_ldap',
180
-				'No LDAP Connector assigned, access impossible for readAttribute.',
181
-				\OCP\Util::WARN);
182
-			return false;
183
-		}
184
-		$cr = $this->connection->getConnectionResource();
185
-		if(!$this->ldap->isResource($cr)) {
186
-			//LDAP not available
187
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
188
-			return false;
189
-		}
190
-		//Cancel possibly running Paged Results operation, otherwise we run in
191
-		//LDAP protocol errors
192
-		$this->abandonPagedSearch();
193
-		// openLDAP requires that we init a new Paged Search. Not needed by AD,
194
-		// but does not hurt either.
195
-		$pagingSize = intval($this->connection->ldapPagingSize);
196
-		// 0 won't result in replies, small numbers may leave out groups
197
-		// (cf. #12306), 500 is default for paging and should work everywhere.
198
-		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
199
-		$attr = mb_strtolower($attr, 'UTF-8');
200
-		// the actual read attribute later may contain parameters on a ranged
201
-		// request, e.g. member;range=99-199. Depends on server reply.
202
-		$attrToRead = $attr;
203
-
204
-		$values = [];
205
-		$isRangeRequest = false;
206
-		do {
207
-			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
208
-			if(is_bool($result)) {
209
-				// when an exists request was run and it was successful, an empty
210
-				// array must be returned
211
-				return $result ? [] : false;
212
-			}
213
-
214
-			if (!$isRangeRequest) {
215
-				$values = $this->extractAttributeValuesFromResult($result, $attr);
216
-				if (!empty($values)) {
217
-					return $values;
218
-				}
219
-			}
220
-
221
-			$isRangeRequest = false;
222
-			$result = $this->extractRangeData($result, $attr);
223
-			if (!empty($result)) {
224
-				$normalizedResult = $this->extractAttributeValuesFromResult(
225
-					[ $attr => $result['values'] ],
226
-					$attr
227
-				);
228
-				$values = array_merge($values, $normalizedResult);
229
-
230
-				if($result['rangeHigh'] === '*') {
231
-					// when server replies with * as high range value, there are
232
-					// no more results left
233
-					return $values;
234
-				} else {
235
-					$low  = $result['rangeHigh'] + 1;
236
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
237
-					$isRangeRequest = true;
238
-				}
239
-			}
240
-		} while($isRangeRequest);
241
-
242
-		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
243
-		return false;
244
-	}
245
-
246
-	/**
247
-	 * Runs an read operation against LDAP
248
-	 *
249
-	 * @param resource $cr the LDAP connection
250
-	 * @param string $dn
251
-	 * @param string $attribute
252
-	 * @param string $filter
253
-	 * @param int $maxResults
254
-	 * @return array|bool false if there was any error, true if an exists check
255
-	 *                    was performed and the requested DN found, array with the
256
-	 *                    returned data on a successful usual operation
257
-	 */
258
-	public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
259
-		$this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0);
260
-		$dn = $this->helper->DNasBaseParameter($dn);
261
-		$rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, array($attribute));
262
-		if (!$this->ldap->isResource($rr)) {
263
-			if ($attribute !== '') {
264
-				//do not throw this message on userExists check, irritates
265
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
266
-			}
267
-			//in case an error occurs , e.g. object does not exist
268
-			return false;
269
-		}
270
-		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
271
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
272
-			return true;
273
-		}
274
-		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
275
-		if (!$this->ldap->isResource($er)) {
276
-			//did not match the filter, return false
277
-			return false;
278
-		}
279
-		//LDAP attributes are not case sensitive
280
-		$result = \OCP\Util::mb_array_change_key_case(
281
-			$this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
282
-
283
-		return $result;
284
-	}
285
-
286
-	/**
287
-	 * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
288
-	 * data if present.
289
-	 *
290
-	 * @param array $result from ILDAPWrapper::getAttributes()
291
-	 * @param string $attribute the attribute name that was read
292
-	 * @return string[]
293
-	 */
294
-	public function extractAttributeValuesFromResult($result, $attribute) {
295
-		$values = [];
296
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
297
-			$lowercaseAttribute = strtolower($attribute);
298
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
299
-				if($this->resemblesDN($attribute)) {
300
-					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
301
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
302
-					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
303
-				} else {
304
-					$values[] = $result[$attribute][$i];
305
-				}
306
-			}
307
-		}
308
-		return $values;
309
-	}
310
-
311
-	/**
312
-	 * Attempts to find ranged data in a getAttribute results and extracts the
313
-	 * returned values as well as information on the range and full attribute
314
-	 * name for further processing.
315
-	 *
316
-	 * @param array $result from ILDAPWrapper::getAttributes()
317
-	 * @param string $attribute the attribute name that was read. Without ";range=…"
318
-	 * @return array If a range was detected with keys 'values', 'attributeName',
319
-	 *               'attributeFull' and 'rangeHigh', otherwise empty.
320
-	 */
321
-	public function extractRangeData($result, $attribute) {
322
-		$keys = array_keys($result);
323
-		foreach($keys as $key) {
324
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
325
-				$queryData = explode(';', $key);
326
-				if(strpos($queryData[1], 'range=') === 0) {
327
-					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
328
-					$data = [
329
-						'values' => $result[$key],
330
-						'attributeName' => $queryData[0],
331
-						'attributeFull' => $key,
332
-						'rangeHigh' => $high,
333
-					];
334
-					return $data;
335
-				}
336
-			}
337
-		}
338
-		return [];
339
-	}
61
+    const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
62
+
63
+    /** @var \OCA\User_LDAP\Connection */
64
+    public $connection;
65
+    /** @var Manager */
66
+    public $userManager;
67
+    //never ever check this var directly, always use getPagedSearchResultState
68
+    protected $pagedSearchedSuccessful;
69
+
70
+    /**
71
+     * @var string[] $cookies an array of returned Paged Result cookies
72
+     */
73
+    protected $cookies = array();
74
+
75
+    /**
76
+     * @var string $lastCookie the last cookie returned from a Paged Results
77
+     * operation, defaults to an empty string
78
+     */
79
+    protected $lastCookie = '';
80
+
81
+    /**
82
+     * @var AbstractMapping $userMapper
83
+     */
84
+    protected $userMapper;
85
+
86
+    /**
87
+     * @var AbstractMapping $userMapper
88
+     */
89
+    protected $groupMapper;
90
+
91
+    /**
92
+     * @var \OCA\User_LDAP\Helper
93
+     */
94
+    private $helper;
95
+    /** @var IConfig */
96
+    private $config;
97
+
98
+    public function __construct(
99
+        Connection $connection,
100
+        ILDAPWrapper $ldap,
101
+        Manager $userManager,
102
+        Helper $helper,
103
+        IConfig $config
104
+    ) {
105
+        parent::__construct($ldap);
106
+        $this->connection = $connection;
107
+        $this->userManager = $userManager;
108
+        $this->userManager->setLdapAccess($this);
109
+        $this->helper = $helper;
110
+        $this->config = $config;
111
+    }
112
+
113
+    /**
114
+     * sets the User Mapper
115
+     * @param AbstractMapping $mapper
116
+     */
117
+    public function setUserMapper(AbstractMapping $mapper) {
118
+        $this->userMapper = $mapper;
119
+    }
120
+
121
+    /**
122
+     * returns the User Mapper
123
+     * @throws \Exception
124
+     * @return AbstractMapping
125
+     */
126
+    public function getUserMapper() {
127
+        if(is_null($this->userMapper)) {
128
+            throw new \Exception('UserMapper was not assigned to this Access instance.');
129
+        }
130
+        return $this->userMapper;
131
+    }
132
+
133
+    /**
134
+     * sets the Group Mapper
135
+     * @param AbstractMapping $mapper
136
+     */
137
+    public function setGroupMapper(AbstractMapping $mapper) {
138
+        $this->groupMapper = $mapper;
139
+    }
140
+
141
+    /**
142
+     * returns the Group Mapper
143
+     * @throws \Exception
144
+     * @return AbstractMapping
145
+     */
146
+    public function getGroupMapper() {
147
+        if(is_null($this->groupMapper)) {
148
+            throw new \Exception('GroupMapper was not assigned to this Access instance.');
149
+        }
150
+        return $this->groupMapper;
151
+    }
152
+
153
+    /**
154
+     * @return bool
155
+     */
156
+    private function checkConnection() {
157
+        return ($this->connection instanceof Connection);
158
+    }
159
+
160
+    /**
161
+     * returns the Connection instance
162
+     * @return \OCA\User_LDAP\Connection
163
+     */
164
+    public function getConnection() {
165
+        return $this->connection;
166
+    }
167
+
168
+    /**
169
+     * reads a given attribute for an LDAP record identified by a DN
170
+     * @param string $dn the record in question
171
+     * @param string $attr the attribute that shall be retrieved
172
+     *        if empty, just check the record's existence
173
+     * @param string $filter
174
+     * @return array|false an array of values on success or an empty
175
+     *          array if $attr is empty, false otherwise
176
+     */
177
+    public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
178
+        if(!$this->checkConnection()) {
179
+            \OCP\Util::writeLog('user_ldap',
180
+                'No LDAP Connector assigned, access impossible for readAttribute.',
181
+                \OCP\Util::WARN);
182
+            return false;
183
+        }
184
+        $cr = $this->connection->getConnectionResource();
185
+        if(!$this->ldap->isResource($cr)) {
186
+            //LDAP not available
187
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
188
+            return false;
189
+        }
190
+        //Cancel possibly running Paged Results operation, otherwise we run in
191
+        //LDAP protocol errors
192
+        $this->abandonPagedSearch();
193
+        // openLDAP requires that we init a new Paged Search. Not needed by AD,
194
+        // but does not hurt either.
195
+        $pagingSize = intval($this->connection->ldapPagingSize);
196
+        // 0 won't result in replies, small numbers may leave out groups
197
+        // (cf. #12306), 500 is default for paging and should work everywhere.
198
+        $maxResults = $pagingSize > 20 ? $pagingSize : 500;
199
+        $attr = mb_strtolower($attr, 'UTF-8');
200
+        // the actual read attribute later may contain parameters on a ranged
201
+        // request, e.g. member;range=99-199. Depends on server reply.
202
+        $attrToRead = $attr;
203
+
204
+        $values = [];
205
+        $isRangeRequest = false;
206
+        do {
207
+            $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
208
+            if(is_bool($result)) {
209
+                // when an exists request was run and it was successful, an empty
210
+                // array must be returned
211
+                return $result ? [] : false;
212
+            }
213
+
214
+            if (!$isRangeRequest) {
215
+                $values = $this->extractAttributeValuesFromResult($result, $attr);
216
+                if (!empty($values)) {
217
+                    return $values;
218
+                }
219
+            }
220
+
221
+            $isRangeRequest = false;
222
+            $result = $this->extractRangeData($result, $attr);
223
+            if (!empty($result)) {
224
+                $normalizedResult = $this->extractAttributeValuesFromResult(
225
+                    [ $attr => $result['values'] ],
226
+                    $attr
227
+                );
228
+                $values = array_merge($values, $normalizedResult);
229
+
230
+                if($result['rangeHigh'] === '*') {
231
+                    // when server replies with * as high range value, there are
232
+                    // no more results left
233
+                    return $values;
234
+                } else {
235
+                    $low  = $result['rangeHigh'] + 1;
236
+                    $attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
237
+                    $isRangeRequest = true;
238
+                }
239
+            }
240
+        } while($isRangeRequest);
241
+
242
+        \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
243
+        return false;
244
+    }
245
+
246
+    /**
247
+     * Runs an read operation against LDAP
248
+     *
249
+     * @param resource $cr the LDAP connection
250
+     * @param string $dn
251
+     * @param string $attribute
252
+     * @param string $filter
253
+     * @param int $maxResults
254
+     * @return array|bool false if there was any error, true if an exists check
255
+     *                    was performed and the requested DN found, array with the
256
+     *                    returned data on a successful usual operation
257
+     */
258
+    public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
259
+        $this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0);
260
+        $dn = $this->helper->DNasBaseParameter($dn);
261
+        $rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, array($attribute));
262
+        if (!$this->ldap->isResource($rr)) {
263
+            if ($attribute !== '') {
264
+                //do not throw this message on userExists check, irritates
265
+                \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
266
+            }
267
+            //in case an error occurs , e.g. object does not exist
268
+            return false;
269
+        }
270
+        if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
271
+            \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
272
+            return true;
273
+        }
274
+        $er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
275
+        if (!$this->ldap->isResource($er)) {
276
+            //did not match the filter, return false
277
+            return false;
278
+        }
279
+        //LDAP attributes are not case sensitive
280
+        $result = \OCP\Util::mb_array_change_key_case(
281
+            $this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
282
+
283
+        return $result;
284
+    }
285
+
286
+    /**
287
+     * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
288
+     * data if present.
289
+     *
290
+     * @param array $result from ILDAPWrapper::getAttributes()
291
+     * @param string $attribute the attribute name that was read
292
+     * @return string[]
293
+     */
294
+    public function extractAttributeValuesFromResult($result, $attribute) {
295
+        $values = [];
296
+        if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
297
+            $lowercaseAttribute = strtolower($attribute);
298
+            for($i=0;$i<$result[$attribute]['count'];$i++) {
299
+                if($this->resemblesDN($attribute)) {
300
+                    $values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
301
+                } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
302
+                    $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
303
+                } else {
304
+                    $values[] = $result[$attribute][$i];
305
+                }
306
+            }
307
+        }
308
+        return $values;
309
+    }
310
+
311
+    /**
312
+     * Attempts to find ranged data in a getAttribute results and extracts the
313
+     * returned values as well as information on the range and full attribute
314
+     * name for further processing.
315
+     *
316
+     * @param array $result from ILDAPWrapper::getAttributes()
317
+     * @param string $attribute the attribute name that was read. Without ";range=…"
318
+     * @return array If a range was detected with keys 'values', 'attributeName',
319
+     *               'attributeFull' and 'rangeHigh', otherwise empty.
320
+     */
321
+    public function extractRangeData($result, $attribute) {
322
+        $keys = array_keys($result);
323
+        foreach($keys as $key) {
324
+            if($key !== $attribute && strpos($key, $attribute) === 0) {
325
+                $queryData = explode(';', $key);
326
+                if(strpos($queryData[1], 'range=') === 0) {
327
+                    $high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
328
+                    $data = [
329
+                        'values' => $result[$key],
330
+                        'attributeName' => $queryData[0],
331
+                        'attributeFull' => $key,
332
+                        'rangeHigh' => $high,
333
+                    ];
334
+                    return $data;
335
+                }
336
+            }
337
+        }
338
+        return [];
339
+    }
340 340
 	
341
-	/**
342
-	 * Set password for an LDAP user identified by a DN
343
-	 *
344
-	 * @param string $userDN the user in question
345
-	 * @param string $password the new password
346
-	 * @return bool
347
-	 * @throws HintException
348
-	 * @throws \Exception
349
-	 */
350
-	public function setPassword($userDN, $password) {
351
-		if(intval($this->connection->turnOnPasswordChange) !== 1) {
352
-			throw new \Exception('LDAP password changes are disabled.');
353
-		}
354
-		$cr = $this->connection->getConnectionResource();
355
-		if(!$this->ldap->isResource($cr)) {
356
-			//LDAP not available
357
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
358
-			return false;
359
-		}
360
-		try {
361
-			return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
362
-		} catch(ConstraintViolationException $e) {
363
-			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
364
-		}
365
-	}
366
-
367
-	/**
368
-	 * checks whether the given attributes value is probably a DN
369
-	 * @param string $attr the attribute in question
370
-	 * @return boolean if so true, otherwise false
371
-	 */
372
-	private function resemblesDN($attr) {
373
-		$resemblingAttributes = array(
374
-			'dn',
375
-			'uniquemember',
376
-			'member',
377
-			// memberOf is an "operational" attribute, without a definition in any RFC
378
-			'memberof'
379
-		);
380
-		return in_array($attr, $resemblingAttributes);
381
-	}
382
-
383
-	/**
384
-	 * checks whether the given string is probably a DN
385
-	 * @param string $string
386
-	 * @return boolean
387
-	 */
388
-	public function stringResemblesDN($string) {
389
-		$r = $this->ldap->explodeDN($string, 0);
390
-		// if exploding a DN succeeds and does not end up in
391
-		// an empty array except for $r[count] being 0.
392
-		return (is_array($r) && count($r) > 1);
393
-	}
394
-
395
-	/**
396
-	 * returns a DN-string that is cleaned from not domain parts, e.g.
397
-	 * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
398
-	 * becomes dc=foobar,dc=server,dc=org
399
-	 * @param string $dn
400
-	 * @return string
401
-	 */
402
-	public function getDomainDNFromDN($dn) {
403
-		$allParts = $this->ldap->explodeDN($dn, 0);
404
-		if($allParts === false) {
405
-			//not a valid DN
406
-			return '';
407
-		}
408
-		$domainParts = array();
409
-		$dcFound = false;
410
-		foreach($allParts as $part) {
411
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
412
-				$dcFound = true;
413
-			}
414
-			if($dcFound) {
415
-				$domainParts[] = $part;
416
-			}
417
-		}
418
-		$domainDN = implode(',', $domainParts);
419
-		return $domainDN;
420
-	}
421
-
422
-	/**
423
-	 * returns the LDAP DN for the given internal Nextcloud name of the group
424
-	 * @param string $name the Nextcloud name in question
425
-	 * @return string|false LDAP DN on success, otherwise false
426
-	 */
427
-	public function groupname2dn($name) {
428
-		return $this->groupMapper->getDNByName($name);
429
-	}
430
-
431
-	/**
432
-	 * returns the LDAP DN for the given internal Nextcloud name of the user
433
-	 * @param string $name the Nextcloud name in question
434
-	 * @return string|false with the LDAP DN on success, otherwise false
435
-	 */
436
-	public function username2dn($name) {
437
-		$fdn = $this->userMapper->getDNByName($name);
438
-
439
-		//Check whether the DN belongs to the Base, to avoid issues on multi-
440
-		//server setups
441
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
442
-			return $fdn;
443
-		}
444
-
445
-		return false;
446
-	}
447
-
448
-	/**
449
-	 * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
450
-	 * @param string $fdn the dn of the group object
451
-	 * @param string $ldapName optional, the display name of the object
452
-	 * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
453
-	 */
454
-	public function dn2groupname($fdn, $ldapName = null) {
455
-		//To avoid bypassing the base DN settings under certain circumstances
456
-		//with the group support, check whether the provided DN matches one of
457
-		//the given Bases
458
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
459
-			return false;
460
-		}
461
-
462
-		return $this->dn2ocname($fdn, $ldapName, false);
463
-	}
464
-
465
-	/**
466
-	 * accepts an array of group DNs and tests whether they match the user
467
-	 * filter by doing read operations against the group entries. Returns an
468
-	 * array of DNs that match the filter.
469
-	 *
470
-	 * @param string[] $groupDNs
471
-	 * @return string[]
472
-	 */
473
-	public function groupsMatchFilter($groupDNs) {
474
-		$validGroupDNs = [];
475
-		foreach($groupDNs as $dn) {
476
-			$cacheKey = 'groupsMatchFilter-'.$dn;
477
-			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
478
-			if(!is_null($groupMatchFilter)) {
479
-				if($groupMatchFilter) {
480
-					$validGroupDNs[] = $dn;
481
-				}
482
-				continue;
483
-			}
484
-
485
-			// Check the base DN first. If this is not met already, we don't
486
-			// need to ask the server at all.
487
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
488
-				$this->connection->writeToCache($cacheKey, false);
489
-				continue;
490
-			}
491
-
492
-			$result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
493
-			if(is_array($result)) {
494
-				$this->connection->writeToCache($cacheKey, true);
495
-				$validGroupDNs[] = $dn;
496
-			} else {
497
-				$this->connection->writeToCache($cacheKey, false);
498
-			}
499
-
500
-		}
501
-		return $validGroupDNs;
502
-	}
503
-
504
-	/**
505
-	 * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
506
-	 * @param string $dn the dn of the user object
507
-	 * @param string $ldapName optional, the display name of the object
508
-	 * @return string|false with with the name to use in Nextcloud
509
-	 */
510
-	public function dn2username($fdn, $ldapName = null) {
511
-		//To avoid bypassing the base DN settings under certain circumstances
512
-		//with the group support, check whether the provided DN matches one of
513
-		//the given Bases
514
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
515
-			return false;
516
-		}
517
-
518
-		return $this->dn2ocname($fdn, $ldapName, true);
519
-	}
520
-
521
-	/**
522
-	 * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
523
-	 *
524
-	 * @param string $fdn the dn of the user object
525
-	 * @param string|null $ldapName optional, the display name of the object
526
-	 * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
527
-	 * @param bool|null $newlyMapped
528
-	 * @param array|null $record
529
-	 * @return false|string with with the name to use in Nextcloud
530
-	 * @throws \Exception
531
-	 */
532
-	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
533
-		$newlyMapped = false;
534
-		if($isUser) {
535
-			$mapper = $this->getUserMapper();
536
-			$nameAttribute = $this->connection->ldapUserDisplayName;
537
-		} else {
538
-			$mapper = $this->getGroupMapper();
539
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
540
-		}
541
-
542
-		//let's try to retrieve the Nextcloud name from the mappings table
543
-		$ncName = $mapper->getNameByDN($fdn);
544
-		if(is_string($ncName)) {
545
-			return $ncName;
546
-		}
547
-
548
-		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
549
-		$uuid = $this->getUUID($fdn, $isUser, $record);
550
-		if(is_string($uuid)) {
551
-			$ncName = $mapper->getNameByUUID($uuid);
552
-			if(is_string($ncName)) {
553
-				$mapper->setDNbyUUID($fdn, $uuid);
554
-				return $ncName;
555
-			}
556
-		} else {
557
-			//If the UUID can't be detected something is foul.
558
-			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', \OCP\Util::INFO);
559
-			return false;
560
-		}
561
-
562
-		if(is_null($ldapName)) {
563
-			$ldapName = $this->readAttribute($fdn, $nameAttribute);
564
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
565
-				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
566
-				return false;
567
-			}
568
-			$ldapName = $ldapName[0];
569
-		}
570
-
571
-		if($isUser) {
572
-			$usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
573
-			if ($usernameAttribute !== '') {
574
-				$username = $this->readAttribute($fdn, $usernameAttribute);
575
-				$username = $username[0];
576
-			} else {
577
-				$username = $uuid;
578
-			}
579
-			$intName = $this->sanitizeUsername($username);
580
-		} else {
581
-			$intName = $ldapName;
582
-		}
583
-
584
-		//a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
585
-		//disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
586
-		//NOTE: mind, disabling cache affects only this instance! Using it
587
-		// outside of core user management will still cache the user as non-existing.
588
-		$originalTTL = $this->connection->ldapCacheTTL;
589
-		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
590
-		if(($isUser && $intName !== '' && !\OCP\User::userExists($intName))
591
-			|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
592
-			if($mapper->map($fdn, $intName, $uuid)) {
593
-				$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
594
-				$newlyMapped = true;
595
-				return $intName;
596
-			}
597
-		}
598
-		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
599
-
600
-		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
601
-		if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
602
-			$newlyMapped = true;
603
-			return $altName;
604
-		}
605
-
606
-		//if everything else did not help..
607
-		\OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', \OCP\Util::INFO);
608
-		return false;
609
-	}
610
-
611
-	/**
612
-	 * gives back the user names as they are used ownClod internally
613
-	 * @param array $ldapUsers as returned by fetchList()
614
-	 * @return array an array with the user names to use in Nextcloud
615
-	 *
616
-	 * gives back the user names as they are used ownClod internally
617
-	 */
618
-	public function nextcloudUserNames($ldapUsers) {
619
-		return $this->ldap2NextcloudNames($ldapUsers, true);
620
-	}
621
-
622
-	/**
623
-	 * gives back the group names as they are used ownClod internally
624
-	 * @param array $ldapGroups as returned by fetchList()
625
-	 * @return array an array with the group names to use in Nextcloud
626
-	 *
627
-	 * gives back the group names as they are used ownClod internally
628
-	 */
629
-	public function nextcloudGroupNames($ldapGroups) {
630
-		return $this->ldap2NextcloudNames($ldapGroups, false);
631
-	}
632
-
633
-	/**
634
-	 * @param array $ldapObjects as returned by fetchList()
635
-	 * @param bool $isUsers
636
-	 * @return array
637
-	 */
638
-	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
639
-		if($isUsers) {
640
-			$nameAttribute = $this->connection->ldapUserDisplayName;
641
-			$sndAttribute  = $this->connection->ldapUserDisplayName2;
642
-		} else {
643
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
644
-		}
645
-		$nextcloudNames = array();
646
-
647
-		foreach($ldapObjects as $ldapObject) {
648
-			$nameByLDAP = null;
649
-			if(    isset($ldapObject[$nameAttribute])
650
-				&& is_array($ldapObject[$nameAttribute])
651
-				&& isset($ldapObject[$nameAttribute][0])
652
-			) {
653
-				// might be set, but not necessarily. if so, we use it.
654
-				$nameByLDAP = $ldapObject[$nameAttribute][0];
655
-			}
656
-
657
-			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
658
-			if($ncName) {
659
-				$nextcloudNames[] = $ncName;
660
-				if($isUsers) {
661
-					//cache the user names so it does not need to be retrieved
662
-					//again later (e.g. sharing dialogue).
663
-					if(is_null($nameByLDAP)) {
664
-						continue;
665
-					}
666
-					$sndName = isset($ldapObject[$sndAttribute][0])
667
-						? $ldapObject[$sndAttribute][0] : '';
668
-					$this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
669
-				}
670
-			}
671
-		}
672
-		return $nextcloudNames;
673
-	}
674
-
675
-	/**
676
-	 * caches the user display name
677
-	 * @param string $ocName the internal Nextcloud username
678
-	 * @param string|false $home the home directory path
679
-	 */
680
-	public function cacheUserHome($ocName, $home) {
681
-		$cacheKey = 'getHome'.$ocName;
682
-		$this->connection->writeToCache($cacheKey, $home);
683
-	}
684
-
685
-	/**
686
-	 * caches a user as existing
687
-	 * @param string $ocName the internal Nextcloud username
688
-	 */
689
-	public function cacheUserExists($ocName) {
690
-		$this->connection->writeToCache('userExists'.$ocName, true);
691
-	}
692
-
693
-	/**
694
-	 * caches the user display name
695
-	 * @param string $ocName the internal Nextcloud username
696
-	 * @param string $displayName the display name
697
-	 * @param string $displayName2 the second display name
698
-	 */
699
-	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
700
-		$user = $this->userManager->get($ocName);
701
-		if($user === null) {
702
-			return;
703
-		}
704
-		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
705
-		$cacheKeyTrunk = 'getDisplayName';
706
-		$this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
707
-	}
708
-
709
-	/**
710
-	 * creates a unique name for internal Nextcloud use for users. Don't call it directly.
711
-	 * @param string $name the display name of the object
712
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
713
-	 *
714
-	 * Instead of using this method directly, call
715
-	 * createAltInternalOwnCloudName($name, true)
716
-	 */
717
-	private function _createAltInternalOwnCloudNameForUsers($name) {
718
-		$attempts = 0;
719
-		//while loop is just a precaution. If a name is not generated within
720
-		//20 attempts, something else is very wrong. Avoids infinite loop.
721
-		while($attempts < 20){
722
-			$altName = $name . '_' . rand(1000,9999);
723
-			if(!\OCP\User::userExists($altName)) {
724
-				return $altName;
725
-			}
726
-			$attempts++;
727
-		}
728
-		return false;
729
-	}
730
-
731
-	/**
732
-	 * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
733
-	 * @param string $name the display name of the object
734
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
735
-	 *
736
-	 * Instead of using this method directly, call
737
-	 * createAltInternalOwnCloudName($name, false)
738
-	 *
739
-	 * Group names are also used as display names, so we do a sequential
740
-	 * numbering, e.g. Developers_42 when there are 41 other groups called
741
-	 * "Developers"
742
-	 */
743
-	private function _createAltInternalOwnCloudNameForGroups($name) {
744
-		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
745
-		if(!($usedNames) || count($usedNames) === 0) {
746
-			$lastNo = 1; //will become name_2
747
-		} else {
748
-			natsort($usedNames);
749
-			$lastName = array_pop($usedNames);
750
-			$lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
751
-		}
752
-		$altName = $name.'_'.strval($lastNo+1);
753
-		unset($usedNames);
754
-
755
-		$attempts = 1;
756
-		while($attempts < 21){
757
-			// Check to be really sure it is unique
758
-			// while loop is just a precaution. If a name is not generated within
759
-			// 20 attempts, something else is very wrong. Avoids infinite loop.
760
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
761
-				return $altName;
762
-			}
763
-			$altName = $name . '_' . ($lastNo + $attempts);
764
-			$attempts++;
765
-		}
766
-		return false;
767
-	}
768
-
769
-	/**
770
-	 * creates a unique name for internal Nextcloud use.
771
-	 * @param string $name the display name of the object
772
-	 * @param boolean $isUser whether name should be created for a user (true) or a group (false)
773
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
774
-	 */
775
-	private function createAltInternalOwnCloudName($name, $isUser) {
776
-		$originalTTL = $this->connection->ldapCacheTTL;
777
-		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
778
-		if($isUser) {
779
-			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
780
-		} else {
781
-			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
782
-		}
783
-		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
784
-
785
-		return $altName;
786
-	}
787
-
788
-	/**
789
-	 * fetches a list of users according to a provided loginName and utilizing
790
-	 * the login filter.
791
-	 *
792
-	 * @param string $loginName
793
-	 * @param array $attributes optional, list of attributes to read
794
-	 * @return array
795
-	 */
796
-	public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
797
-		$loginName = $this->escapeFilterPart($loginName);
798
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
799
-		$users = $this->fetchListOfUsers($filter, $attributes);
800
-		return $users;
801
-	}
802
-
803
-	/**
804
-	 * counts the number of users according to a provided loginName and
805
-	 * utilizing the login filter.
806
-	 *
807
-	 * @param string $loginName
808
-	 * @return int
809
-	 */
810
-	public function countUsersByLoginName($loginName) {
811
-		$loginName = $this->escapeFilterPart($loginName);
812
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
813
-		$users = $this->countUsers($filter);
814
-		return $users;
815
-	}
816
-
817
-	/**
818
-	 * @param string $filter
819
-	 * @param string|string[] $attr
820
-	 * @param int $limit
821
-	 * @param int $offset
822
-	 * @param bool $forceApplyAttributes
823
-	 * @return array
824
-	 */
825
-	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
826
-		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
827
-		$recordsToUpdate = $ldapRecords;
828
-		if(!$forceApplyAttributes) {
829
-			$isBackgroundJobModeAjax = $this->config
830
-					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
831
-			$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
832
-				$newlyMapped = false;
833
-				$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
834
-				if(is_string($uid)) {
835
-					$this->cacheUserExists($uid);
836
-				}
837
-				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
838
-			});
839
-		}
840
-		$this->batchApplyUserAttributes($recordsToUpdate);
841
-		return $this->fetchList($ldapRecords, (count($attr) > 1));
842
-	}
843
-
844
-	/**
845
-	 * provided with an array of LDAP user records the method will fetch the
846
-	 * user object and requests it to process the freshly fetched attributes and
847
-	 * and their values
848
-	 * @param array $ldapRecords
849
-	 */
850
-	public function batchApplyUserAttributes(array $ldapRecords){
851
-		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
852
-		foreach($ldapRecords as $userRecord) {
853
-			if(!isset($userRecord[$displayNameAttribute])) {
854
-				// displayName is obligatory
855
-				continue;
856
-			}
857
-			$ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
858
-			if($ocName === false) {
859
-				continue;
860
-			}
861
-			$user = $this->userManager->get($ocName);
862
-			if($user instanceof OfflineUser) {
863
-				$user->unmark();
864
-				$user = $this->userManager->get($ocName);
865
-			}
866
-			if ($user !== null) {
867
-				$user->processAttributes($userRecord);
868
-			} else {
869
-				\OC::$server->getLogger()->debug(
870
-					"The ldap user manager returned null for $ocName",
871
-					['app'=>'user_ldap']
872
-				);
873
-			}
874
-		}
875
-	}
876
-
877
-	/**
878
-	 * @param string $filter
879
-	 * @param string|string[] $attr
880
-	 * @param int $limit
881
-	 * @param int $offset
882
-	 * @return array
883
-	 */
884
-	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
885
-		return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1));
886
-	}
887
-
888
-	/**
889
-	 * @param array $list
890
-	 * @param bool $manyAttributes
891
-	 * @return array
892
-	 */
893
-	private function fetchList($list, $manyAttributes) {
894
-		if(is_array($list)) {
895
-			if($manyAttributes) {
896
-				return $list;
897
-			} else {
898
-				$list = array_reduce($list, function($carry, $item) {
899
-					$attribute = array_keys($item)[0];
900
-					$carry[] = $item[$attribute][0];
901
-					return $carry;
902
-				}, array());
903
-				return array_unique($list, SORT_LOCALE_STRING);
904
-			}
905
-		}
906
-
907
-		//error cause actually, maybe throw an exception in future.
908
-		return array();
909
-	}
910
-
911
-	/**
912
-	 * executes an LDAP search, optimized for Users
913
-	 * @param string $filter the LDAP filter for the search
914
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
915
-	 * @param integer $limit
916
-	 * @param integer $offset
917
-	 * @return array with the search result
918
-	 *
919
-	 * Executes an LDAP search
920
-	 */
921
-	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
922
-		return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
923
-	}
924
-
925
-	/**
926
-	 * @param string $filter
927
-	 * @param string|string[] $attr
928
-	 * @param int $limit
929
-	 * @param int $offset
930
-	 * @return false|int
931
-	 */
932
-	public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) {
933
-		return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
934
-	}
935
-
936
-	/**
937
-	 * executes an LDAP search, optimized for Groups
938
-	 * @param string $filter the LDAP filter for the search
939
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
940
-	 * @param integer $limit
941
-	 * @param integer $offset
942
-	 * @return array with the search result
943
-	 *
944
-	 * Executes an LDAP search
945
-	 */
946
-	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
947
-		return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
948
-	}
949
-
950
-	/**
951
-	 * returns the number of available groups
952
-	 * @param string $filter the LDAP search filter
953
-	 * @param string[] $attr optional
954
-	 * @param int|null $limit
955
-	 * @param int|null $offset
956
-	 * @return int|bool
957
-	 */
958
-	public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) {
959
-		return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
960
-	}
961
-
962
-	/**
963
-	 * returns the number of available objects on the base DN
964
-	 *
965
-	 * @param int|null $limit
966
-	 * @param int|null $offset
967
-	 * @return int|bool
968
-	 */
969
-	public function countObjects($limit = null, $offset = null) {
970
-		return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset);
971
-	}
972
-
973
-	/**
974
-	 * Returns the LDAP handler
975
-	 * @throws \OC\ServerNotAvailableException
976
-	 */
977
-
978
-	/**
979
-	 * @return mixed
980
-	 * @throws \OC\ServerNotAvailableException
981
-	 */
982
-	private function invokeLDAPMethod() {
983
-		$arguments = func_get_args();
984
-		$command = array_shift($arguments);
985
-		$cr = array_shift($arguments);
986
-		if (!method_exists($this->ldap, $command)) {
987
-			return null;
988
-		}
989
-		array_unshift($arguments, $cr);
990
-		// php no longer supports call-time pass-by-reference
991
-		// thus cannot support controlPagedResultResponse as the third argument
992
-		// is a reference
993
-		$doMethod = function () use ($command, &$arguments) {
994
-			if ($command == 'controlPagedResultResponse') {
995
-				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
996
-			} else {
997
-				return call_user_func_array(array($this->ldap, $command), $arguments);
998
-			}
999
-		};
1000
-		try {
1001
-			$ret = $doMethod();
1002
-		} catch (ServerNotAvailableException $e) {
1003
-			/* Server connection lost, attempt to reestablish it
341
+    /**
342
+     * Set password for an LDAP user identified by a DN
343
+     *
344
+     * @param string $userDN the user in question
345
+     * @param string $password the new password
346
+     * @return bool
347
+     * @throws HintException
348
+     * @throws \Exception
349
+     */
350
+    public function setPassword($userDN, $password) {
351
+        if(intval($this->connection->turnOnPasswordChange) !== 1) {
352
+            throw new \Exception('LDAP password changes are disabled.');
353
+        }
354
+        $cr = $this->connection->getConnectionResource();
355
+        if(!$this->ldap->isResource($cr)) {
356
+            //LDAP not available
357
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
358
+            return false;
359
+        }
360
+        try {
361
+            return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
362
+        } catch(ConstraintViolationException $e) {
363
+            throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
364
+        }
365
+    }
366
+
367
+    /**
368
+     * checks whether the given attributes value is probably a DN
369
+     * @param string $attr the attribute in question
370
+     * @return boolean if so true, otherwise false
371
+     */
372
+    private function resemblesDN($attr) {
373
+        $resemblingAttributes = array(
374
+            'dn',
375
+            'uniquemember',
376
+            'member',
377
+            // memberOf is an "operational" attribute, without a definition in any RFC
378
+            'memberof'
379
+        );
380
+        return in_array($attr, $resemblingAttributes);
381
+    }
382
+
383
+    /**
384
+     * checks whether the given string is probably a DN
385
+     * @param string $string
386
+     * @return boolean
387
+     */
388
+    public function stringResemblesDN($string) {
389
+        $r = $this->ldap->explodeDN($string, 0);
390
+        // if exploding a DN succeeds and does not end up in
391
+        // an empty array except for $r[count] being 0.
392
+        return (is_array($r) && count($r) > 1);
393
+    }
394
+
395
+    /**
396
+     * returns a DN-string that is cleaned from not domain parts, e.g.
397
+     * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
398
+     * becomes dc=foobar,dc=server,dc=org
399
+     * @param string $dn
400
+     * @return string
401
+     */
402
+    public function getDomainDNFromDN($dn) {
403
+        $allParts = $this->ldap->explodeDN($dn, 0);
404
+        if($allParts === false) {
405
+            //not a valid DN
406
+            return '';
407
+        }
408
+        $domainParts = array();
409
+        $dcFound = false;
410
+        foreach($allParts as $part) {
411
+            if(!$dcFound && strpos($part, 'dc=') === 0) {
412
+                $dcFound = true;
413
+            }
414
+            if($dcFound) {
415
+                $domainParts[] = $part;
416
+            }
417
+        }
418
+        $domainDN = implode(',', $domainParts);
419
+        return $domainDN;
420
+    }
421
+
422
+    /**
423
+     * returns the LDAP DN for the given internal Nextcloud name of the group
424
+     * @param string $name the Nextcloud name in question
425
+     * @return string|false LDAP DN on success, otherwise false
426
+     */
427
+    public function groupname2dn($name) {
428
+        return $this->groupMapper->getDNByName($name);
429
+    }
430
+
431
+    /**
432
+     * returns the LDAP DN for the given internal Nextcloud name of the user
433
+     * @param string $name the Nextcloud name in question
434
+     * @return string|false with the LDAP DN on success, otherwise false
435
+     */
436
+    public function username2dn($name) {
437
+        $fdn = $this->userMapper->getDNByName($name);
438
+
439
+        //Check whether the DN belongs to the Base, to avoid issues on multi-
440
+        //server setups
441
+        if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
442
+            return $fdn;
443
+        }
444
+
445
+        return false;
446
+    }
447
+
448
+    /**
449
+     * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
450
+     * @param string $fdn the dn of the group object
451
+     * @param string $ldapName optional, the display name of the object
452
+     * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
453
+     */
454
+    public function dn2groupname($fdn, $ldapName = null) {
455
+        //To avoid bypassing the base DN settings under certain circumstances
456
+        //with the group support, check whether the provided DN matches one of
457
+        //the given Bases
458
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
459
+            return false;
460
+        }
461
+
462
+        return $this->dn2ocname($fdn, $ldapName, false);
463
+    }
464
+
465
+    /**
466
+     * accepts an array of group DNs and tests whether they match the user
467
+     * filter by doing read operations against the group entries. Returns an
468
+     * array of DNs that match the filter.
469
+     *
470
+     * @param string[] $groupDNs
471
+     * @return string[]
472
+     */
473
+    public function groupsMatchFilter($groupDNs) {
474
+        $validGroupDNs = [];
475
+        foreach($groupDNs as $dn) {
476
+            $cacheKey = 'groupsMatchFilter-'.$dn;
477
+            $groupMatchFilter = $this->connection->getFromCache($cacheKey);
478
+            if(!is_null($groupMatchFilter)) {
479
+                if($groupMatchFilter) {
480
+                    $validGroupDNs[] = $dn;
481
+                }
482
+                continue;
483
+            }
484
+
485
+            // Check the base DN first. If this is not met already, we don't
486
+            // need to ask the server at all.
487
+            if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
488
+                $this->connection->writeToCache($cacheKey, false);
489
+                continue;
490
+            }
491
+
492
+            $result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
493
+            if(is_array($result)) {
494
+                $this->connection->writeToCache($cacheKey, true);
495
+                $validGroupDNs[] = $dn;
496
+            } else {
497
+                $this->connection->writeToCache($cacheKey, false);
498
+            }
499
+
500
+        }
501
+        return $validGroupDNs;
502
+    }
503
+
504
+    /**
505
+     * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
506
+     * @param string $dn the dn of the user object
507
+     * @param string $ldapName optional, the display name of the object
508
+     * @return string|false with with the name to use in Nextcloud
509
+     */
510
+    public function dn2username($fdn, $ldapName = null) {
511
+        //To avoid bypassing the base DN settings under certain circumstances
512
+        //with the group support, check whether the provided DN matches one of
513
+        //the given Bases
514
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
515
+            return false;
516
+        }
517
+
518
+        return $this->dn2ocname($fdn, $ldapName, true);
519
+    }
520
+
521
+    /**
522
+     * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
523
+     *
524
+     * @param string $fdn the dn of the user object
525
+     * @param string|null $ldapName optional, the display name of the object
526
+     * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
527
+     * @param bool|null $newlyMapped
528
+     * @param array|null $record
529
+     * @return false|string with with the name to use in Nextcloud
530
+     * @throws \Exception
531
+     */
532
+    public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
533
+        $newlyMapped = false;
534
+        if($isUser) {
535
+            $mapper = $this->getUserMapper();
536
+            $nameAttribute = $this->connection->ldapUserDisplayName;
537
+        } else {
538
+            $mapper = $this->getGroupMapper();
539
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
540
+        }
541
+
542
+        //let's try to retrieve the Nextcloud name from the mappings table
543
+        $ncName = $mapper->getNameByDN($fdn);
544
+        if(is_string($ncName)) {
545
+            return $ncName;
546
+        }
547
+
548
+        //second try: get the UUID and check if it is known. Then, update the DN and return the name.
549
+        $uuid = $this->getUUID($fdn, $isUser, $record);
550
+        if(is_string($uuid)) {
551
+            $ncName = $mapper->getNameByUUID($uuid);
552
+            if(is_string($ncName)) {
553
+                $mapper->setDNbyUUID($fdn, $uuid);
554
+                return $ncName;
555
+            }
556
+        } else {
557
+            //If the UUID can't be detected something is foul.
558
+            \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', \OCP\Util::INFO);
559
+            return false;
560
+        }
561
+
562
+        if(is_null($ldapName)) {
563
+            $ldapName = $this->readAttribute($fdn, $nameAttribute);
564
+            if(!isset($ldapName[0]) && empty($ldapName[0])) {
565
+                \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
566
+                return false;
567
+            }
568
+            $ldapName = $ldapName[0];
569
+        }
570
+
571
+        if($isUser) {
572
+            $usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
573
+            if ($usernameAttribute !== '') {
574
+                $username = $this->readAttribute($fdn, $usernameAttribute);
575
+                $username = $username[0];
576
+            } else {
577
+                $username = $uuid;
578
+            }
579
+            $intName = $this->sanitizeUsername($username);
580
+        } else {
581
+            $intName = $ldapName;
582
+        }
583
+
584
+        //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
585
+        //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
586
+        //NOTE: mind, disabling cache affects only this instance! Using it
587
+        // outside of core user management will still cache the user as non-existing.
588
+        $originalTTL = $this->connection->ldapCacheTTL;
589
+        $this->connection->setConfiguration(array('ldapCacheTTL' => 0));
590
+        if(($isUser && $intName !== '' && !\OCP\User::userExists($intName))
591
+            || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
592
+            if($mapper->map($fdn, $intName, $uuid)) {
593
+                $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
594
+                $newlyMapped = true;
595
+                return $intName;
596
+            }
597
+        }
598
+        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
599
+
600
+        $altName = $this->createAltInternalOwnCloudName($intName, $isUser);
601
+        if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
602
+            $newlyMapped = true;
603
+            return $altName;
604
+        }
605
+
606
+        //if everything else did not help..
607
+        \OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', \OCP\Util::INFO);
608
+        return false;
609
+    }
610
+
611
+    /**
612
+     * gives back the user names as they are used ownClod internally
613
+     * @param array $ldapUsers as returned by fetchList()
614
+     * @return array an array with the user names to use in Nextcloud
615
+     *
616
+     * gives back the user names as they are used ownClod internally
617
+     */
618
+    public function nextcloudUserNames($ldapUsers) {
619
+        return $this->ldap2NextcloudNames($ldapUsers, true);
620
+    }
621
+
622
+    /**
623
+     * gives back the group names as they are used ownClod internally
624
+     * @param array $ldapGroups as returned by fetchList()
625
+     * @return array an array with the group names to use in Nextcloud
626
+     *
627
+     * gives back the group names as they are used ownClod internally
628
+     */
629
+    public function nextcloudGroupNames($ldapGroups) {
630
+        return $this->ldap2NextcloudNames($ldapGroups, false);
631
+    }
632
+
633
+    /**
634
+     * @param array $ldapObjects as returned by fetchList()
635
+     * @param bool $isUsers
636
+     * @return array
637
+     */
638
+    private function ldap2NextcloudNames($ldapObjects, $isUsers) {
639
+        if($isUsers) {
640
+            $nameAttribute = $this->connection->ldapUserDisplayName;
641
+            $sndAttribute  = $this->connection->ldapUserDisplayName2;
642
+        } else {
643
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
644
+        }
645
+        $nextcloudNames = array();
646
+
647
+        foreach($ldapObjects as $ldapObject) {
648
+            $nameByLDAP = null;
649
+            if(    isset($ldapObject[$nameAttribute])
650
+                && is_array($ldapObject[$nameAttribute])
651
+                && isset($ldapObject[$nameAttribute][0])
652
+            ) {
653
+                // might be set, but not necessarily. if so, we use it.
654
+                $nameByLDAP = $ldapObject[$nameAttribute][0];
655
+            }
656
+
657
+            $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
658
+            if($ncName) {
659
+                $nextcloudNames[] = $ncName;
660
+                if($isUsers) {
661
+                    //cache the user names so it does not need to be retrieved
662
+                    //again later (e.g. sharing dialogue).
663
+                    if(is_null($nameByLDAP)) {
664
+                        continue;
665
+                    }
666
+                    $sndName = isset($ldapObject[$sndAttribute][0])
667
+                        ? $ldapObject[$sndAttribute][0] : '';
668
+                    $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
669
+                }
670
+            }
671
+        }
672
+        return $nextcloudNames;
673
+    }
674
+
675
+    /**
676
+     * caches the user display name
677
+     * @param string $ocName the internal Nextcloud username
678
+     * @param string|false $home the home directory path
679
+     */
680
+    public function cacheUserHome($ocName, $home) {
681
+        $cacheKey = 'getHome'.$ocName;
682
+        $this->connection->writeToCache($cacheKey, $home);
683
+    }
684
+
685
+    /**
686
+     * caches a user as existing
687
+     * @param string $ocName the internal Nextcloud username
688
+     */
689
+    public function cacheUserExists($ocName) {
690
+        $this->connection->writeToCache('userExists'.$ocName, true);
691
+    }
692
+
693
+    /**
694
+     * caches the user display name
695
+     * @param string $ocName the internal Nextcloud username
696
+     * @param string $displayName the display name
697
+     * @param string $displayName2 the second display name
698
+     */
699
+    public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
700
+        $user = $this->userManager->get($ocName);
701
+        if($user === null) {
702
+            return;
703
+        }
704
+        $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
705
+        $cacheKeyTrunk = 'getDisplayName';
706
+        $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
707
+    }
708
+
709
+    /**
710
+     * creates a unique name for internal Nextcloud use for users. Don't call it directly.
711
+     * @param string $name the display name of the object
712
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
713
+     *
714
+     * Instead of using this method directly, call
715
+     * createAltInternalOwnCloudName($name, true)
716
+     */
717
+    private function _createAltInternalOwnCloudNameForUsers($name) {
718
+        $attempts = 0;
719
+        //while loop is just a precaution. If a name is not generated within
720
+        //20 attempts, something else is very wrong. Avoids infinite loop.
721
+        while($attempts < 20){
722
+            $altName = $name . '_' . rand(1000,9999);
723
+            if(!\OCP\User::userExists($altName)) {
724
+                return $altName;
725
+            }
726
+            $attempts++;
727
+        }
728
+        return false;
729
+    }
730
+
731
+    /**
732
+     * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
733
+     * @param string $name the display name of the object
734
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
735
+     *
736
+     * Instead of using this method directly, call
737
+     * createAltInternalOwnCloudName($name, false)
738
+     *
739
+     * Group names are also used as display names, so we do a sequential
740
+     * numbering, e.g. Developers_42 when there are 41 other groups called
741
+     * "Developers"
742
+     */
743
+    private function _createAltInternalOwnCloudNameForGroups($name) {
744
+        $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
745
+        if(!($usedNames) || count($usedNames) === 0) {
746
+            $lastNo = 1; //will become name_2
747
+        } else {
748
+            natsort($usedNames);
749
+            $lastName = array_pop($usedNames);
750
+            $lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
751
+        }
752
+        $altName = $name.'_'.strval($lastNo+1);
753
+        unset($usedNames);
754
+
755
+        $attempts = 1;
756
+        while($attempts < 21){
757
+            // Check to be really sure it is unique
758
+            // while loop is just a precaution. If a name is not generated within
759
+            // 20 attempts, something else is very wrong. Avoids infinite loop.
760
+            if(!\OC::$server->getGroupManager()->groupExists($altName)) {
761
+                return $altName;
762
+            }
763
+            $altName = $name . '_' . ($lastNo + $attempts);
764
+            $attempts++;
765
+        }
766
+        return false;
767
+    }
768
+
769
+    /**
770
+     * creates a unique name for internal Nextcloud use.
771
+     * @param string $name the display name of the object
772
+     * @param boolean $isUser whether name should be created for a user (true) or a group (false)
773
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
774
+     */
775
+    private function createAltInternalOwnCloudName($name, $isUser) {
776
+        $originalTTL = $this->connection->ldapCacheTTL;
777
+        $this->connection->setConfiguration(array('ldapCacheTTL' => 0));
778
+        if($isUser) {
779
+            $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
780
+        } else {
781
+            $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
782
+        }
783
+        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
784
+
785
+        return $altName;
786
+    }
787
+
788
+    /**
789
+     * fetches a list of users according to a provided loginName and utilizing
790
+     * the login filter.
791
+     *
792
+     * @param string $loginName
793
+     * @param array $attributes optional, list of attributes to read
794
+     * @return array
795
+     */
796
+    public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
797
+        $loginName = $this->escapeFilterPart($loginName);
798
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
799
+        $users = $this->fetchListOfUsers($filter, $attributes);
800
+        return $users;
801
+    }
802
+
803
+    /**
804
+     * counts the number of users according to a provided loginName and
805
+     * utilizing the login filter.
806
+     *
807
+     * @param string $loginName
808
+     * @return int
809
+     */
810
+    public function countUsersByLoginName($loginName) {
811
+        $loginName = $this->escapeFilterPart($loginName);
812
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
813
+        $users = $this->countUsers($filter);
814
+        return $users;
815
+    }
816
+
817
+    /**
818
+     * @param string $filter
819
+     * @param string|string[] $attr
820
+     * @param int $limit
821
+     * @param int $offset
822
+     * @param bool $forceApplyAttributes
823
+     * @return array
824
+     */
825
+    public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
826
+        $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
827
+        $recordsToUpdate = $ldapRecords;
828
+        if(!$forceApplyAttributes) {
829
+            $isBackgroundJobModeAjax = $this->config
830
+                    ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
831
+            $recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
832
+                $newlyMapped = false;
833
+                $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
834
+                if(is_string($uid)) {
835
+                    $this->cacheUserExists($uid);
836
+                }
837
+                return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
838
+            });
839
+        }
840
+        $this->batchApplyUserAttributes($recordsToUpdate);
841
+        return $this->fetchList($ldapRecords, (count($attr) > 1));
842
+    }
843
+
844
+    /**
845
+     * provided with an array of LDAP user records the method will fetch the
846
+     * user object and requests it to process the freshly fetched attributes and
847
+     * and their values
848
+     * @param array $ldapRecords
849
+     */
850
+    public function batchApplyUserAttributes(array $ldapRecords){
851
+        $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
852
+        foreach($ldapRecords as $userRecord) {
853
+            if(!isset($userRecord[$displayNameAttribute])) {
854
+                // displayName is obligatory
855
+                continue;
856
+            }
857
+            $ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
858
+            if($ocName === false) {
859
+                continue;
860
+            }
861
+            $user = $this->userManager->get($ocName);
862
+            if($user instanceof OfflineUser) {
863
+                $user->unmark();
864
+                $user = $this->userManager->get($ocName);
865
+            }
866
+            if ($user !== null) {
867
+                $user->processAttributes($userRecord);
868
+            } else {
869
+                \OC::$server->getLogger()->debug(
870
+                    "The ldap user manager returned null for $ocName",
871
+                    ['app'=>'user_ldap']
872
+                );
873
+            }
874
+        }
875
+    }
876
+
877
+    /**
878
+     * @param string $filter
879
+     * @param string|string[] $attr
880
+     * @param int $limit
881
+     * @param int $offset
882
+     * @return array
883
+     */
884
+    public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
885
+        return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1));
886
+    }
887
+
888
+    /**
889
+     * @param array $list
890
+     * @param bool $manyAttributes
891
+     * @return array
892
+     */
893
+    private function fetchList($list, $manyAttributes) {
894
+        if(is_array($list)) {
895
+            if($manyAttributes) {
896
+                return $list;
897
+            } else {
898
+                $list = array_reduce($list, function($carry, $item) {
899
+                    $attribute = array_keys($item)[0];
900
+                    $carry[] = $item[$attribute][0];
901
+                    return $carry;
902
+                }, array());
903
+                return array_unique($list, SORT_LOCALE_STRING);
904
+            }
905
+        }
906
+
907
+        //error cause actually, maybe throw an exception in future.
908
+        return array();
909
+    }
910
+
911
+    /**
912
+     * executes an LDAP search, optimized for Users
913
+     * @param string $filter the LDAP filter for the search
914
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
915
+     * @param integer $limit
916
+     * @param integer $offset
917
+     * @return array with the search result
918
+     *
919
+     * Executes an LDAP search
920
+     */
921
+    public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
922
+        return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
923
+    }
924
+
925
+    /**
926
+     * @param string $filter
927
+     * @param string|string[] $attr
928
+     * @param int $limit
929
+     * @param int $offset
930
+     * @return false|int
931
+     */
932
+    public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) {
933
+        return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
934
+    }
935
+
936
+    /**
937
+     * executes an LDAP search, optimized for Groups
938
+     * @param string $filter the LDAP filter for the search
939
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
940
+     * @param integer $limit
941
+     * @param integer $offset
942
+     * @return array with the search result
943
+     *
944
+     * Executes an LDAP search
945
+     */
946
+    public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
947
+        return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
948
+    }
949
+
950
+    /**
951
+     * returns the number of available groups
952
+     * @param string $filter the LDAP search filter
953
+     * @param string[] $attr optional
954
+     * @param int|null $limit
955
+     * @param int|null $offset
956
+     * @return int|bool
957
+     */
958
+    public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) {
959
+        return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
960
+    }
961
+
962
+    /**
963
+     * returns the number of available objects on the base DN
964
+     *
965
+     * @param int|null $limit
966
+     * @param int|null $offset
967
+     * @return int|bool
968
+     */
969
+    public function countObjects($limit = null, $offset = null) {
970
+        return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset);
971
+    }
972
+
973
+    /**
974
+     * Returns the LDAP handler
975
+     * @throws \OC\ServerNotAvailableException
976
+     */
977
+
978
+    /**
979
+     * @return mixed
980
+     * @throws \OC\ServerNotAvailableException
981
+     */
982
+    private function invokeLDAPMethod() {
983
+        $arguments = func_get_args();
984
+        $command = array_shift($arguments);
985
+        $cr = array_shift($arguments);
986
+        if (!method_exists($this->ldap, $command)) {
987
+            return null;
988
+        }
989
+        array_unshift($arguments, $cr);
990
+        // php no longer supports call-time pass-by-reference
991
+        // thus cannot support controlPagedResultResponse as the third argument
992
+        // is a reference
993
+        $doMethod = function () use ($command, &$arguments) {
994
+            if ($command == 'controlPagedResultResponse') {
995
+                throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
996
+            } else {
997
+                return call_user_func_array(array($this->ldap, $command), $arguments);
998
+            }
999
+        };
1000
+        try {
1001
+            $ret = $doMethod();
1002
+        } catch (ServerNotAvailableException $e) {
1003
+            /* Server connection lost, attempt to reestablish it
1004 1004
 			 * Maybe implement exponential backoff?
1005 1005
 			 * This was enough to get solr indexer working which has large delays between LDAP fetches.
1006 1006
 			 */
1007
-			\OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", \OCP\Util::DEBUG);
1008
-			$this->connection->resetConnectionResource();
1009
-			$cr = $this->connection->getConnectionResource();
1010
-
1011
-			if(!$this->ldap->isResource($cr)) {
1012
-				// Seems like we didn't find any resource.
1013
-				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", \OCP\Util::DEBUG);
1014
-				throw $e;
1015
-			}
1016
-
1017
-			$arguments[0] = array_pad([], count($arguments[0]), $cr);
1018
-			$ret = $doMethod();
1019
-		}
1020
-		return $ret;
1021
-	}
1022
-
1023
-	/**
1024
-	 * retrieved. Results will according to the order in the array.
1025
-	 *
1026
-	 * @param $filter
1027
-	 * @param $base
1028
-	 * @param string[]|string|null $attr
1029
-	 * @param int $limit optional, maximum results to be counted
1030
-	 * @param int $offset optional, a starting point
1031
-	 * @return array|false array with the search result as first value and pagedSearchOK as
1032
-	 * second | false if not successful
1033
-	 * @throws ServerNotAvailableException
1034
-	 */
1035
-	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1036
-		if(!is_null($attr) && !is_array($attr)) {
1037
-			$attr = array(mb_strtolower($attr, 'UTF-8'));
1038
-		}
1039
-
1040
-		// See if we have a resource, in case not cancel with message
1041
-		$cr = $this->connection->getConnectionResource();
1042
-		if(!$this->ldap->isResource($cr)) {
1043
-			// Seems like we didn't find any resource.
1044
-			// Return an empty array just like before.
1045
-			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
1046
-			return false;
1047
-		}
1048
-
1049
-		//check whether paged search should be attempted
1050
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, intval($limit), $offset);
1051
-
1052
-		$linkResources = array_pad(array(), count($base), $cr);
1053
-		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1054
-		// cannot use $cr anymore, might have changed in the previous call!
1055
-		$error = $this->ldap->errno($this->connection->getConnectionResource());
1056
-		if(!is_array($sr) || $error !== 0) {
1057
-			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
1058
-			return false;
1059
-		}
1060
-
1061
-		return array($sr, $pagedSearchOK);
1062
-	}
1063
-
1064
-	/**
1065
-	 * processes an LDAP paged search operation
1066
-	 * @param array $sr the array containing the LDAP search resources
1067
-	 * @param string $filter the LDAP filter for the search
1068
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1069
-	 * @param int $iFoundItems number of results in the single search operation
1070
-	 * @param int $limit maximum results to be counted
1071
-	 * @param int $offset a starting point
1072
-	 * @param bool $pagedSearchOK whether a paged search has been executed
1073
-	 * @param bool $skipHandling required for paged search when cookies to
1074
-	 * prior results need to be gained
1075
-	 * @return bool cookie validity, true if we have more pages, false otherwise.
1076
-	 */
1077
-	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1078
-		$cookie = null;
1079
-		if($pagedSearchOK) {
1080
-			$cr = $this->connection->getConnectionResource();
1081
-			foreach($sr as $key => $res) {
1082
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1083
-					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1084
-				}
1085
-			}
1086
-
1087
-			//browsing through prior pages to get the cookie for the new one
1088
-			if($skipHandling) {
1089
-				return false;
1090
-			}
1091
-			// if count is bigger, then the server does not support
1092
-			// paged search. Instead, he did a normal search. We set a
1093
-			// flag here, so the callee knows how to deal with it.
1094
-			if($iFoundItems <= $limit) {
1095
-				$this->pagedSearchedSuccessful = true;
1096
-			}
1097
-		} else {
1098
-			if(!is_null($limit)) {
1099
-				\OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO);
1100
-			}
1101
-		}
1102
-		/* ++ Fixing RHDS searches with pages with zero results ++
1007
+            \OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", \OCP\Util::DEBUG);
1008
+            $this->connection->resetConnectionResource();
1009
+            $cr = $this->connection->getConnectionResource();
1010
+
1011
+            if(!$this->ldap->isResource($cr)) {
1012
+                // Seems like we didn't find any resource.
1013
+                \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", \OCP\Util::DEBUG);
1014
+                throw $e;
1015
+            }
1016
+
1017
+            $arguments[0] = array_pad([], count($arguments[0]), $cr);
1018
+            $ret = $doMethod();
1019
+        }
1020
+        return $ret;
1021
+    }
1022
+
1023
+    /**
1024
+     * retrieved. Results will according to the order in the array.
1025
+     *
1026
+     * @param $filter
1027
+     * @param $base
1028
+     * @param string[]|string|null $attr
1029
+     * @param int $limit optional, maximum results to be counted
1030
+     * @param int $offset optional, a starting point
1031
+     * @return array|false array with the search result as first value and pagedSearchOK as
1032
+     * second | false if not successful
1033
+     * @throws ServerNotAvailableException
1034
+     */
1035
+    private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1036
+        if(!is_null($attr) && !is_array($attr)) {
1037
+            $attr = array(mb_strtolower($attr, 'UTF-8'));
1038
+        }
1039
+
1040
+        // See if we have a resource, in case not cancel with message
1041
+        $cr = $this->connection->getConnectionResource();
1042
+        if(!$this->ldap->isResource($cr)) {
1043
+            // Seems like we didn't find any resource.
1044
+            // Return an empty array just like before.
1045
+            \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
1046
+            return false;
1047
+        }
1048
+
1049
+        //check whether paged search should be attempted
1050
+        $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, intval($limit), $offset);
1051
+
1052
+        $linkResources = array_pad(array(), count($base), $cr);
1053
+        $sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1054
+        // cannot use $cr anymore, might have changed in the previous call!
1055
+        $error = $this->ldap->errno($this->connection->getConnectionResource());
1056
+        if(!is_array($sr) || $error !== 0) {
1057
+            \OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
1058
+            return false;
1059
+        }
1060
+
1061
+        return array($sr, $pagedSearchOK);
1062
+    }
1063
+
1064
+    /**
1065
+     * processes an LDAP paged search operation
1066
+     * @param array $sr the array containing the LDAP search resources
1067
+     * @param string $filter the LDAP filter for the search
1068
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1069
+     * @param int $iFoundItems number of results in the single search operation
1070
+     * @param int $limit maximum results to be counted
1071
+     * @param int $offset a starting point
1072
+     * @param bool $pagedSearchOK whether a paged search has been executed
1073
+     * @param bool $skipHandling required for paged search when cookies to
1074
+     * prior results need to be gained
1075
+     * @return bool cookie validity, true if we have more pages, false otherwise.
1076
+     */
1077
+    private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1078
+        $cookie = null;
1079
+        if($pagedSearchOK) {
1080
+            $cr = $this->connection->getConnectionResource();
1081
+            foreach($sr as $key => $res) {
1082
+                if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1083
+                    $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1084
+                }
1085
+            }
1086
+
1087
+            //browsing through prior pages to get the cookie for the new one
1088
+            if($skipHandling) {
1089
+                return false;
1090
+            }
1091
+            // if count is bigger, then the server does not support
1092
+            // paged search. Instead, he did a normal search. We set a
1093
+            // flag here, so the callee knows how to deal with it.
1094
+            if($iFoundItems <= $limit) {
1095
+                $this->pagedSearchedSuccessful = true;
1096
+            }
1097
+        } else {
1098
+            if(!is_null($limit)) {
1099
+                \OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO);
1100
+            }
1101
+        }
1102
+        /* ++ Fixing RHDS searches with pages with zero results ++
1103 1103
 		 * Return cookie status. If we don't have more pages, with RHDS
1104 1104
 		 * cookie is null, with openldap cookie is an empty string and
1105 1105
 		 * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0
1106 1106
 		 */
1107
-		return !empty($cookie) || $cookie === '0';
1108
-	}
1109
-
1110
-	/**
1111
-	 * executes an LDAP search, but counts the results only
1112
-	 *
1113
-	 * @param string $filter the LDAP filter for the search
1114
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1115
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1116
-	 * retrieved. Results will according to the order in the array.
1117
-	 * @param int $limit optional, maximum results to be counted
1118
-	 * @param int $offset optional, a starting point
1119
-	 * @param bool $skipHandling indicates whether the pages search operation is
1120
-	 * completed
1121
-	 * @return int|false Integer or false if the search could not be initialized
1122
-	 * @throws ServerNotAvailableException
1123
-	 */
1124
-	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1125
-		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1126
-
1127
-		$limitPerPage = intval($this->connection->ldapPagingSize);
1128
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1129
-			$limitPerPage = $limit;
1130
-		}
1131
-
1132
-		$counter = 0;
1133
-		$count = null;
1134
-		$this->connection->getConnectionResource();
1135
-
1136
-		do {
1137
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1138
-			if($search === false) {
1139
-				return $counter > 0 ? $counter : false;
1140
-			}
1141
-			list($sr, $pagedSearchOK) = $search;
1142
-
1143
-			/* ++ Fixing RHDS searches with pages with zero results ++
1107
+        return !empty($cookie) || $cookie === '0';
1108
+    }
1109
+
1110
+    /**
1111
+     * executes an LDAP search, but counts the results only
1112
+     *
1113
+     * @param string $filter the LDAP filter for the search
1114
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1115
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1116
+     * retrieved. Results will according to the order in the array.
1117
+     * @param int $limit optional, maximum results to be counted
1118
+     * @param int $offset optional, a starting point
1119
+     * @param bool $skipHandling indicates whether the pages search operation is
1120
+     * completed
1121
+     * @return int|false Integer or false if the search could not be initialized
1122
+     * @throws ServerNotAvailableException
1123
+     */
1124
+    private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1125
+        \OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1126
+
1127
+        $limitPerPage = intval($this->connection->ldapPagingSize);
1128
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1129
+            $limitPerPage = $limit;
1130
+        }
1131
+
1132
+        $counter = 0;
1133
+        $count = null;
1134
+        $this->connection->getConnectionResource();
1135
+
1136
+        do {
1137
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1138
+            if($search === false) {
1139
+                return $counter > 0 ? $counter : false;
1140
+            }
1141
+            list($sr, $pagedSearchOK) = $search;
1142
+
1143
+            /* ++ Fixing RHDS searches with pages with zero results ++
1144 1144
 			 * countEntriesInSearchResults() method signature changed
1145 1145
 			 * by removing $limit and &$hasHitLimit parameters
1146 1146
 			 */
1147
-			$count = $this->countEntriesInSearchResults($sr);
1148
-			$counter += $count;
1147
+            $count = $this->countEntriesInSearchResults($sr);
1148
+            $counter += $count;
1149 1149
 
1150
-			$hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1151
-										$offset, $pagedSearchOK, $skipHandling);
1152
-			$offset += $limitPerPage;
1153
-			/* ++ Fixing RHDS searches with pages with zero results ++
1150
+            $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1151
+                                        $offset, $pagedSearchOK, $skipHandling);
1152
+            $offset += $limitPerPage;
1153
+            /* ++ Fixing RHDS searches with pages with zero results ++
1154 1154
 			 * Continue now depends on $hasMorePages value
1155 1155
 			 */
1156
-			$continue = $pagedSearchOK && $hasMorePages;
1157
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1158
-
1159
-		return $counter;
1160
-	}
1161
-
1162
-	/**
1163
-	 * @param array $searchResults
1164
-	 * @return int
1165
-	 */
1166
-	private function countEntriesInSearchResults($searchResults) {
1167
-		$counter = 0;
1168
-
1169
-		foreach($searchResults as $res) {
1170
-			$count = intval($this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res));
1171
-			$counter += $count;
1172
-		}
1173
-
1174
-		return $counter;
1175
-	}
1176
-
1177
-	/**
1178
-	 * Executes an LDAP search
1179
-	 *
1180
-	 * @param string $filter the LDAP filter for the search
1181
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1182
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1183
-	 * @param int $limit
1184
-	 * @param int $offset
1185
-	 * @param bool $skipHandling
1186
-	 * @return array with the search result
1187
-	 * @throws ServerNotAvailableException
1188
-	 */
1189
-	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1190
-		$limitPerPage = intval($this->connection->ldapPagingSize);
1191
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1192
-			$limitPerPage = $limit;
1193
-		}
1194
-
1195
-		/* ++ Fixing RHDS searches with pages with zero results ++
1156
+            $continue = $pagedSearchOK && $hasMorePages;
1157
+        } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1158
+
1159
+        return $counter;
1160
+    }
1161
+
1162
+    /**
1163
+     * @param array $searchResults
1164
+     * @return int
1165
+     */
1166
+    private function countEntriesInSearchResults($searchResults) {
1167
+        $counter = 0;
1168
+
1169
+        foreach($searchResults as $res) {
1170
+            $count = intval($this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res));
1171
+            $counter += $count;
1172
+        }
1173
+
1174
+        return $counter;
1175
+    }
1176
+
1177
+    /**
1178
+     * Executes an LDAP search
1179
+     *
1180
+     * @param string $filter the LDAP filter for the search
1181
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1182
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1183
+     * @param int $limit
1184
+     * @param int $offset
1185
+     * @param bool $skipHandling
1186
+     * @return array with the search result
1187
+     * @throws ServerNotAvailableException
1188
+     */
1189
+    public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1190
+        $limitPerPage = intval($this->connection->ldapPagingSize);
1191
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1192
+            $limitPerPage = $limit;
1193
+        }
1194
+
1195
+        /* ++ Fixing RHDS searches with pages with zero results ++
1196 1196
 		 * As we can have pages with zero results and/or pages with less
1197 1197
 		 * than $limit results but with a still valid server 'cookie',
1198 1198
 		 * loops through until we get $continue equals true and
1199 1199
 		 * $findings['count'] < $limit
1200 1200
 		 */
1201
-		$findings = [];
1202
-		$savedoffset = $offset;
1203
-		do {
1204
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1205
-			if($search === false) {
1206
-				return [];
1207
-			}
1208
-			list($sr, $pagedSearchOK) = $search;
1209
-			$cr = $this->connection->getConnectionResource();
1210
-
1211
-			if($skipHandling) {
1212
-				//i.e. result do not need to be fetched, we just need the cookie
1213
-				//thus pass 1 or any other value as $iFoundItems because it is not
1214
-				//used
1215
-				$this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1216
-								$offset, $pagedSearchOK,
1217
-								$skipHandling);
1218
-				return array();
1219
-			}
1220
-
1221
-			$iFoundItems = 0;
1222
-			foreach($sr as $res) {
1223
-				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1224
-				$iFoundItems = max($iFoundItems, $findings['count']);
1225
-				unset($findings['count']);
1226
-			}
1227
-
1228
-			$continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1229
-				$limitPerPage, $offset, $pagedSearchOK,
1230
-										$skipHandling);
1231
-			$offset += $limitPerPage;
1232
-		} while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1233
-		// reseting offset
1234
-		$offset = $savedoffset;
1235
-
1236
-		// if we're here, probably no connection resource is returned.
1237
-		// to make Nextcloud behave nicely, we simply give back an empty array.
1238
-		if(is_null($findings)) {
1239
-			return array();
1240
-		}
1241
-
1242
-		if(!is_null($attr)) {
1243
-			$selection = [];
1244
-			$i = 0;
1245
-			foreach($findings as $item) {
1246
-				if(!is_array($item)) {
1247
-					continue;
1248
-				}
1249
-				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1250
-				foreach($attr as $key) {
1251
-					if(isset($item[$key])) {
1252
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1253
-							unset($item[$key]['count']);
1254
-						}
1255
-						if($key !== 'dn') {
1256
-							if($this->resemblesDN($key)) {
1257
-								$selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1258
-							} else if($key === 'objectguid' || $key === 'guid') {
1259
-								$selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1260
-							} else {
1261
-								$selection[$i][$key] = $item[$key];
1262
-							}
1263
-						} else {
1264
-							$selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1265
-						}
1266
-					}
1267
-
1268
-				}
1269
-				$i++;
1270
-			}
1271
-			$findings = $selection;
1272
-		}
1273
-		//we slice the findings, when
1274
-		//a) paged search unsuccessful, though attempted
1275
-		//b) no paged search, but limit set
1276
-		if((!$this->getPagedSearchResultState()
1277
-			&& $pagedSearchOK)
1278
-			|| (
1279
-				!$pagedSearchOK
1280
-				&& !is_null($limit)
1281
-			)
1282
-		) {
1283
-			$findings = array_slice($findings, intval($offset), $limit);
1284
-		}
1285
-		return $findings;
1286
-	}
1287
-
1288
-	/**
1289
-	 * @param string $name
1290
-	 * @return bool|mixed|string
1291
-	 */
1292
-	public function sanitizeUsername($name) {
1293
-		if($this->connection->ldapIgnoreNamingRules) {
1294
-			return trim($name);
1295
-		}
1296
-
1297
-		// Transliteration
1298
-		// latin characters to ASCII
1299
-		$name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1300
-
1301
-		// Replacements
1302
-		$name = str_replace(' ', '_', $name);
1303
-
1304
-		// Every remaining disallowed characters will be removed
1305
-		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1306
-
1307
-		return $name;
1308
-	}
1309
-
1310
-	/**
1311
-	* escapes (user provided) parts for LDAP filter
1312
-	* @param string $input, the provided value
1313
-	* @param bool $allowAsterisk whether in * at the beginning should be preserved
1314
-	* @return string the escaped string
1315
-	*/
1316
-	public function escapeFilterPart($input, $allowAsterisk = false) {
1317
-		$asterisk = '';
1318
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1319
-			$asterisk = '*';
1320
-			$input = mb_substr($input, 1, null, 'UTF-8');
1321
-		}
1322
-		$search  = array('*', '\\', '(', ')');
1323
-		$replace = array('\\*', '\\\\', '\\(', '\\)');
1324
-		return $asterisk . str_replace($search, $replace, $input);
1325
-	}
1326
-
1327
-	/**
1328
-	 * combines the input filters with AND
1329
-	 * @param string[] $filters the filters to connect
1330
-	 * @return string the combined filter
1331
-	 */
1332
-	public function combineFilterWithAnd($filters) {
1333
-		return $this->combineFilter($filters, '&');
1334
-	}
1335
-
1336
-	/**
1337
-	 * combines the input filters with OR
1338
-	 * @param string[] $filters the filters to connect
1339
-	 * @return string the combined filter
1340
-	 * Combines Filter arguments with OR
1341
-	 */
1342
-	public function combineFilterWithOr($filters) {
1343
-		return $this->combineFilter($filters, '|');
1344
-	}
1345
-
1346
-	/**
1347
-	 * combines the input filters with given operator
1348
-	 * @param string[] $filters the filters to connect
1349
-	 * @param string $operator either & or |
1350
-	 * @return string the combined filter
1351
-	 */
1352
-	private function combineFilter($filters, $operator) {
1353
-		$combinedFilter = '('.$operator;
1354
-		foreach($filters as $filter) {
1355
-			if ($filter !== '' && $filter[0] !== '(') {
1356
-				$filter = '('.$filter.')';
1357
-			}
1358
-			$combinedFilter.=$filter;
1359
-		}
1360
-		$combinedFilter.=')';
1361
-		return $combinedFilter;
1362
-	}
1363
-
1364
-	/**
1365
-	 * creates a filter part for to perform search for users
1366
-	 * @param string $search the search term
1367
-	 * @return string the final filter part to use in LDAP searches
1368
-	 */
1369
-	public function getFilterPartForUserSearch($search) {
1370
-		return $this->getFilterPartForSearch($search,
1371
-			$this->connection->ldapAttributesForUserSearch,
1372
-			$this->connection->ldapUserDisplayName);
1373
-	}
1374
-
1375
-	/**
1376
-	 * creates a filter part for to perform search for groups
1377
-	 * @param string $search the search term
1378
-	 * @return string the final filter part to use in LDAP searches
1379
-	 */
1380
-	public function getFilterPartForGroupSearch($search) {
1381
-		return $this->getFilterPartForSearch($search,
1382
-			$this->connection->ldapAttributesForGroupSearch,
1383
-			$this->connection->ldapGroupDisplayName);
1384
-	}
1385
-
1386
-	/**
1387
-	 * creates a filter part for searches by splitting up the given search
1388
-	 * string into single words
1389
-	 * @param string $search the search term
1390
-	 * @param string[] $searchAttributes needs to have at least two attributes,
1391
-	 * otherwise it does not make sense :)
1392
-	 * @return string the final filter part to use in LDAP searches
1393
-	 * @throws \Exception
1394
-	 */
1395
-	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1396
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1397
-			throw new \Exception('searchAttributes must be an array with at least two string');
1398
-		}
1399
-		$searchWords = explode(' ', trim($search));
1400
-		$wordFilters = array();
1401
-		foreach($searchWords as $word) {
1402
-			$word = $this->prepareSearchTerm($word);
1403
-			//every word needs to appear at least once
1404
-			$wordMatchOneAttrFilters = array();
1405
-			foreach($searchAttributes as $attr) {
1406
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1407
-			}
1408
-			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1409
-		}
1410
-		return $this->combineFilterWithAnd($wordFilters);
1411
-	}
1412
-
1413
-	/**
1414
-	 * creates a filter part for searches
1415
-	 * @param string $search the search term
1416
-	 * @param string[]|null $searchAttributes
1417
-	 * @param string $fallbackAttribute a fallback attribute in case the user
1418
-	 * did not define search attributes. Typically the display name attribute.
1419
-	 * @return string the final filter part to use in LDAP searches
1420
-	 */
1421
-	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1422
-		$filter = array();
1423
-		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1424
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1425
-			try {
1426
-				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1427
-			} catch(\Exception $e) {
1428
-				\OCP\Util::writeLog(
1429
-					'user_ldap',
1430
-					'Creating advanced filter for search failed, falling back to simple method.',
1431
-					\OCP\Util::INFO
1432
-				);
1433
-			}
1434
-		}
1435
-
1436
-		$search = $this->prepareSearchTerm($search);
1437
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1438
-			if ($fallbackAttribute === '') {
1439
-				return '';
1440
-			}
1441
-			$filter[] = $fallbackAttribute . '=' . $search;
1442
-		} else {
1443
-			foreach($searchAttributes as $attribute) {
1444
-				$filter[] = $attribute . '=' . $search;
1445
-			}
1446
-		}
1447
-		if(count($filter) === 1) {
1448
-			return '('.$filter[0].')';
1449
-		}
1450
-		return $this->combineFilterWithOr($filter);
1451
-	}
1452
-
1453
-	/**
1454
-	 * returns the search term depending on whether we are allowed
1455
-	 * list users found by ldap with the current input appended by
1456
-	 * a *
1457
-	 * @return string
1458
-	 */
1459
-	private function prepareSearchTerm($term) {
1460
-		$config = \OC::$server->getConfig();
1461
-
1462
-		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1463
-
1464
-		$result = $term;
1465
-		if ($term === '') {
1466
-			$result = '*';
1467
-		} else if ($allowEnum !== 'no') {
1468
-			$result = $term . '*';
1469
-		}
1470
-		return $result;
1471
-	}
1472
-
1473
-	/**
1474
-	 * returns the filter used for counting users
1475
-	 * @return string
1476
-	 */
1477
-	public function getFilterForUserCount() {
1478
-		$filter = $this->combineFilterWithAnd(array(
1479
-			$this->connection->ldapUserFilter,
1480
-			$this->connection->ldapUserDisplayName . '=*'
1481
-		));
1482
-
1483
-		return $filter;
1484
-	}
1485
-
1486
-	/**
1487
-	 * @param string $name
1488
-	 * @param string $password
1489
-	 * @return bool
1490
-	 */
1491
-	public function areCredentialsValid($name, $password) {
1492
-		$name = $this->helper->DNasBaseParameter($name);
1493
-		$testConnection = clone $this->connection;
1494
-		$credentials = array(
1495
-			'ldapAgentName' => $name,
1496
-			'ldapAgentPassword' => $password
1497
-		);
1498
-		if(!$testConnection->setConfiguration($credentials)) {
1499
-			return false;
1500
-		}
1501
-		return $testConnection->bind();
1502
-	}
1503
-
1504
-	/**
1505
-	 * reverse lookup of a DN given a known UUID
1506
-	 *
1507
-	 * @param string $uuid
1508
-	 * @return string
1509
-	 * @throws \Exception
1510
-	 */
1511
-	public function getUserDnByUuid($uuid) {
1512
-		$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1513
-		$filter       = $this->connection->ldapUserFilter;
1514
-		$base         = $this->connection->ldapBaseUsers;
1515
-
1516
-		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1517
-			// Sacrebleu! The UUID attribute is unknown :( We need first an
1518
-			// existing DN to be able to reliably detect it.
1519
-			$result = $this->search($filter, $base, ['dn'], 1);
1520
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1521
-				throw new \Exception('Cannot determine UUID attribute');
1522
-			}
1523
-			$dn = $result[0]['dn'][0];
1524
-			if(!$this->detectUuidAttribute($dn, true)) {
1525
-				throw new \Exception('Cannot determine UUID attribute');
1526
-			}
1527
-		} else {
1528
-			// The UUID attribute is either known or an override is given.
1529
-			// By calling this method we ensure that $this->connection->$uuidAttr
1530
-			// is definitely set
1531
-			if(!$this->detectUuidAttribute('', true)) {
1532
-				throw new \Exception('Cannot determine UUID attribute');
1533
-			}
1534
-		}
1535
-
1536
-		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1537
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1538
-			$uuid = $this->formatGuid2ForFilterUser($uuid);
1539
-		}
1540
-
1541
-		$filter = $uuidAttr . '=' . $uuid;
1542
-		$result = $this->searchUsers($filter, ['dn'], 2);
1543
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1544
-			// we put the count into account to make sure that this is
1545
-			// really unique
1546
-			return $result[0]['dn'][0];
1547
-		}
1548
-
1549
-		throw new \Exception('Cannot determine UUID attribute');
1550
-	}
1551
-
1552
-	/**
1553
-	 * auto-detects the directory's UUID attribute
1554
-	 *
1555
-	 * @param string $dn a known DN used to check against
1556
-	 * @param bool $isUser
1557
-	 * @param bool $force the detection should be run, even if it is not set to auto
1558
-	 * @param array|null $ldapRecord
1559
-	 * @return bool true on success, false otherwise
1560
-	 */
1561
-	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1562
-		if($isUser) {
1563
-			$uuidAttr     = 'ldapUuidUserAttribute';
1564
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1565
-		} else {
1566
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1567
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1568
-		}
1569
-
1570
-		if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1571
-			return true;
1572
-		}
1573
-
1574
-		if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1575
-			$this->connection->$uuidAttr = $uuidOverride;
1576
-			return true;
1577
-		}
1578
-
1579
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1580
-			if($ldapRecord !== null) {
1581
-				// we have the info from LDAP already, we don't need to talk to the server again
1582
-				if(isset($ldapRecord[$attribute])) {
1583
-					$this->connection->$uuidAttr = $attribute;
1584
-					return true;
1585
-				} else {
1586
-					continue;
1587
-				}
1588
-			}
1589
-
1590
-			$value = $this->readAttribute($dn, $attribute);
1591
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1592
-				\OCP\Util::writeLog('user_ldap',
1593
-									'Setting '.$attribute.' as '.$uuidAttr,
1594
-									\OCP\Util::DEBUG);
1595
-				$this->connection->$uuidAttr = $attribute;
1596
-				return true;
1597
-			}
1598
-		}
1599
-		\OCP\Util::writeLog('user_ldap',
1600
-							'Could not autodetect the UUID attribute',
1601
-							\OCP\Util::ERROR);
1602
-
1603
-		return false;
1604
-	}
1605
-
1606
-	/**
1607
-	 * @param string $dn
1608
-	 * @param bool $isUser
1609
-	 * @param null $ldapRecord
1610
-	 * @return bool|string
1611
-	 */
1612
-	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1613
-		if($isUser) {
1614
-			$uuidAttr     = 'ldapUuidUserAttribute';
1615
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1616
-		} else {
1617
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1618
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1619
-		}
1620
-
1621
-		$uuid = false;
1622
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1623
-			$attr = $this->connection->$uuidAttr;
1624
-			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1625
-			if( !is_array($uuid)
1626
-				&& $uuidOverride !== ''
1627
-				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1628
-			{
1629
-				$uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1630
-					? $ldapRecord[$this->connection->$uuidAttr]
1631
-					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1632
-			}
1633
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1634
-				$uuid = $uuid[0];
1635
-			}
1636
-		}
1637
-
1638
-		return $uuid;
1639
-	}
1640
-
1641
-	/**
1642
-	 * converts a binary ObjectGUID into a string representation
1643
-	 * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1644
-	 * @return string
1645
-	 * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1646
-	 */
1647
-	private function convertObjectGUID2Str($oguid) {
1648
-		$hex_guid = bin2hex($oguid);
1649
-		$hex_guid_to_guid_str = '';
1650
-		for($k = 1; $k <= 4; ++$k) {
1651
-			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1652
-		}
1653
-		$hex_guid_to_guid_str .= '-';
1654
-		for($k = 1; $k <= 2; ++$k) {
1655
-			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1656
-		}
1657
-		$hex_guid_to_guid_str .= '-';
1658
-		for($k = 1; $k <= 2; ++$k) {
1659
-			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1660
-		}
1661
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1662
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1663
-
1664
-		return strtoupper($hex_guid_to_guid_str);
1665
-	}
1666
-
1667
-	/**
1668
-	 * the first three blocks of the string-converted GUID happen to be in
1669
-	 * reverse order. In order to use it in a filter, this needs to be
1670
-	 * corrected. Furthermore the dashes need to be replaced and \\ preprended
1671
-	 * to every two hax figures.
1672
-	 *
1673
-	 * If an invalid string is passed, it will be returned without change.
1674
-	 *
1675
-	 * @param string $guid
1676
-	 * @return string
1677
-	 */
1678
-	public function formatGuid2ForFilterUser($guid) {
1679
-		if(!is_string($guid)) {
1680
-			throw new \InvalidArgumentException('String expected');
1681
-		}
1682
-		$blocks = explode('-', $guid);
1683
-		if(count($blocks) !== 5) {
1684
-			/*
1201
+        $findings = [];
1202
+        $savedoffset = $offset;
1203
+        do {
1204
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1205
+            if($search === false) {
1206
+                return [];
1207
+            }
1208
+            list($sr, $pagedSearchOK) = $search;
1209
+            $cr = $this->connection->getConnectionResource();
1210
+
1211
+            if($skipHandling) {
1212
+                //i.e. result do not need to be fetched, we just need the cookie
1213
+                //thus pass 1 or any other value as $iFoundItems because it is not
1214
+                //used
1215
+                $this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1216
+                                $offset, $pagedSearchOK,
1217
+                                $skipHandling);
1218
+                return array();
1219
+            }
1220
+
1221
+            $iFoundItems = 0;
1222
+            foreach($sr as $res) {
1223
+                $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1224
+                $iFoundItems = max($iFoundItems, $findings['count']);
1225
+                unset($findings['count']);
1226
+            }
1227
+
1228
+            $continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1229
+                $limitPerPage, $offset, $pagedSearchOK,
1230
+                                        $skipHandling);
1231
+            $offset += $limitPerPage;
1232
+        } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1233
+        // reseting offset
1234
+        $offset = $savedoffset;
1235
+
1236
+        // if we're here, probably no connection resource is returned.
1237
+        // to make Nextcloud behave nicely, we simply give back an empty array.
1238
+        if(is_null($findings)) {
1239
+            return array();
1240
+        }
1241
+
1242
+        if(!is_null($attr)) {
1243
+            $selection = [];
1244
+            $i = 0;
1245
+            foreach($findings as $item) {
1246
+                if(!is_array($item)) {
1247
+                    continue;
1248
+                }
1249
+                $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1250
+                foreach($attr as $key) {
1251
+                    if(isset($item[$key])) {
1252
+                        if(is_array($item[$key]) && isset($item[$key]['count'])) {
1253
+                            unset($item[$key]['count']);
1254
+                        }
1255
+                        if($key !== 'dn') {
1256
+                            if($this->resemblesDN($key)) {
1257
+                                $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1258
+                            } else if($key === 'objectguid' || $key === 'guid') {
1259
+                                $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1260
+                            } else {
1261
+                                $selection[$i][$key] = $item[$key];
1262
+                            }
1263
+                        } else {
1264
+                            $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1265
+                        }
1266
+                    }
1267
+
1268
+                }
1269
+                $i++;
1270
+            }
1271
+            $findings = $selection;
1272
+        }
1273
+        //we slice the findings, when
1274
+        //a) paged search unsuccessful, though attempted
1275
+        //b) no paged search, but limit set
1276
+        if((!$this->getPagedSearchResultState()
1277
+            && $pagedSearchOK)
1278
+            || (
1279
+                !$pagedSearchOK
1280
+                && !is_null($limit)
1281
+            )
1282
+        ) {
1283
+            $findings = array_slice($findings, intval($offset), $limit);
1284
+        }
1285
+        return $findings;
1286
+    }
1287
+
1288
+    /**
1289
+     * @param string $name
1290
+     * @return bool|mixed|string
1291
+     */
1292
+    public function sanitizeUsername($name) {
1293
+        if($this->connection->ldapIgnoreNamingRules) {
1294
+            return trim($name);
1295
+        }
1296
+
1297
+        // Transliteration
1298
+        // latin characters to ASCII
1299
+        $name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1300
+
1301
+        // Replacements
1302
+        $name = str_replace(' ', '_', $name);
1303
+
1304
+        // Every remaining disallowed characters will be removed
1305
+        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1306
+
1307
+        return $name;
1308
+    }
1309
+
1310
+    /**
1311
+     * escapes (user provided) parts for LDAP filter
1312
+     * @param string $input, the provided value
1313
+     * @param bool $allowAsterisk whether in * at the beginning should be preserved
1314
+     * @return string the escaped string
1315
+     */
1316
+    public function escapeFilterPart($input, $allowAsterisk = false) {
1317
+        $asterisk = '';
1318
+        if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1319
+            $asterisk = '*';
1320
+            $input = mb_substr($input, 1, null, 'UTF-8');
1321
+        }
1322
+        $search  = array('*', '\\', '(', ')');
1323
+        $replace = array('\\*', '\\\\', '\\(', '\\)');
1324
+        return $asterisk . str_replace($search, $replace, $input);
1325
+    }
1326
+
1327
+    /**
1328
+     * combines the input filters with AND
1329
+     * @param string[] $filters the filters to connect
1330
+     * @return string the combined filter
1331
+     */
1332
+    public function combineFilterWithAnd($filters) {
1333
+        return $this->combineFilter($filters, '&');
1334
+    }
1335
+
1336
+    /**
1337
+     * combines the input filters with OR
1338
+     * @param string[] $filters the filters to connect
1339
+     * @return string the combined filter
1340
+     * Combines Filter arguments with OR
1341
+     */
1342
+    public function combineFilterWithOr($filters) {
1343
+        return $this->combineFilter($filters, '|');
1344
+    }
1345
+
1346
+    /**
1347
+     * combines the input filters with given operator
1348
+     * @param string[] $filters the filters to connect
1349
+     * @param string $operator either & or |
1350
+     * @return string the combined filter
1351
+     */
1352
+    private function combineFilter($filters, $operator) {
1353
+        $combinedFilter = '('.$operator;
1354
+        foreach($filters as $filter) {
1355
+            if ($filter !== '' && $filter[0] !== '(') {
1356
+                $filter = '('.$filter.')';
1357
+            }
1358
+            $combinedFilter.=$filter;
1359
+        }
1360
+        $combinedFilter.=')';
1361
+        return $combinedFilter;
1362
+    }
1363
+
1364
+    /**
1365
+     * creates a filter part for to perform search for users
1366
+     * @param string $search the search term
1367
+     * @return string the final filter part to use in LDAP searches
1368
+     */
1369
+    public function getFilterPartForUserSearch($search) {
1370
+        return $this->getFilterPartForSearch($search,
1371
+            $this->connection->ldapAttributesForUserSearch,
1372
+            $this->connection->ldapUserDisplayName);
1373
+    }
1374
+
1375
+    /**
1376
+     * creates a filter part for to perform search for groups
1377
+     * @param string $search the search term
1378
+     * @return string the final filter part to use in LDAP searches
1379
+     */
1380
+    public function getFilterPartForGroupSearch($search) {
1381
+        return $this->getFilterPartForSearch($search,
1382
+            $this->connection->ldapAttributesForGroupSearch,
1383
+            $this->connection->ldapGroupDisplayName);
1384
+    }
1385
+
1386
+    /**
1387
+     * creates a filter part for searches by splitting up the given search
1388
+     * string into single words
1389
+     * @param string $search the search term
1390
+     * @param string[] $searchAttributes needs to have at least two attributes,
1391
+     * otherwise it does not make sense :)
1392
+     * @return string the final filter part to use in LDAP searches
1393
+     * @throws \Exception
1394
+     */
1395
+    private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1396
+        if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1397
+            throw new \Exception('searchAttributes must be an array with at least two string');
1398
+        }
1399
+        $searchWords = explode(' ', trim($search));
1400
+        $wordFilters = array();
1401
+        foreach($searchWords as $word) {
1402
+            $word = $this->prepareSearchTerm($word);
1403
+            //every word needs to appear at least once
1404
+            $wordMatchOneAttrFilters = array();
1405
+            foreach($searchAttributes as $attr) {
1406
+                $wordMatchOneAttrFilters[] = $attr . '=' . $word;
1407
+            }
1408
+            $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1409
+        }
1410
+        return $this->combineFilterWithAnd($wordFilters);
1411
+    }
1412
+
1413
+    /**
1414
+     * creates a filter part for searches
1415
+     * @param string $search the search term
1416
+     * @param string[]|null $searchAttributes
1417
+     * @param string $fallbackAttribute a fallback attribute in case the user
1418
+     * did not define search attributes. Typically the display name attribute.
1419
+     * @return string the final filter part to use in LDAP searches
1420
+     */
1421
+    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1422
+        $filter = array();
1423
+        $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1424
+        if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1425
+            try {
1426
+                return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1427
+            } catch(\Exception $e) {
1428
+                \OCP\Util::writeLog(
1429
+                    'user_ldap',
1430
+                    'Creating advanced filter for search failed, falling back to simple method.',
1431
+                    \OCP\Util::INFO
1432
+                );
1433
+            }
1434
+        }
1435
+
1436
+        $search = $this->prepareSearchTerm($search);
1437
+        if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1438
+            if ($fallbackAttribute === '') {
1439
+                return '';
1440
+            }
1441
+            $filter[] = $fallbackAttribute . '=' . $search;
1442
+        } else {
1443
+            foreach($searchAttributes as $attribute) {
1444
+                $filter[] = $attribute . '=' . $search;
1445
+            }
1446
+        }
1447
+        if(count($filter) === 1) {
1448
+            return '('.$filter[0].')';
1449
+        }
1450
+        return $this->combineFilterWithOr($filter);
1451
+    }
1452
+
1453
+    /**
1454
+     * returns the search term depending on whether we are allowed
1455
+     * list users found by ldap with the current input appended by
1456
+     * a *
1457
+     * @return string
1458
+     */
1459
+    private function prepareSearchTerm($term) {
1460
+        $config = \OC::$server->getConfig();
1461
+
1462
+        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1463
+
1464
+        $result = $term;
1465
+        if ($term === '') {
1466
+            $result = '*';
1467
+        } else if ($allowEnum !== 'no') {
1468
+            $result = $term . '*';
1469
+        }
1470
+        return $result;
1471
+    }
1472
+
1473
+    /**
1474
+     * returns the filter used for counting users
1475
+     * @return string
1476
+     */
1477
+    public function getFilterForUserCount() {
1478
+        $filter = $this->combineFilterWithAnd(array(
1479
+            $this->connection->ldapUserFilter,
1480
+            $this->connection->ldapUserDisplayName . '=*'
1481
+        ));
1482
+
1483
+        return $filter;
1484
+    }
1485
+
1486
+    /**
1487
+     * @param string $name
1488
+     * @param string $password
1489
+     * @return bool
1490
+     */
1491
+    public function areCredentialsValid($name, $password) {
1492
+        $name = $this->helper->DNasBaseParameter($name);
1493
+        $testConnection = clone $this->connection;
1494
+        $credentials = array(
1495
+            'ldapAgentName' => $name,
1496
+            'ldapAgentPassword' => $password
1497
+        );
1498
+        if(!$testConnection->setConfiguration($credentials)) {
1499
+            return false;
1500
+        }
1501
+        return $testConnection->bind();
1502
+    }
1503
+
1504
+    /**
1505
+     * reverse lookup of a DN given a known UUID
1506
+     *
1507
+     * @param string $uuid
1508
+     * @return string
1509
+     * @throws \Exception
1510
+     */
1511
+    public function getUserDnByUuid($uuid) {
1512
+        $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1513
+        $filter       = $this->connection->ldapUserFilter;
1514
+        $base         = $this->connection->ldapBaseUsers;
1515
+
1516
+        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1517
+            // Sacrebleu! The UUID attribute is unknown :( We need first an
1518
+            // existing DN to be able to reliably detect it.
1519
+            $result = $this->search($filter, $base, ['dn'], 1);
1520
+            if(!isset($result[0]) || !isset($result[0]['dn'])) {
1521
+                throw new \Exception('Cannot determine UUID attribute');
1522
+            }
1523
+            $dn = $result[0]['dn'][0];
1524
+            if(!$this->detectUuidAttribute($dn, true)) {
1525
+                throw new \Exception('Cannot determine UUID attribute');
1526
+            }
1527
+        } else {
1528
+            // The UUID attribute is either known or an override is given.
1529
+            // By calling this method we ensure that $this->connection->$uuidAttr
1530
+            // is definitely set
1531
+            if(!$this->detectUuidAttribute('', true)) {
1532
+                throw new \Exception('Cannot determine UUID attribute');
1533
+            }
1534
+        }
1535
+
1536
+        $uuidAttr = $this->connection->ldapUuidUserAttribute;
1537
+        if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1538
+            $uuid = $this->formatGuid2ForFilterUser($uuid);
1539
+        }
1540
+
1541
+        $filter = $uuidAttr . '=' . $uuid;
1542
+        $result = $this->searchUsers($filter, ['dn'], 2);
1543
+        if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1544
+            // we put the count into account to make sure that this is
1545
+            // really unique
1546
+            return $result[0]['dn'][0];
1547
+        }
1548
+
1549
+        throw new \Exception('Cannot determine UUID attribute');
1550
+    }
1551
+
1552
+    /**
1553
+     * auto-detects the directory's UUID attribute
1554
+     *
1555
+     * @param string $dn a known DN used to check against
1556
+     * @param bool $isUser
1557
+     * @param bool $force the detection should be run, even if it is not set to auto
1558
+     * @param array|null $ldapRecord
1559
+     * @return bool true on success, false otherwise
1560
+     */
1561
+    private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1562
+        if($isUser) {
1563
+            $uuidAttr     = 'ldapUuidUserAttribute';
1564
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1565
+        } else {
1566
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1567
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1568
+        }
1569
+
1570
+        if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1571
+            return true;
1572
+        }
1573
+
1574
+        if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1575
+            $this->connection->$uuidAttr = $uuidOverride;
1576
+            return true;
1577
+        }
1578
+
1579
+        foreach(self::UUID_ATTRIBUTES as $attribute) {
1580
+            if($ldapRecord !== null) {
1581
+                // we have the info from LDAP already, we don't need to talk to the server again
1582
+                if(isset($ldapRecord[$attribute])) {
1583
+                    $this->connection->$uuidAttr = $attribute;
1584
+                    return true;
1585
+                } else {
1586
+                    continue;
1587
+                }
1588
+            }
1589
+
1590
+            $value = $this->readAttribute($dn, $attribute);
1591
+            if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1592
+                \OCP\Util::writeLog('user_ldap',
1593
+                                    'Setting '.$attribute.' as '.$uuidAttr,
1594
+                                    \OCP\Util::DEBUG);
1595
+                $this->connection->$uuidAttr = $attribute;
1596
+                return true;
1597
+            }
1598
+        }
1599
+        \OCP\Util::writeLog('user_ldap',
1600
+                            'Could not autodetect the UUID attribute',
1601
+                            \OCP\Util::ERROR);
1602
+
1603
+        return false;
1604
+    }
1605
+
1606
+    /**
1607
+     * @param string $dn
1608
+     * @param bool $isUser
1609
+     * @param null $ldapRecord
1610
+     * @return bool|string
1611
+     */
1612
+    public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1613
+        if($isUser) {
1614
+            $uuidAttr     = 'ldapUuidUserAttribute';
1615
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1616
+        } else {
1617
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1618
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1619
+        }
1620
+
1621
+        $uuid = false;
1622
+        if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1623
+            $attr = $this->connection->$uuidAttr;
1624
+            $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1625
+            if( !is_array($uuid)
1626
+                && $uuidOverride !== ''
1627
+                && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1628
+            {
1629
+                $uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1630
+                    ? $ldapRecord[$this->connection->$uuidAttr]
1631
+                    : $this->readAttribute($dn, $this->connection->$uuidAttr);
1632
+            }
1633
+            if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1634
+                $uuid = $uuid[0];
1635
+            }
1636
+        }
1637
+
1638
+        return $uuid;
1639
+    }
1640
+
1641
+    /**
1642
+     * converts a binary ObjectGUID into a string representation
1643
+     * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1644
+     * @return string
1645
+     * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1646
+     */
1647
+    private function convertObjectGUID2Str($oguid) {
1648
+        $hex_guid = bin2hex($oguid);
1649
+        $hex_guid_to_guid_str = '';
1650
+        for($k = 1; $k <= 4; ++$k) {
1651
+            $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1652
+        }
1653
+        $hex_guid_to_guid_str .= '-';
1654
+        for($k = 1; $k <= 2; ++$k) {
1655
+            $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1656
+        }
1657
+        $hex_guid_to_guid_str .= '-';
1658
+        for($k = 1; $k <= 2; ++$k) {
1659
+            $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1660
+        }
1661
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1662
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1663
+
1664
+        return strtoupper($hex_guid_to_guid_str);
1665
+    }
1666
+
1667
+    /**
1668
+     * the first three blocks of the string-converted GUID happen to be in
1669
+     * reverse order. In order to use it in a filter, this needs to be
1670
+     * corrected. Furthermore the dashes need to be replaced and \\ preprended
1671
+     * to every two hax figures.
1672
+     *
1673
+     * If an invalid string is passed, it will be returned without change.
1674
+     *
1675
+     * @param string $guid
1676
+     * @return string
1677
+     */
1678
+    public function formatGuid2ForFilterUser($guid) {
1679
+        if(!is_string($guid)) {
1680
+            throw new \InvalidArgumentException('String expected');
1681
+        }
1682
+        $blocks = explode('-', $guid);
1683
+        if(count($blocks) !== 5) {
1684
+            /*
1685 1685
 			 * Why not throw an Exception instead? This method is a utility
1686 1686
 			 * called only when trying to figure out whether a "missing" known
1687 1687
 			 * LDAP user was or was not renamed on the LDAP server. And this
@@ -1692,274 +1692,274 @@  discard block
 block discarded – undo
1692 1692
 			 * an exception here would kill the experience for a valid, acting
1693 1693
 			 * user. Instead we write a log message.
1694 1694
 			 */
1695
-			\OC::$server->getLogger()->info(
1696
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1697
-				'({uuid}) probably does not match UUID configuration.',
1698
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1699
-			);
1700
-			return $guid;
1701
-		}
1702
-		for($i=0; $i < 3; $i++) {
1703
-			$pairs = str_split($blocks[$i], 2);
1704
-			$pairs = array_reverse($pairs);
1705
-			$blocks[$i] = implode('', $pairs);
1706
-		}
1707
-		for($i=0; $i < 5; $i++) {
1708
-			$pairs = str_split($blocks[$i], 2);
1709
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1710
-		}
1711
-		return implode('', $blocks);
1712
-	}
1713
-
1714
-	/**
1715
-	 * gets a SID of the domain of the given dn
1716
-	 * @param string $dn
1717
-	 * @return string|bool
1718
-	 */
1719
-	public function getSID($dn) {
1720
-		$domainDN = $this->getDomainDNFromDN($dn);
1721
-		$cacheKey = 'getSID-'.$domainDN;
1722
-		$sid = $this->connection->getFromCache($cacheKey);
1723
-		if(!is_null($sid)) {
1724
-			return $sid;
1725
-		}
1726
-
1727
-		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1728
-		if(!is_array($objectSid) || empty($objectSid)) {
1729
-			$this->connection->writeToCache($cacheKey, false);
1730
-			return false;
1731
-		}
1732
-		$domainObjectSid = $this->convertSID2Str($objectSid[0]);
1733
-		$this->connection->writeToCache($cacheKey, $domainObjectSid);
1734
-
1735
-		return $domainObjectSid;
1736
-	}
1737
-
1738
-	/**
1739
-	 * converts a binary SID into a string representation
1740
-	 * @param string $sid
1741
-	 * @return string
1742
-	 */
1743
-	public function convertSID2Str($sid) {
1744
-		// The format of a SID binary string is as follows:
1745
-		// 1 byte for the revision level
1746
-		// 1 byte for the number n of variable sub-ids
1747
-		// 6 bytes for identifier authority value
1748
-		// n*4 bytes for n sub-ids
1749
-		//
1750
-		// Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1751
-		//  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1752
-		$revision = ord($sid[0]);
1753
-		$numberSubID = ord($sid[1]);
1754
-
1755
-		$subIdStart = 8; // 1 + 1 + 6
1756
-		$subIdLength = 4;
1757
-		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1758
-			// Incorrect number of bytes present.
1759
-			return '';
1760
-		}
1761
-
1762
-		// 6 bytes = 48 bits can be represented using floats without loss of
1763
-		// precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1764
-		$iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1765
-
1766
-		$subIDs = array();
1767
-		for ($i = 0; $i < $numberSubID; $i++) {
1768
-			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1769
-			$subIDs[] = sprintf('%u', $subID[1]);
1770
-		}
1771
-
1772
-		// Result for example above: S-1-5-21-249921958-728525901-1594176202
1773
-		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1774
-	}
1775
-
1776
-	/**
1777
-	 * checks if the given DN is part of the given base DN(s)
1778
-	 * @param string $dn the DN
1779
-	 * @param string[] $bases array containing the allowed base DN or DNs
1780
-	 * @return bool
1781
-	 */
1782
-	public function isDNPartOfBase($dn, $bases) {
1783
-		$belongsToBase = false;
1784
-		$bases = $this->helper->sanitizeDN($bases);
1785
-
1786
-		foreach($bases as $base) {
1787
-			$belongsToBase = true;
1788
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1789
-				$belongsToBase = false;
1790
-			}
1791
-			if($belongsToBase) {
1792
-				break;
1793
-			}
1794
-		}
1795
-		return $belongsToBase;
1796
-	}
1797
-
1798
-	/**
1799
-	 * resets a running Paged Search operation
1800
-	 */
1801
-	private function abandonPagedSearch() {
1802
-		if($this->connection->hasPagedResultSupport) {
1803
-			$cr = $this->connection->getConnectionResource();
1804
-			$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1805
-			$this->getPagedSearchResultState();
1806
-			$this->lastCookie = '';
1807
-			$this->cookies = array();
1808
-		}
1809
-	}
1810
-
1811
-	/**
1812
-	 * get a cookie for the next LDAP paged search
1813
-	 * @param string $base a string with the base DN for the search
1814
-	 * @param string $filter the search filter to identify the correct search
1815
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1816
-	 * @param int $offset the offset for the new search to identify the correct search really good
1817
-	 * @return string containing the key or empty if none is cached
1818
-	 */
1819
-	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1820
-		if($offset === 0) {
1821
-			return '';
1822
-		}
1823
-		$offset -= $limit;
1824
-		//we work with cache here
1825
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1826
-		$cookie = '';
1827
-		if(isset($this->cookies[$cacheKey])) {
1828
-			$cookie = $this->cookies[$cacheKey];
1829
-			if(is_null($cookie)) {
1830
-				$cookie = '';
1831
-			}
1832
-		}
1833
-		return $cookie;
1834
-	}
1835
-
1836
-	/**
1837
-	 * checks whether an LDAP paged search operation has more pages that can be
1838
-	 * retrieved, typically when offset and limit are provided.
1839
-	 *
1840
-	 * Be very careful to use it: the last cookie value, which is inspected, can
1841
-	 * be reset by other operations. Best, call it immediately after a search(),
1842
-	 * searchUsers() or searchGroups() call. count-methods are probably safe as
1843
-	 * well. Don't rely on it with any fetchList-method.
1844
-	 * @return bool
1845
-	 */
1846
-	public function hasMoreResults() {
1847
-		if(!$this->connection->hasPagedResultSupport) {
1848
-			return false;
1849
-		}
1850
-
1851
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1852
-			// as in RFC 2696, when all results are returned, the cookie will
1853
-			// be empty.
1854
-			return false;
1855
-		}
1856
-
1857
-		return true;
1858
-	}
1859
-
1860
-	/**
1861
-	 * set a cookie for LDAP paged search run
1862
-	 * @param string $base a string with the base DN for the search
1863
-	 * @param string $filter the search filter to identify the correct search
1864
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1865
-	 * @param int $offset the offset for the run search to identify the correct search really good
1866
-	 * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1867
-	 * @return void
1868
-	 */
1869
-	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1870
-		// allow '0' for 389ds
1871
-		if(!empty($cookie) || $cookie === '0') {
1872
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1873
-			$this->cookies[$cacheKey] = $cookie;
1874
-			$this->lastCookie = $cookie;
1875
-		}
1876
-	}
1877
-
1878
-	/**
1879
-	 * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1880
-	 * @return boolean|null true on success, null or false otherwise
1881
-	 */
1882
-	public function getPagedSearchResultState() {
1883
-		$result = $this->pagedSearchedSuccessful;
1884
-		$this->pagedSearchedSuccessful = null;
1885
-		return $result;
1886
-	}
1887
-
1888
-	/**
1889
-	 * Prepares a paged search, if possible
1890
-	 * @param string $filter the LDAP filter for the search
1891
-	 * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1892
-	 * @param string[] $attr optional, when a certain attribute shall be filtered outside
1893
-	 * @param int $limit
1894
-	 * @param int $offset
1895
-	 * @return bool|true
1896
-	 */
1897
-	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1898
-		$pagedSearchOK = false;
1899
-		if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1900
-			$offset = intval($offset); //can be null
1901
-			\OCP\Util::writeLog('user_ldap',
1902
-				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1903
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1904
-				\OCP\Util::DEBUG);
1905
-			//get the cookie from the search for the previous search, required by LDAP
1906
-			foreach($bases as $base) {
1907
-
1908
-				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1909
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1910
-					// no cookie known from a potential previous search. We need
1911
-					// to start from 0 to come to the desired page. cookie value
1912
-					// of '0' is valid, because 389ds
1913
-					$reOffset = 0;
1914
-					while($reOffset < $offset) {
1915
-						$this->search($filter, array($base), $attr, $limit, $reOffset, true);
1916
-						$reOffset += $limit;
1917
-					}
1918
-					$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1919
-					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1920
-					// '0' is valid, because 389ds
1921
-					//TODO: remember this, probably does not change in the next request...
1922
-					if(empty($cookie) && $cookie !== '0') {
1923
-						$cookie = null;
1924
-					}
1925
-				}
1926
-				if(!is_null($cookie)) {
1927
-					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1928
-					$this->abandonPagedSearch();
1929
-					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1930
-						$this->connection->getConnectionResource(), $limit,
1931
-						false, $cookie);
1932
-					if(!$pagedSearchOK) {
1933
-						return false;
1934
-					}
1935
-					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
1936
-				} else {
1937
-					\OCP\Util::writeLog('user_ldap',
1938
-						'No paged search for us, Cpt., Limit '.$limit.' Offset '.$offset,
1939
-						\OCP\Util::INFO);
1940
-				}
1941
-
1942
-			}
1943
-		/* ++ Fixing RHDS searches with pages with zero results ++
1695
+            \OC::$server->getLogger()->info(
1696
+                'Passed string does not resemble a valid GUID. Known UUID ' .
1697
+                '({uuid}) probably does not match UUID configuration.',
1698
+                [ 'app' => 'user_ldap', 'uuid' => $guid ]
1699
+            );
1700
+            return $guid;
1701
+        }
1702
+        for($i=0; $i < 3; $i++) {
1703
+            $pairs = str_split($blocks[$i], 2);
1704
+            $pairs = array_reverse($pairs);
1705
+            $blocks[$i] = implode('', $pairs);
1706
+        }
1707
+        for($i=0; $i < 5; $i++) {
1708
+            $pairs = str_split($blocks[$i], 2);
1709
+            $blocks[$i] = '\\' . implode('\\', $pairs);
1710
+        }
1711
+        return implode('', $blocks);
1712
+    }
1713
+
1714
+    /**
1715
+     * gets a SID of the domain of the given dn
1716
+     * @param string $dn
1717
+     * @return string|bool
1718
+     */
1719
+    public function getSID($dn) {
1720
+        $domainDN = $this->getDomainDNFromDN($dn);
1721
+        $cacheKey = 'getSID-'.$domainDN;
1722
+        $sid = $this->connection->getFromCache($cacheKey);
1723
+        if(!is_null($sid)) {
1724
+            return $sid;
1725
+        }
1726
+
1727
+        $objectSid = $this->readAttribute($domainDN, 'objectsid');
1728
+        if(!is_array($objectSid) || empty($objectSid)) {
1729
+            $this->connection->writeToCache($cacheKey, false);
1730
+            return false;
1731
+        }
1732
+        $domainObjectSid = $this->convertSID2Str($objectSid[0]);
1733
+        $this->connection->writeToCache($cacheKey, $domainObjectSid);
1734
+
1735
+        return $domainObjectSid;
1736
+    }
1737
+
1738
+    /**
1739
+     * converts a binary SID into a string representation
1740
+     * @param string $sid
1741
+     * @return string
1742
+     */
1743
+    public function convertSID2Str($sid) {
1744
+        // The format of a SID binary string is as follows:
1745
+        // 1 byte for the revision level
1746
+        // 1 byte for the number n of variable sub-ids
1747
+        // 6 bytes for identifier authority value
1748
+        // n*4 bytes for n sub-ids
1749
+        //
1750
+        // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1751
+        //  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1752
+        $revision = ord($sid[0]);
1753
+        $numberSubID = ord($sid[1]);
1754
+
1755
+        $subIdStart = 8; // 1 + 1 + 6
1756
+        $subIdLength = 4;
1757
+        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1758
+            // Incorrect number of bytes present.
1759
+            return '';
1760
+        }
1761
+
1762
+        // 6 bytes = 48 bits can be represented using floats without loss of
1763
+        // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1764
+        $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1765
+
1766
+        $subIDs = array();
1767
+        for ($i = 0; $i < $numberSubID; $i++) {
1768
+            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1769
+            $subIDs[] = sprintf('%u', $subID[1]);
1770
+        }
1771
+
1772
+        // Result for example above: S-1-5-21-249921958-728525901-1594176202
1773
+        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1774
+    }
1775
+
1776
+    /**
1777
+     * checks if the given DN is part of the given base DN(s)
1778
+     * @param string $dn the DN
1779
+     * @param string[] $bases array containing the allowed base DN or DNs
1780
+     * @return bool
1781
+     */
1782
+    public function isDNPartOfBase($dn, $bases) {
1783
+        $belongsToBase = false;
1784
+        $bases = $this->helper->sanitizeDN($bases);
1785
+
1786
+        foreach($bases as $base) {
1787
+            $belongsToBase = true;
1788
+            if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1789
+                $belongsToBase = false;
1790
+            }
1791
+            if($belongsToBase) {
1792
+                break;
1793
+            }
1794
+        }
1795
+        return $belongsToBase;
1796
+    }
1797
+
1798
+    /**
1799
+     * resets a running Paged Search operation
1800
+     */
1801
+    private function abandonPagedSearch() {
1802
+        if($this->connection->hasPagedResultSupport) {
1803
+            $cr = $this->connection->getConnectionResource();
1804
+            $this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1805
+            $this->getPagedSearchResultState();
1806
+            $this->lastCookie = '';
1807
+            $this->cookies = array();
1808
+        }
1809
+    }
1810
+
1811
+    /**
1812
+     * get a cookie for the next LDAP paged search
1813
+     * @param string $base a string with the base DN for the search
1814
+     * @param string $filter the search filter to identify the correct search
1815
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1816
+     * @param int $offset the offset for the new search to identify the correct search really good
1817
+     * @return string containing the key or empty if none is cached
1818
+     */
1819
+    private function getPagedResultCookie($base, $filter, $limit, $offset) {
1820
+        if($offset === 0) {
1821
+            return '';
1822
+        }
1823
+        $offset -= $limit;
1824
+        //we work with cache here
1825
+        $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1826
+        $cookie = '';
1827
+        if(isset($this->cookies[$cacheKey])) {
1828
+            $cookie = $this->cookies[$cacheKey];
1829
+            if(is_null($cookie)) {
1830
+                $cookie = '';
1831
+            }
1832
+        }
1833
+        return $cookie;
1834
+    }
1835
+
1836
+    /**
1837
+     * checks whether an LDAP paged search operation has more pages that can be
1838
+     * retrieved, typically when offset and limit are provided.
1839
+     *
1840
+     * Be very careful to use it: the last cookie value, which is inspected, can
1841
+     * be reset by other operations. Best, call it immediately after a search(),
1842
+     * searchUsers() or searchGroups() call. count-methods are probably safe as
1843
+     * well. Don't rely on it with any fetchList-method.
1844
+     * @return bool
1845
+     */
1846
+    public function hasMoreResults() {
1847
+        if(!$this->connection->hasPagedResultSupport) {
1848
+            return false;
1849
+        }
1850
+
1851
+        if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1852
+            // as in RFC 2696, when all results are returned, the cookie will
1853
+            // be empty.
1854
+            return false;
1855
+        }
1856
+
1857
+        return true;
1858
+    }
1859
+
1860
+    /**
1861
+     * set a cookie for LDAP paged search run
1862
+     * @param string $base a string with the base DN for the search
1863
+     * @param string $filter the search filter to identify the correct search
1864
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1865
+     * @param int $offset the offset for the run search to identify the correct search really good
1866
+     * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1867
+     * @return void
1868
+     */
1869
+    private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1870
+        // allow '0' for 389ds
1871
+        if(!empty($cookie) || $cookie === '0') {
1872
+            $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1873
+            $this->cookies[$cacheKey] = $cookie;
1874
+            $this->lastCookie = $cookie;
1875
+        }
1876
+    }
1877
+
1878
+    /**
1879
+     * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1880
+     * @return boolean|null true on success, null or false otherwise
1881
+     */
1882
+    public function getPagedSearchResultState() {
1883
+        $result = $this->pagedSearchedSuccessful;
1884
+        $this->pagedSearchedSuccessful = null;
1885
+        return $result;
1886
+    }
1887
+
1888
+    /**
1889
+     * Prepares a paged search, if possible
1890
+     * @param string $filter the LDAP filter for the search
1891
+     * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1892
+     * @param string[] $attr optional, when a certain attribute shall be filtered outside
1893
+     * @param int $limit
1894
+     * @param int $offset
1895
+     * @return bool|true
1896
+     */
1897
+    private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1898
+        $pagedSearchOK = false;
1899
+        if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1900
+            $offset = intval($offset); //can be null
1901
+            \OCP\Util::writeLog('user_ldap',
1902
+                'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1903
+                .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1904
+                \OCP\Util::DEBUG);
1905
+            //get the cookie from the search for the previous search, required by LDAP
1906
+            foreach($bases as $base) {
1907
+
1908
+                $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1909
+                if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1910
+                    // no cookie known from a potential previous search. We need
1911
+                    // to start from 0 to come to the desired page. cookie value
1912
+                    // of '0' is valid, because 389ds
1913
+                    $reOffset = 0;
1914
+                    while($reOffset < $offset) {
1915
+                        $this->search($filter, array($base), $attr, $limit, $reOffset, true);
1916
+                        $reOffset += $limit;
1917
+                    }
1918
+                    $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1919
+                    //still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1920
+                    // '0' is valid, because 389ds
1921
+                    //TODO: remember this, probably does not change in the next request...
1922
+                    if(empty($cookie) && $cookie !== '0') {
1923
+                        $cookie = null;
1924
+                    }
1925
+                }
1926
+                if(!is_null($cookie)) {
1927
+                    //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1928
+                    $this->abandonPagedSearch();
1929
+                    $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1930
+                        $this->connection->getConnectionResource(), $limit,
1931
+                        false, $cookie);
1932
+                    if(!$pagedSearchOK) {
1933
+                        return false;
1934
+                    }
1935
+                    \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
1936
+                } else {
1937
+                    \OCP\Util::writeLog('user_ldap',
1938
+                        'No paged search for us, Cpt., Limit '.$limit.' Offset '.$offset,
1939
+                        \OCP\Util::INFO);
1940
+                }
1941
+
1942
+            }
1943
+        /* ++ Fixing RHDS searches with pages with zero results ++
1944 1944
 		 * We coudn't get paged searches working with our RHDS for login ($limit = 0),
1945 1945
 		 * due to pages with zero results.
1946 1946
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
1947 1947
 		 * if we don't have a previous paged search.
1948 1948
 		 */
1949
-		} else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1950
-			// a search without limit was requested. However, if we do use
1951
-			// Paged Search once, we always must do it. This requires us to
1952
-			// initialize it with the configured page size.
1953
-			$this->abandonPagedSearch();
1954
-			// in case someone set it to 0 … use 500, otherwise no results will
1955
-			// be returned.
1956
-			$pageSize = intval($this->connection->ldapPagingSize) > 0 ? intval($this->connection->ldapPagingSize) : 500;
1957
-			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1958
-				$this->connection->getConnectionResource(),
1959
-				$pageSize, false, '');
1960
-		}
1961
-
1962
-		return $pagedSearchOK;
1963
-	}
1949
+        } else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1950
+            // a search without limit was requested. However, if we do use
1951
+            // Paged Search once, we always must do it. This requires us to
1952
+            // initialize it with the configured page size.
1953
+            $this->abandonPagedSearch();
1954
+            // in case someone set it to 0 … use 500, otherwise no results will
1955
+            // be returned.
1956
+            $pageSize = intval($this->connection->ldapPagingSize) > 0 ? intval($this->connection->ldapPagingSize) : 500;
1957
+            $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1958
+                $this->connection->getConnectionResource(),
1959
+                $pageSize, false, '');
1960
+        }
1961
+
1962
+        return $pagedSearchOK;
1963
+    }
1964 1964
 
1965 1965
 }
Please login to merge, or discard this patch.
Spacing   +171 added lines, -171 removed lines patch added patch discarded remove patch
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
 	 * @return AbstractMapping
125 125
 	 */
126 126
 	public function getUserMapper() {
127
-		if(is_null($this->userMapper)) {
127
+		if (is_null($this->userMapper)) {
128 128
 			throw new \Exception('UserMapper was not assigned to this Access instance.');
129 129
 		}
130 130
 		return $this->userMapper;
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 	 * @return AbstractMapping
145 145
 	 */
146 146
 	public function getGroupMapper() {
147
-		if(is_null($this->groupMapper)) {
147
+		if (is_null($this->groupMapper)) {
148 148
 			throw new \Exception('GroupMapper was not assigned to this Access instance.');
149 149
 		}
150 150
 		return $this->groupMapper;
@@ -175,14 +175,14 @@  discard block
 block discarded – undo
175 175
 	 *          array if $attr is empty, false otherwise
176 176
 	 */
177 177
 	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
178
-		if(!$this->checkConnection()) {
178
+		if (!$this->checkConnection()) {
179 179
 			\OCP\Util::writeLog('user_ldap',
180 180
 				'No LDAP Connector assigned, access impossible for readAttribute.',
181 181
 				\OCP\Util::WARN);
182 182
 			return false;
183 183
 		}
184 184
 		$cr = $this->connection->getConnectionResource();
185
-		if(!$this->ldap->isResource($cr)) {
185
+		if (!$this->ldap->isResource($cr)) {
186 186
 			//LDAP not available
187 187
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
188 188
 			return false;
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 		$isRangeRequest = false;
206 206
 		do {
207 207
 			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
208
-			if(is_bool($result)) {
208
+			if (is_bool($result)) {
209 209
 				// when an exists request was run and it was successful, an empty
210 210
 				// array must be returned
211 211
 				return $result ? [] : false;
@@ -222,22 +222,22 @@  discard block
 block discarded – undo
222 222
 			$result = $this->extractRangeData($result, $attr);
223 223
 			if (!empty($result)) {
224 224
 				$normalizedResult = $this->extractAttributeValuesFromResult(
225
-					[ $attr => $result['values'] ],
225
+					[$attr => $result['values']],
226 226
 					$attr
227 227
 				);
228 228
 				$values = array_merge($values, $normalizedResult);
229 229
 
230
-				if($result['rangeHigh'] === '*') {
230
+				if ($result['rangeHigh'] === '*') {
231 231
 					// when server replies with * as high range value, there are
232 232
 					// no more results left
233 233
 					return $values;
234 234
 				} else {
235
-					$low  = $result['rangeHigh'] + 1;
236
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
235
+					$low = $result['rangeHigh'] + 1;
236
+					$attrToRead = $result['attributeName'].';range='.$low.'-*';
237 237
 					$isRangeRequest = true;
238 238
 				}
239 239
 			}
240
-		} while($isRangeRequest);
240
+		} while ($isRangeRequest);
241 241
 
242 242
 		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
243 243
 		return false;
@@ -262,13 +262,13 @@  discard block
 block discarded – undo
262 262
 		if (!$this->ldap->isResource($rr)) {
263 263
 			if ($attribute !== '') {
264 264
 				//do not throw this message on userExists check, irritates
265
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
265
+				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN '.$dn, \OCP\Util::DEBUG);
266 266
 			}
267 267
 			//in case an error occurs , e.g. object does not exist
268 268
 			return false;
269 269
 		}
270 270
 		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
271
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
271
+			\OCP\Util::writeLog('user_ldap', 'readAttribute: '.$dn.' found', \OCP\Util::DEBUG);
272 272
 			return true;
273 273
 		}
274 274
 		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
@@ -293,12 +293,12 @@  discard block
 block discarded – undo
293 293
 	 */
294 294
 	public function extractAttributeValuesFromResult($result, $attribute) {
295 295
 		$values = [];
296
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
296
+		if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
297 297
 			$lowercaseAttribute = strtolower($attribute);
298
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
299
-				if($this->resemblesDN($attribute)) {
298
+			for ($i = 0; $i < $result[$attribute]['count']; $i++) {
299
+				if ($this->resemblesDN($attribute)) {
300 300
 					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
301
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
301
+				} elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
302 302
 					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
303 303
 				} else {
304 304
 					$values[] = $result[$attribute][$i];
@@ -320,10 +320,10 @@  discard block
 block discarded – undo
320 320
 	 */
321 321
 	public function extractRangeData($result, $attribute) {
322 322
 		$keys = array_keys($result);
323
-		foreach($keys as $key) {
324
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
323
+		foreach ($keys as $key) {
324
+			if ($key !== $attribute && strpos($key, $attribute) === 0) {
325 325
 				$queryData = explode(';', $key);
326
-				if(strpos($queryData[1], 'range=') === 0) {
326
+				if (strpos($queryData[1], 'range=') === 0) {
327 327
 					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
328 328
 					$data = [
329 329
 						'values' => $result[$key],
@@ -348,18 +348,18 @@  discard block
 block discarded – undo
348 348
 	 * @throws \Exception
349 349
 	 */
350 350
 	public function setPassword($userDN, $password) {
351
-		if(intval($this->connection->turnOnPasswordChange) !== 1) {
351
+		if (intval($this->connection->turnOnPasswordChange) !== 1) {
352 352
 			throw new \Exception('LDAP password changes are disabled.');
353 353
 		}
354 354
 		$cr = $this->connection->getConnectionResource();
355
-		if(!$this->ldap->isResource($cr)) {
355
+		if (!$this->ldap->isResource($cr)) {
356 356
 			//LDAP not available
357 357
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
358 358
 			return false;
359 359
 		}
360 360
 		try {
361 361
 			return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
362
-		} catch(ConstraintViolationException $e) {
362
+		} catch (ConstraintViolationException $e) {
363 363
 			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
364 364
 		}
365 365
 	}
@@ -401,17 +401,17 @@  discard block
 block discarded – undo
401 401
 	 */
402 402
 	public function getDomainDNFromDN($dn) {
403 403
 		$allParts = $this->ldap->explodeDN($dn, 0);
404
-		if($allParts === false) {
404
+		if ($allParts === false) {
405 405
 			//not a valid DN
406 406
 			return '';
407 407
 		}
408 408
 		$domainParts = array();
409 409
 		$dcFound = false;
410
-		foreach($allParts as $part) {
411
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
410
+		foreach ($allParts as $part) {
411
+			if (!$dcFound && strpos($part, 'dc=') === 0) {
412 412
 				$dcFound = true;
413 413
 			}
414
-			if($dcFound) {
414
+			if ($dcFound) {
415 415
 				$domainParts[] = $part;
416 416
 			}
417 417
 		}
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
 
439 439
 		//Check whether the DN belongs to the Base, to avoid issues on multi-
440 440
 		//server setups
441
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
441
+		if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
442 442
 			return $fdn;
443 443
 		}
444 444
 
@@ -455,7 +455,7 @@  discard block
 block discarded – undo
455 455
 		//To avoid bypassing the base DN settings under certain circumstances
456 456
 		//with the group support, check whether the provided DN matches one of
457 457
 		//the given Bases
458
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
458
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
459 459
 			return false;
460 460
 		}
461 461
 
@@ -472,11 +472,11 @@  discard block
 block discarded – undo
472 472
 	 */
473 473
 	public function groupsMatchFilter($groupDNs) {
474 474
 		$validGroupDNs = [];
475
-		foreach($groupDNs as $dn) {
475
+		foreach ($groupDNs as $dn) {
476 476
 			$cacheKey = 'groupsMatchFilter-'.$dn;
477 477
 			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
478
-			if(!is_null($groupMatchFilter)) {
479
-				if($groupMatchFilter) {
478
+			if (!is_null($groupMatchFilter)) {
479
+				if ($groupMatchFilter) {
480 480
 					$validGroupDNs[] = $dn;
481 481
 				}
482 482
 				continue;
@@ -484,13 +484,13 @@  discard block
 block discarded – undo
484 484
 
485 485
 			// Check the base DN first. If this is not met already, we don't
486 486
 			// need to ask the server at all.
487
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
487
+			if (!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
488 488
 				$this->connection->writeToCache($cacheKey, false);
489 489
 				continue;
490 490
 			}
491 491
 
492 492
 			$result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
493
-			if(is_array($result)) {
493
+			if (is_array($result)) {
494 494
 				$this->connection->writeToCache($cacheKey, true);
495 495
 				$validGroupDNs[] = $dn;
496 496
 			} else {
@@ -511,7 +511,7 @@  discard block
 block discarded – undo
511 511
 		//To avoid bypassing the base DN settings under certain circumstances
512 512
 		//with the group support, check whether the provided DN matches one of
513 513
 		//the given Bases
514
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
514
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
515 515
 			return false;
516 516
 		}
517 517
 
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 	 */
532 532
 	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
533 533
 		$newlyMapped = false;
534
-		if($isUser) {
534
+		if ($isUser) {
535 535
 			$mapper = $this->getUserMapper();
536 536
 			$nameAttribute = $this->connection->ldapUserDisplayName;
537 537
 		} else {
@@ -541,15 +541,15 @@  discard block
 block discarded – undo
541 541
 
542 542
 		//let's try to retrieve the Nextcloud name from the mappings table
543 543
 		$ncName = $mapper->getNameByDN($fdn);
544
-		if(is_string($ncName)) {
544
+		if (is_string($ncName)) {
545 545
 			return $ncName;
546 546
 		}
547 547
 
548 548
 		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
549 549
 		$uuid = $this->getUUID($fdn, $isUser, $record);
550
-		if(is_string($uuid)) {
550
+		if (is_string($uuid)) {
551 551
 			$ncName = $mapper->getNameByUUID($uuid);
552
-			if(is_string($ncName)) {
552
+			if (is_string($ncName)) {
553 553
 				$mapper->setDNbyUUID($fdn, $uuid);
554 554
 				return $ncName;
555 555
 			}
@@ -559,16 +559,16 @@  discard block
 block discarded – undo
559 559
 			return false;
560 560
 		}
561 561
 
562
-		if(is_null($ldapName)) {
562
+		if (is_null($ldapName)) {
563 563
 			$ldapName = $this->readAttribute($fdn, $nameAttribute);
564
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
564
+			if (!isset($ldapName[0]) && empty($ldapName[0])) {
565 565
 				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
566 566
 				return false;
567 567
 			}
568 568
 			$ldapName = $ldapName[0];
569 569
 		}
570 570
 
571
-		if($isUser) {
571
+		if ($isUser) {
572 572
 			$usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
573 573
 			if ($usernameAttribute !== '') {
574 574
 				$username = $this->readAttribute($fdn, $usernameAttribute);
@@ -587,9 +587,9 @@  discard block
 block discarded – undo
587 587
 		// outside of core user management will still cache the user as non-existing.
588 588
 		$originalTTL = $this->connection->ldapCacheTTL;
589 589
 		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
590
-		if(($isUser && $intName !== '' && !\OCP\User::userExists($intName))
590
+		if (($isUser && $intName !== '' && !\OCP\User::userExists($intName))
591 591
 			|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
592
-			if($mapper->map($fdn, $intName, $uuid)) {
592
+			if ($mapper->map($fdn, $intName, $uuid)) {
593 593
 				$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
594 594
 				$newlyMapped = true;
595 595
 				return $intName;
@@ -598,7 +598,7 @@  discard block
 block discarded – undo
598 598
 		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
599 599
 
600 600
 		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
601
-		if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
601
+		if (is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
602 602
 			$newlyMapped = true;
603 603
 			return $altName;
604 604
 		}
@@ -636,7 +636,7 @@  discard block
 block discarded – undo
636 636
 	 * @return array
637 637
 	 */
638 638
 	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
639
-		if($isUsers) {
639
+		if ($isUsers) {
640 640
 			$nameAttribute = $this->connection->ldapUserDisplayName;
641 641
 			$sndAttribute  = $this->connection->ldapUserDisplayName2;
642 642
 		} else {
@@ -644,9 +644,9 @@  discard block
 block discarded – undo
644 644
 		}
645 645
 		$nextcloudNames = array();
646 646
 
647
-		foreach($ldapObjects as $ldapObject) {
647
+		foreach ($ldapObjects as $ldapObject) {
648 648
 			$nameByLDAP = null;
649
-			if(    isset($ldapObject[$nameAttribute])
649
+			if (isset($ldapObject[$nameAttribute])
650 650
 				&& is_array($ldapObject[$nameAttribute])
651 651
 				&& isset($ldapObject[$nameAttribute][0])
652 652
 			) {
@@ -655,12 +655,12 @@  discard block
 block discarded – undo
655 655
 			}
656 656
 
657 657
 			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
658
-			if($ncName) {
658
+			if ($ncName) {
659 659
 				$nextcloudNames[] = $ncName;
660
-				if($isUsers) {
660
+				if ($isUsers) {
661 661
 					//cache the user names so it does not need to be retrieved
662 662
 					//again later (e.g. sharing dialogue).
663
-					if(is_null($nameByLDAP)) {
663
+					if (is_null($nameByLDAP)) {
664 664
 						continue;
665 665
 					}
666 666
 					$sndName = isset($ldapObject[$sndAttribute][0])
@@ -698,7 +698,7 @@  discard block
 block discarded – undo
698 698
 	 */
699 699
 	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
700 700
 		$user = $this->userManager->get($ocName);
701
-		if($user === null) {
701
+		if ($user === null) {
702 702
 			return;
703 703
 		}
704 704
 		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
@@ -718,9 +718,9 @@  discard block
 block discarded – undo
718 718
 		$attempts = 0;
719 719
 		//while loop is just a precaution. If a name is not generated within
720 720
 		//20 attempts, something else is very wrong. Avoids infinite loop.
721
-		while($attempts < 20){
722
-			$altName = $name . '_' . rand(1000,9999);
723
-			if(!\OCP\User::userExists($altName)) {
721
+		while ($attempts < 20) {
722
+			$altName = $name.'_'.rand(1000, 9999);
723
+			if (!\OCP\User::userExists($altName)) {
724 724
 				return $altName;
725 725
 			}
726 726
 			$attempts++;
@@ -742,25 +742,25 @@  discard block
 block discarded – undo
742 742
 	 */
743 743
 	private function _createAltInternalOwnCloudNameForGroups($name) {
744 744
 		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
745
-		if(!($usedNames) || count($usedNames) === 0) {
745
+		if (!($usedNames) || count($usedNames) === 0) {
746 746
 			$lastNo = 1; //will become name_2
747 747
 		} else {
748 748
 			natsort($usedNames);
749 749
 			$lastName = array_pop($usedNames);
750 750
 			$lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
751 751
 		}
752
-		$altName = $name.'_'.strval($lastNo+1);
752
+		$altName = $name.'_'.strval($lastNo + 1);
753 753
 		unset($usedNames);
754 754
 
755 755
 		$attempts = 1;
756
-		while($attempts < 21){
756
+		while ($attempts < 21) {
757 757
 			// Check to be really sure it is unique
758 758
 			// while loop is just a precaution. If a name is not generated within
759 759
 			// 20 attempts, something else is very wrong. Avoids infinite loop.
760
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
760
+			if (!\OC::$server->getGroupManager()->groupExists($altName)) {
761 761
 				return $altName;
762 762
 			}
763
-			$altName = $name . '_' . ($lastNo + $attempts);
763
+			$altName = $name.'_'.($lastNo + $attempts);
764 764
 			$attempts++;
765 765
 		}
766 766
 		return false;
@@ -775,7 +775,7 @@  discard block
 block discarded – undo
775 775
 	private function createAltInternalOwnCloudName($name, $isUser) {
776 776
 		$originalTTL = $this->connection->ldapCacheTTL;
777 777
 		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
778
-		if($isUser) {
778
+		if ($isUser) {
779 779
 			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
780 780
 		} else {
781 781
 			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
@@ -825,13 +825,13 @@  discard block
 block discarded – undo
825 825
 	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
826 826
 		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
827 827
 		$recordsToUpdate = $ldapRecords;
828
-		if(!$forceApplyAttributes) {
828
+		if (!$forceApplyAttributes) {
829 829
 			$isBackgroundJobModeAjax = $this->config
830 830
 					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
831 831
 			$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
832 832
 				$newlyMapped = false;
833 833
 				$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
834
-				if(is_string($uid)) {
834
+				if (is_string($uid)) {
835 835
 					$this->cacheUserExists($uid);
836 836
 				}
837 837
 				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
@@ -847,19 +847,19 @@  discard block
 block discarded – undo
847 847
 	 * and their values
848 848
 	 * @param array $ldapRecords
849 849
 	 */
850
-	public function batchApplyUserAttributes(array $ldapRecords){
850
+	public function batchApplyUserAttributes(array $ldapRecords) {
851 851
 		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
852
-		foreach($ldapRecords as $userRecord) {
853
-			if(!isset($userRecord[$displayNameAttribute])) {
852
+		foreach ($ldapRecords as $userRecord) {
853
+			if (!isset($userRecord[$displayNameAttribute])) {
854 854
 				// displayName is obligatory
855 855
 				continue;
856 856
 			}
857
-			$ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
858
-			if($ocName === false) {
857
+			$ocName = $this->dn2ocname($userRecord['dn'][0], null, true);
858
+			if ($ocName === false) {
859 859
 				continue;
860 860
 			}
861 861
 			$user = $this->userManager->get($ocName);
862
-			if($user instanceof OfflineUser) {
862
+			if ($user instanceof OfflineUser) {
863 863
 				$user->unmark();
864 864
 				$user = $this->userManager->get($ocName);
865 865
 			}
@@ -891,8 +891,8 @@  discard block
 block discarded – undo
891 891
 	 * @return array
892 892
 	 */
893 893
 	private function fetchList($list, $manyAttributes) {
894
-		if(is_array($list)) {
895
-			if($manyAttributes) {
894
+		if (is_array($list)) {
895
+			if ($manyAttributes) {
896 896
 				return $list;
897 897
 			} else {
898 898
 				$list = array_reduce($list, function($carry, $item) {
@@ -990,7 +990,7 @@  discard block
 block discarded – undo
990 990
 		// php no longer supports call-time pass-by-reference
991 991
 		// thus cannot support controlPagedResultResponse as the third argument
992 992
 		// is a reference
993
-		$doMethod = function () use ($command, &$arguments) {
993
+		$doMethod = function() use ($command, &$arguments) {
994 994
 			if ($command == 'controlPagedResultResponse') {
995 995
 				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
996 996
 			} else {
@@ -1008,7 +1008,7 @@  discard block
 block discarded – undo
1008 1008
 			$this->connection->resetConnectionResource();
1009 1009
 			$cr = $this->connection->getConnectionResource();
1010 1010
 
1011
-			if(!$this->ldap->isResource($cr)) {
1011
+			if (!$this->ldap->isResource($cr)) {
1012 1012
 				// Seems like we didn't find any resource.
1013 1013
 				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", \OCP\Util::DEBUG);
1014 1014
 				throw $e;
@@ -1033,13 +1033,13 @@  discard block
 block discarded – undo
1033 1033
 	 * @throws ServerNotAvailableException
1034 1034
 	 */
1035 1035
 	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1036
-		if(!is_null($attr) && !is_array($attr)) {
1036
+		if (!is_null($attr) && !is_array($attr)) {
1037 1037
 			$attr = array(mb_strtolower($attr, 'UTF-8'));
1038 1038
 		}
1039 1039
 
1040 1040
 		// See if we have a resource, in case not cancel with message
1041 1041
 		$cr = $this->connection->getConnectionResource();
1042
-		if(!$this->ldap->isResource($cr)) {
1042
+		if (!$this->ldap->isResource($cr)) {
1043 1043
 			// Seems like we didn't find any resource.
1044 1044
 			// Return an empty array just like before.
1045 1045
 			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
@@ -1053,7 +1053,7 @@  discard block
 block discarded – undo
1053 1053
 		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1054 1054
 		// cannot use $cr anymore, might have changed in the previous call!
1055 1055
 		$error = $this->ldap->errno($this->connection->getConnectionResource());
1056
-		if(!is_array($sr) || $error !== 0) {
1056
+		if (!is_array($sr) || $error !== 0) {
1057 1057
 			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
1058 1058
 			return false;
1059 1059
 		}
@@ -1076,26 +1076,26 @@  discard block
 block discarded – undo
1076 1076
 	 */
1077 1077
 	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1078 1078
 		$cookie = null;
1079
-		if($pagedSearchOK) {
1079
+		if ($pagedSearchOK) {
1080 1080
 			$cr = $this->connection->getConnectionResource();
1081
-			foreach($sr as $key => $res) {
1082
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1081
+			foreach ($sr as $key => $res) {
1082
+				if ($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1083 1083
 					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1084 1084
 				}
1085 1085
 			}
1086 1086
 
1087 1087
 			//browsing through prior pages to get the cookie for the new one
1088
-			if($skipHandling) {
1088
+			if ($skipHandling) {
1089 1089
 				return false;
1090 1090
 			}
1091 1091
 			// if count is bigger, then the server does not support
1092 1092
 			// paged search. Instead, he did a normal search. We set a
1093 1093
 			// flag here, so the callee knows how to deal with it.
1094
-			if($iFoundItems <= $limit) {
1094
+			if ($iFoundItems <= $limit) {
1095 1095
 				$this->pagedSearchedSuccessful = true;
1096 1096
 			}
1097 1097
 		} else {
1098
-			if(!is_null($limit)) {
1098
+			if (!is_null($limit)) {
1099 1099
 				\OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO);
1100 1100
 			}
1101 1101
 		}
@@ -1125,7 +1125,7 @@  discard block
 block discarded – undo
1125 1125
 		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1126 1126
 
1127 1127
 		$limitPerPage = intval($this->connection->ldapPagingSize);
1128
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1128
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1129 1129
 			$limitPerPage = $limit;
1130 1130
 		}
1131 1131
 
@@ -1135,7 +1135,7 @@  discard block
 block discarded – undo
1135 1135
 
1136 1136
 		do {
1137 1137
 			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1138
-			if($search === false) {
1138
+			if ($search === false) {
1139 1139
 				return $counter > 0 ? $counter : false;
1140 1140
 			}
1141 1141
 			list($sr, $pagedSearchOK) = $search;
@@ -1154,7 +1154,7 @@  discard block
 block discarded – undo
1154 1154
 			 * Continue now depends on $hasMorePages value
1155 1155
 			 */
1156 1156
 			$continue = $pagedSearchOK && $hasMorePages;
1157
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1157
+		} while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1158 1158
 
1159 1159
 		return $counter;
1160 1160
 	}
@@ -1166,7 +1166,7 @@  discard block
 block discarded – undo
1166 1166
 	private function countEntriesInSearchResults($searchResults) {
1167 1167
 		$counter = 0;
1168 1168
 
1169
-		foreach($searchResults as $res) {
1169
+		foreach ($searchResults as $res) {
1170 1170
 			$count = intval($this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res));
1171 1171
 			$counter += $count;
1172 1172
 		}
@@ -1188,7 +1188,7 @@  discard block
 block discarded – undo
1188 1188
 	 */
1189 1189
 	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1190 1190
 		$limitPerPage = intval($this->connection->ldapPagingSize);
1191
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1191
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1192 1192
 			$limitPerPage = $limit;
1193 1193
 		}
1194 1194
 
@@ -1202,13 +1202,13 @@  discard block
 block discarded – undo
1202 1202
 		$savedoffset = $offset;
1203 1203
 		do {
1204 1204
 			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1205
-			if($search === false) {
1205
+			if ($search === false) {
1206 1206
 				return [];
1207 1207
 			}
1208 1208
 			list($sr, $pagedSearchOK) = $search;
1209 1209
 			$cr = $this->connection->getConnectionResource();
1210 1210
 
1211
-			if($skipHandling) {
1211
+			if ($skipHandling) {
1212 1212
 				//i.e. result do not need to be fetched, we just need the cookie
1213 1213
 				//thus pass 1 or any other value as $iFoundItems because it is not
1214 1214
 				//used
@@ -1219,7 +1219,7 @@  discard block
 block discarded – undo
1219 1219
 			}
1220 1220
 
1221 1221
 			$iFoundItems = 0;
1222
-			foreach($sr as $res) {
1222
+			foreach ($sr as $res) {
1223 1223
 				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1224 1224
 				$iFoundItems = max($iFoundItems, $findings['count']);
1225 1225
 				unset($findings['count']);
@@ -1235,27 +1235,27 @@  discard block
 block discarded – undo
1235 1235
 
1236 1236
 		// if we're here, probably no connection resource is returned.
1237 1237
 		// to make Nextcloud behave nicely, we simply give back an empty array.
1238
-		if(is_null($findings)) {
1238
+		if (is_null($findings)) {
1239 1239
 			return array();
1240 1240
 		}
1241 1241
 
1242
-		if(!is_null($attr)) {
1242
+		if (!is_null($attr)) {
1243 1243
 			$selection = [];
1244 1244
 			$i = 0;
1245
-			foreach($findings as $item) {
1246
-				if(!is_array($item)) {
1245
+			foreach ($findings as $item) {
1246
+				if (!is_array($item)) {
1247 1247
 					continue;
1248 1248
 				}
1249 1249
 				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1250
-				foreach($attr as $key) {
1251
-					if(isset($item[$key])) {
1252
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1250
+				foreach ($attr as $key) {
1251
+					if (isset($item[$key])) {
1252
+						if (is_array($item[$key]) && isset($item[$key]['count'])) {
1253 1253
 							unset($item[$key]['count']);
1254 1254
 						}
1255
-						if($key !== 'dn') {
1256
-							if($this->resemblesDN($key)) {
1255
+						if ($key !== 'dn') {
1256
+							if ($this->resemblesDN($key)) {
1257 1257
 								$selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1258
-							} else if($key === 'objectguid' || $key === 'guid') {
1258
+							} else if ($key === 'objectguid' || $key === 'guid') {
1259 1259
 								$selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1260 1260
 							} else {
1261 1261
 								$selection[$i][$key] = $item[$key];
@@ -1273,7 +1273,7 @@  discard block
 block discarded – undo
1273 1273
 		//we slice the findings, when
1274 1274
 		//a) paged search unsuccessful, though attempted
1275 1275
 		//b) no paged search, but limit set
1276
-		if((!$this->getPagedSearchResultState()
1276
+		if ((!$this->getPagedSearchResultState()
1277 1277
 			&& $pagedSearchOK)
1278 1278
 			|| (
1279 1279
 				!$pagedSearchOK
@@ -1290,7 +1290,7 @@  discard block
 block discarded – undo
1290 1290
 	 * @return bool|mixed|string
1291 1291
 	 */
1292 1292
 	public function sanitizeUsername($name) {
1293
-		if($this->connection->ldapIgnoreNamingRules) {
1293
+		if ($this->connection->ldapIgnoreNamingRules) {
1294 1294
 			return trim($name);
1295 1295
 		}
1296 1296
 
@@ -1315,13 +1315,13 @@  discard block
 block discarded – undo
1315 1315
 	*/
1316 1316
 	public function escapeFilterPart($input, $allowAsterisk = false) {
1317 1317
 		$asterisk = '';
1318
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1318
+		if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1319 1319
 			$asterisk = '*';
1320 1320
 			$input = mb_substr($input, 1, null, 'UTF-8');
1321 1321
 		}
1322 1322
 		$search  = array('*', '\\', '(', ')');
1323 1323
 		$replace = array('\\*', '\\\\', '\\(', '\\)');
1324
-		return $asterisk . str_replace($search, $replace, $input);
1324
+		return $asterisk.str_replace($search, $replace, $input);
1325 1325
 	}
1326 1326
 
1327 1327
 	/**
@@ -1351,13 +1351,13 @@  discard block
 block discarded – undo
1351 1351
 	 */
1352 1352
 	private function combineFilter($filters, $operator) {
1353 1353
 		$combinedFilter = '('.$operator;
1354
-		foreach($filters as $filter) {
1354
+		foreach ($filters as $filter) {
1355 1355
 			if ($filter !== '' && $filter[0] !== '(') {
1356 1356
 				$filter = '('.$filter.')';
1357 1357
 			}
1358
-			$combinedFilter.=$filter;
1358
+			$combinedFilter .= $filter;
1359 1359
 		}
1360
-		$combinedFilter.=')';
1360
+		$combinedFilter .= ')';
1361 1361
 		return $combinedFilter;
1362 1362
 	}
1363 1363
 
@@ -1393,17 +1393,17 @@  discard block
 block discarded – undo
1393 1393
 	 * @throws \Exception
1394 1394
 	 */
1395 1395
 	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1396
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1396
+		if (!is_array($searchAttributes) || count($searchAttributes) < 2) {
1397 1397
 			throw new \Exception('searchAttributes must be an array with at least two string');
1398 1398
 		}
1399 1399
 		$searchWords = explode(' ', trim($search));
1400 1400
 		$wordFilters = array();
1401
-		foreach($searchWords as $word) {
1401
+		foreach ($searchWords as $word) {
1402 1402
 			$word = $this->prepareSearchTerm($word);
1403 1403
 			//every word needs to appear at least once
1404 1404
 			$wordMatchOneAttrFilters = array();
1405
-			foreach($searchAttributes as $attr) {
1406
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1405
+			foreach ($searchAttributes as $attr) {
1406
+				$wordMatchOneAttrFilters[] = $attr.'='.$word;
1407 1407
 			}
1408 1408
 			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1409 1409
 		}
@@ -1421,10 +1421,10 @@  discard block
 block discarded – undo
1421 1421
 	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1422 1422
 		$filter = array();
1423 1423
 		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1424
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1424
+		if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1425 1425
 			try {
1426 1426
 				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1427
-			} catch(\Exception $e) {
1427
+			} catch (\Exception $e) {
1428 1428
 				\OCP\Util::writeLog(
1429 1429
 					'user_ldap',
1430 1430
 					'Creating advanced filter for search failed, falling back to simple method.',
@@ -1434,17 +1434,17 @@  discard block
 block discarded – undo
1434 1434
 		}
1435 1435
 
1436 1436
 		$search = $this->prepareSearchTerm($search);
1437
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1437
+		if (!is_array($searchAttributes) || count($searchAttributes) === 0) {
1438 1438
 			if ($fallbackAttribute === '') {
1439 1439
 				return '';
1440 1440
 			}
1441
-			$filter[] = $fallbackAttribute . '=' . $search;
1441
+			$filter[] = $fallbackAttribute.'='.$search;
1442 1442
 		} else {
1443
-			foreach($searchAttributes as $attribute) {
1444
-				$filter[] = $attribute . '=' . $search;
1443
+			foreach ($searchAttributes as $attribute) {
1444
+				$filter[] = $attribute.'='.$search;
1445 1445
 			}
1446 1446
 		}
1447
-		if(count($filter) === 1) {
1447
+		if (count($filter) === 1) {
1448 1448
 			return '('.$filter[0].')';
1449 1449
 		}
1450 1450
 		return $this->combineFilterWithOr($filter);
@@ -1465,7 +1465,7 @@  discard block
 block discarded – undo
1465 1465
 		if ($term === '') {
1466 1466
 			$result = '*';
1467 1467
 		} else if ($allowEnum !== 'no') {
1468
-			$result = $term . '*';
1468
+			$result = $term.'*';
1469 1469
 		}
1470 1470
 		return $result;
1471 1471
 	}
@@ -1477,7 +1477,7 @@  discard block
 block discarded – undo
1477 1477
 	public function getFilterForUserCount() {
1478 1478
 		$filter = $this->combineFilterWithAnd(array(
1479 1479
 			$this->connection->ldapUserFilter,
1480
-			$this->connection->ldapUserDisplayName . '=*'
1480
+			$this->connection->ldapUserDisplayName.'=*'
1481 1481
 		));
1482 1482
 
1483 1483
 		return $filter;
@@ -1495,7 +1495,7 @@  discard block
 block discarded – undo
1495 1495
 			'ldapAgentName' => $name,
1496 1496
 			'ldapAgentPassword' => $password
1497 1497
 		);
1498
-		if(!$testConnection->setConfiguration($credentials)) {
1498
+		if (!$testConnection->setConfiguration($credentials)) {
1499 1499
 			return false;
1500 1500
 		}
1501 1501
 		return $testConnection->bind();
@@ -1517,30 +1517,30 @@  discard block
 block discarded – undo
1517 1517
 			// Sacrebleu! The UUID attribute is unknown :( We need first an
1518 1518
 			// existing DN to be able to reliably detect it.
1519 1519
 			$result = $this->search($filter, $base, ['dn'], 1);
1520
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1520
+			if (!isset($result[0]) || !isset($result[0]['dn'])) {
1521 1521
 				throw new \Exception('Cannot determine UUID attribute');
1522 1522
 			}
1523 1523
 			$dn = $result[0]['dn'][0];
1524
-			if(!$this->detectUuidAttribute($dn, true)) {
1524
+			if (!$this->detectUuidAttribute($dn, true)) {
1525 1525
 				throw new \Exception('Cannot determine UUID attribute');
1526 1526
 			}
1527 1527
 		} else {
1528 1528
 			// The UUID attribute is either known or an override is given.
1529 1529
 			// By calling this method we ensure that $this->connection->$uuidAttr
1530 1530
 			// is definitely set
1531
-			if(!$this->detectUuidAttribute('', true)) {
1531
+			if (!$this->detectUuidAttribute('', true)) {
1532 1532
 				throw new \Exception('Cannot determine UUID attribute');
1533 1533
 			}
1534 1534
 		}
1535 1535
 
1536 1536
 		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1537
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1537
+		if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1538 1538
 			$uuid = $this->formatGuid2ForFilterUser($uuid);
1539 1539
 		}
1540 1540
 
1541
-		$filter = $uuidAttr . '=' . $uuid;
1541
+		$filter = $uuidAttr.'='.$uuid;
1542 1542
 		$result = $this->searchUsers($filter, ['dn'], 2);
1543
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1543
+		if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1544 1544
 			// we put the count into account to make sure that this is
1545 1545
 			// really unique
1546 1546
 			return $result[0]['dn'][0];
@@ -1559,7 +1559,7 @@  discard block
 block discarded – undo
1559 1559
 	 * @return bool true on success, false otherwise
1560 1560
 	 */
1561 1561
 	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1562
-		if($isUser) {
1562
+		if ($isUser) {
1563 1563
 			$uuidAttr     = 'ldapUuidUserAttribute';
1564 1564
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1565 1565
 		} else {
@@ -1567,7 +1567,7 @@  discard block
 block discarded – undo
1567 1567
 			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1568 1568
 		}
1569 1569
 
1570
-		if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1570
+		if (($this->connection->$uuidAttr !== 'auto') && !$force) {
1571 1571
 			return true;
1572 1572
 		}
1573 1573
 
@@ -1576,10 +1576,10 @@  discard block
 block discarded – undo
1576 1576
 			return true;
1577 1577
 		}
1578 1578
 
1579
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1580
-			if($ldapRecord !== null) {
1579
+		foreach (self::UUID_ATTRIBUTES as $attribute) {
1580
+			if ($ldapRecord !== null) {
1581 1581
 				// we have the info from LDAP already, we don't need to talk to the server again
1582
-				if(isset($ldapRecord[$attribute])) {
1582
+				if (isset($ldapRecord[$attribute])) {
1583 1583
 					$this->connection->$uuidAttr = $attribute;
1584 1584
 					return true;
1585 1585
 				} else {
@@ -1588,7 +1588,7 @@  discard block
 block discarded – undo
1588 1588
 			}
1589 1589
 
1590 1590
 			$value = $this->readAttribute($dn, $attribute);
1591
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1591
+			if (is_array($value) && isset($value[0]) && !empty($value[0])) {
1592 1592
 				\OCP\Util::writeLog('user_ldap',
1593 1593
 									'Setting '.$attribute.' as '.$uuidAttr,
1594 1594
 									\OCP\Util::DEBUG);
@@ -1610,7 +1610,7 @@  discard block
 block discarded – undo
1610 1610
 	 * @return bool|string
1611 1611
 	 */
1612 1612
 	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1613
-		if($isUser) {
1613
+		if ($isUser) {
1614 1614
 			$uuidAttr     = 'ldapUuidUserAttribute';
1615 1615
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1616 1616
 		} else {
@@ -1619,10 +1619,10 @@  discard block
 block discarded – undo
1619 1619
 		}
1620 1620
 
1621 1621
 		$uuid = false;
1622
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1622
+		if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1623 1623
 			$attr = $this->connection->$uuidAttr;
1624 1624
 			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1625
-			if( !is_array($uuid)
1625
+			if (!is_array($uuid)
1626 1626
 				&& $uuidOverride !== ''
1627 1627
 				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1628 1628
 			{
@@ -1630,7 +1630,7 @@  discard block
 block discarded – undo
1630 1630
 					? $ldapRecord[$this->connection->$uuidAttr]
1631 1631
 					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1632 1632
 			}
1633
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1633
+			if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1634 1634
 				$uuid = $uuid[0];
1635 1635
 			}
1636 1636
 		}
@@ -1647,19 +1647,19 @@  discard block
 block discarded – undo
1647 1647
 	private function convertObjectGUID2Str($oguid) {
1648 1648
 		$hex_guid = bin2hex($oguid);
1649 1649
 		$hex_guid_to_guid_str = '';
1650
-		for($k = 1; $k <= 4; ++$k) {
1650
+		for ($k = 1; $k <= 4; ++$k) {
1651 1651
 			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1652 1652
 		}
1653 1653
 		$hex_guid_to_guid_str .= '-';
1654
-		for($k = 1; $k <= 2; ++$k) {
1654
+		for ($k = 1; $k <= 2; ++$k) {
1655 1655
 			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1656 1656
 		}
1657 1657
 		$hex_guid_to_guid_str .= '-';
1658
-		for($k = 1; $k <= 2; ++$k) {
1658
+		for ($k = 1; $k <= 2; ++$k) {
1659 1659
 			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1660 1660
 		}
1661
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1662
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1661
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 16, 4);
1662
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 20);
1663 1663
 
1664 1664
 		return strtoupper($hex_guid_to_guid_str);
1665 1665
 	}
@@ -1676,11 +1676,11 @@  discard block
 block discarded – undo
1676 1676
 	 * @return string
1677 1677
 	 */
1678 1678
 	public function formatGuid2ForFilterUser($guid) {
1679
-		if(!is_string($guid)) {
1679
+		if (!is_string($guid)) {
1680 1680
 			throw new \InvalidArgumentException('String expected');
1681 1681
 		}
1682 1682
 		$blocks = explode('-', $guid);
1683
-		if(count($blocks) !== 5) {
1683
+		if (count($blocks) !== 5) {
1684 1684
 			/*
1685 1685
 			 * Why not throw an Exception instead? This method is a utility
1686 1686
 			 * called only when trying to figure out whether a "missing" known
@@ -1693,20 +1693,20 @@  discard block
 block discarded – undo
1693 1693
 			 * user. Instead we write a log message.
1694 1694
 			 */
1695 1695
 			\OC::$server->getLogger()->info(
1696
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1696
+				'Passed string does not resemble a valid GUID. Known UUID '.
1697 1697
 				'({uuid}) probably does not match UUID configuration.',
1698
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1698
+				['app' => 'user_ldap', 'uuid' => $guid]
1699 1699
 			);
1700 1700
 			return $guid;
1701 1701
 		}
1702
-		for($i=0; $i < 3; $i++) {
1702
+		for ($i = 0; $i < 3; $i++) {
1703 1703
 			$pairs = str_split($blocks[$i], 2);
1704 1704
 			$pairs = array_reverse($pairs);
1705 1705
 			$blocks[$i] = implode('', $pairs);
1706 1706
 		}
1707
-		for($i=0; $i < 5; $i++) {
1707
+		for ($i = 0; $i < 5; $i++) {
1708 1708
 			$pairs = str_split($blocks[$i], 2);
1709
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1709
+			$blocks[$i] = '\\'.implode('\\', $pairs);
1710 1710
 		}
1711 1711
 		return implode('', $blocks);
1712 1712
 	}
@@ -1720,12 +1720,12 @@  discard block
 block discarded – undo
1720 1720
 		$domainDN = $this->getDomainDNFromDN($dn);
1721 1721
 		$cacheKey = 'getSID-'.$domainDN;
1722 1722
 		$sid = $this->connection->getFromCache($cacheKey);
1723
-		if(!is_null($sid)) {
1723
+		if (!is_null($sid)) {
1724 1724
 			return $sid;
1725 1725
 		}
1726 1726
 
1727 1727
 		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1728
-		if(!is_array($objectSid) || empty($objectSid)) {
1728
+		if (!is_array($objectSid) || empty($objectSid)) {
1729 1729
 			$this->connection->writeToCache($cacheKey, false);
1730 1730
 			return false;
1731 1731
 		}
@@ -1783,12 +1783,12 @@  discard block
 block discarded – undo
1783 1783
 		$belongsToBase = false;
1784 1784
 		$bases = $this->helper->sanitizeDN($bases);
1785 1785
 
1786
-		foreach($bases as $base) {
1786
+		foreach ($bases as $base) {
1787 1787
 			$belongsToBase = true;
1788
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1788
+			if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) {
1789 1789
 				$belongsToBase = false;
1790 1790
 			}
1791
-			if($belongsToBase) {
1791
+			if ($belongsToBase) {
1792 1792
 				break;
1793 1793
 			}
1794 1794
 		}
@@ -1799,7 +1799,7 @@  discard block
 block discarded – undo
1799 1799
 	 * resets a running Paged Search operation
1800 1800
 	 */
1801 1801
 	private function abandonPagedSearch() {
1802
-		if($this->connection->hasPagedResultSupport) {
1802
+		if ($this->connection->hasPagedResultSupport) {
1803 1803
 			$cr = $this->connection->getConnectionResource();
1804 1804
 			$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1805 1805
 			$this->getPagedSearchResultState();
@@ -1817,16 +1817,16 @@  discard block
 block discarded – undo
1817 1817
 	 * @return string containing the key or empty if none is cached
1818 1818
 	 */
1819 1819
 	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1820
-		if($offset === 0) {
1820
+		if ($offset === 0) {
1821 1821
 			return '';
1822 1822
 		}
1823 1823
 		$offset -= $limit;
1824 1824
 		//we work with cache here
1825
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1825
+		$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.intval($limit).'-'.intval($offset);
1826 1826
 		$cookie = '';
1827
-		if(isset($this->cookies[$cacheKey])) {
1827
+		if (isset($this->cookies[$cacheKey])) {
1828 1828
 			$cookie = $this->cookies[$cacheKey];
1829
-			if(is_null($cookie)) {
1829
+			if (is_null($cookie)) {
1830 1830
 				$cookie = '';
1831 1831
 			}
1832 1832
 		}
@@ -1844,11 +1844,11 @@  discard block
 block discarded – undo
1844 1844
 	 * @return bool
1845 1845
 	 */
1846 1846
 	public function hasMoreResults() {
1847
-		if(!$this->connection->hasPagedResultSupport) {
1847
+		if (!$this->connection->hasPagedResultSupport) {
1848 1848
 			return false;
1849 1849
 		}
1850 1850
 
1851
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1851
+		if (empty($this->lastCookie) && $this->lastCookie !== '0') {
1852 1852
 			// as in RFC 2696, when all results are returned, the cookie will
1853 1853
 			// be empty.
1854 1854
 			return false;
@@ -1868,8 +1868,8 @@  discard block
 block discarded – undo
1868 1868
 	 */
1869 1869
 	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1870 1870
 		// allow '0' for 389ds
1871
-		if(!empty($cookie) || $cookie === '0') {
1872
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1871
+		if (!empty($cookie) || $cookie === '0') {
1872
+			$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.intval($limit).'-'.intval($offset);
1873 1873
 			$this->cookies[$cacheKey] = $cookie;
1874 1874
 			$this->lastCookie = $cookie;
1875 1875
 		}
@@ -1896,22 +1896,22 @@  discard block
 block discarded – undo
1896 1896
 	 */
1897 1897
 	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1898 1898
 		$pagedSearchOK = false;
1899
-		if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1899
+		if ($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1900 1900
 			$offset = intval($offset); //can be null
1901 1901
 			\OCP\Util::writeLog('user_ldap',
1902 1902
 				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1903
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1903
+				.' attr '.print_r($attr, true).' limit '.$limit.' offset '.$offset,
1904 1904
 				\OCP\Util::DEBUG);
1905 1905
 			//get the cookie from the search for the previous search, required by LDAP
1906
-			foreach($bases as $base) {
1906
+			foreach ($bases as $base) {
1907 1907
 
1908 1908
 				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1909
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1909
+				if (empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1910 1910
 					// no cookie known from a potential previous search. We need
1911 1911
 					// to start from 0 to come to the desired page. cookie value
1912 1912
 					// of '0' is valid, because 389ds
1913 1913
 					$reOffset = 0;
1914
-					while($reOffset < $offset) {
1914
+					while ($reOffset < $offset) {
1915 1915
 						$this->search($filter, array($base), $attr, $limit, $reOffset, true);
1916 1916
 						$reOffset += $limit;
1917 1917
 					}
@@ -1919,17 +1919,17 @@  discard block
 block discarded – undo
1919 1919
 					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1920 1920
 					// '0' is valid, because 389ds
1921 1921
 					//TODO: remember this, probably does not change in the next request...
1922
-					if(empty($cookie) && $cookie !== '0') {
1922
+					if (empty($cookie) && $cookie !== '0') {
1923 1923
 						$cookie = null;
1924 1924
 					}
1925 1925
 				}
1926
-				if(!is_null($cookie)) {
1926
+				if (!is_null($cookie)) {
1927 1927
 					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1928 1928
 					$this->abandonPagedSearch();
1929 1929
 					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1930 1930
 						$this->connection->getConnectionResource(), $limit,
1931 1931
 						false, $cookie);
1932
-					if(!$pagedSearchOK) {
1932
+					if (!$pagedSearchOK) {
1933 1933
 						return false;
1934 1934
 					}
1935 1935
 					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
@@ -1946,7 +1946,7 @@  discard block
 block discarded – undo
1946 1946
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
1947 1947
 		 * if we don't have a previous paged search.
1948 1948
 		 */
1949
-		} else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1949
+		} else if ($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1950 1950
 			// a search without limit was requested. However, if we do use
1951 1951
 			// Paged Search once, we always must do it. This requires us to
1952 1952
 			// initialize it with the configured page size.
Please login to merge, or discard this patch.