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