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