Completed
Pull Request — master (#8634)
by Blizzz
33:44 queued 15:43
created
apps/user_ldap/lib/Access.php 2 patches
Doc Comments   +6 added lines, -5 removed lines patch added patch discarded remove patch
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
 
507 507
 	/**
508 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
509
+	 * @param string $fdn the dn of the user object
510 510
 	 * @param string $ldapName optional, the display name of the object
511 511
 	 * @return string|false with with the name to use in Nextcloud
512 512
 	 */
@@ -805,7 +805,7 @@  discard block
 block discarded – undo
805 805
 	 * the login filter.
806 806
 	 *
807 807
 	 * @param string $loginName
808
-	 * @param array $attributes optional, list of attributes to read
808
+	 * @param string[] $attributes optional, list of attributes to read
809 809
 	 * @return array
810 810
 	 */
811 811
 	public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
 
890 890
 	/**
891 891
 	 * @param string $filter
892
-	 * @param string|string[] $attr
892
+	 * @param string[] $attr
893 893
 	 * @param int $limit
894 894
 	 * @param int $offset
895 895
 	 * @return array
@@ -937,7 +937,7 @@  discard block
 block discarded – undo
937 937
 
938 938
 	/**
939 939
 	 * @param string $filter
940
-	 * @param string|string[] $attr
940
+	 * @param string[] $attr
941 941
 	 * @param int $limit
942 942
 	 * @param int $offset
943 943
 	 * @return false|int
@@ -1036,7 +1036,7 @@  discard block
 block discarded – undo
1036 1036
 	/**
1037 1037
 	 * retrieved. Results will according to the order in the array.
1038 1038
 	 *
1039
-	 * @param $filter
1039
+	 * @param string $filter
1040 1040
 	 * @param $base
1041 1041
 	 * @param string[]|string|null $attr
1042 1042
 	 * @param int $limit optional, maximum results to be counted
@@ -1331,6 +1331,7 @@  discard block
 block discarded – undo
1331 1331
 	* escapes (user provided) parts for LDAP filter
1332 1332
 	* @param string $input, the provided value
1333 1333
 	* @param bool $allowAsterisk whether in * at the beginning should be preserved
1334
+	* @param string $input
1334 1335
 	* @return string the escaped string
1335 1336
 	*/
1336 1337
 	public function escapeFilterPart($input, $allowAsterisk = false) {
Please login to merge, or discard this patch.
Indentation   +1890 added lines, -1890 removed lines patch added patch discarded remove patch
@@ -59,1655 +59,1655 @@  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 alternative 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 alternative 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
-	 * @throws \InvalidArgumentException
1308
-	 */
1309
-	public function sanitizeUsername($name) {
1310
-		$name = trim($name);
1311
-
1312
-		if($this->connection->ldapIgnoreNamingRules) {
1313
-			return $name;
1314
-		}
1315
-
1316
-		// Transliteration to ASCII
1317
-		$transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1318
-		if($transliterated !== false) {
1319
-			// depending on system config iconv can work or not
1320
-			$name = $transliterated;
1321
-		}
1322
-
1323
-		// Replacements
1324
-		$name = str_replace(' ', '_', $name);
1325
-
1326
-		// Every remaining disallowed characters will be removed
1327
-		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1328
-
1329
-		if($name === '') {
1330
-			throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1331
-		}
1332
-
1333
-		return $name;
1334
-	}
1335
-
1336
-	/**
1337
-	* escapes (user provided) parts for LDAP filter
1338
-	* @param string $input, the provided value
1339
-	* @param bool $allowAsterisk whether in * at the beginning should be preserved
1340
-	* @return string the escaped string
1341
-	*/
1342
-	public function escapeFilterPart($input, $allowAsterisk = false) {
1343
-		$asterisk = '';
1344
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1345
-			$asterisk = '*';
1346
-			$input = mb_substr($input, 1, null, 'UTF-8');
1347
-		}
1348
-		$search  = array('*', '\\', '(', ')');
1349
-		$replace = array('\\*', '\\\\', '\\(', '\\)');
1350
-		return $asterisk . str_replace($search, $replace, $input);
1351
-	}
1352
-
1353
-	/**
1354
-	 * combines the input filters with AND
1355
-	 * @param string[] $filters the filters to connect
1356
-	 * @return string the combined filter
1357
-	 */
1358
-	public function combineFilterWithAnd($filters) {
1359
-		return $this->combineFilter($filters, '&');
1360
-	}
1361
-
1362
-	/**
1363
-	 * combines the input filters with OR
1364
-	 * @param string[] $filters the filters to connect
1365
-	 * @return string the combined filter
1366
-	 * Combines Filter arguments with OR
1367
-	 */
1368
-	public function combineFilterWithOr($filters) {
1369
-		return $this->combineFilter($filters, '|');
1370
-	}
1371
-
1372
-	/**
1373
-	 * combines the input filters with given operator
1374
-	 * @param string[] $filters the filters to connect
1375
-	 * @param string $operator either & or |
1376
-	 * @return string the combined filter
1377
-	 */
1378
-	private function combineFilter($filters, $operator) {
1379
-		$combinedFilter = '('.$operator;
1380
-		foreach($filters as $filter) {
1381
-			if ($filter !== '' && $filter[0] !== '(') {
1382
-				$filter = '('.$filter.')';
1383
-			}
1384
-			$combinedFilter.=$filter;
1385
-		}
1386
-		$combinedFilter.=')';
1387
-		return $combinedFilter;
1388
-	}
1389
-
1390
-	/**
1391
-	 * creates a filter part for to perform search for users
1392
-	 * @param string $search the search term
1393
-	 * @return string the final filter part to use in LDAP searches
1394
-	 */
1395
-	public function getFilterPartForUserSearch($search) {
1396
-		return $this->getFilterPartForSearch($search,
1397
-			$this->connection->ldapAttributesForUserSearch,
1398
-			$this->connection->ldapUserDisplayName);
1399
-	}
1400
-
1401
-	/**
1402
-	 * creates a filter part for to perform search for groups
1403
-	 * @param string $search the search term
1404
-	 * @return string the final filter part to use in LDAP searches
1405
-	 */
1406
-	public function getFilterPartForGroupSearch($search) {
1407
-		return $this->getFilterPartForSearch($search,
1408
-			$this->connection->ldapAttributesForGroupSearch,
1409
-			$this->connection->ldapGroupDisplayName);
1410
-	}
1411
-
1412
-	/**
1413
-	 * creates a filter part for searches by splitting up the given search
1414
-	 * string into single words
1415
-	 * @param string $search the search term
1416
-	 * @param string[] $searchAttributes needs to have at least two attributes,
1417
-	 * otherwise it does not make sense :)
1418
-	 * @return string the final filter part to use in LDAP searches
1419
-	 * @throws \Exception
1420
-	 */
1421
-	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1422
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1423
-			throw new \Exception('searchAttributes must be an array with at least two string');
1424
-		}
1425
-		$searchWords = explode(' ', trim($search));
1426
-		$wordFilters = array();
1427
-		foreach($searchWords as $word) {
1428
-			$word = $this->prepareSearchTerm($word);
1429
-			//every word needs to appear at least once
1430
-			$wordMatchOneAttrFilters = array();
1431
-			foreach($searchAttributes as $attr) {
1432
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1433
-			}
1434
-			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1435
-		}
1436
-		return $this->combineFilterWithAnd($wordFilters);
1437
-	}
1438
-
1439
-	/**
1440
-	 * creates a filter part for searches
1441
-	 * @param string $search the search term
1442
-	 * @param string[]|null $searchAttributes
1443
-	 * @param string $fallbackAttribute a fallback attribute in case the user
1444
-	 * did not define search attributes. Typically the display name attribute.
1445
-	 * @return string the final filter part to use in LDAP searches
1446
-	 */
1447
-	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1448
-		$filter = array();
1449
-		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1450
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1451
-			try {
1452
-				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1453
-			} catch(\Exception $e) {
1454
-				\OCP\Util::writeLog(
1455
-					'user_ldap',
1456
-					'Creating advanced filter for search failed, falling back to simple method.',
1457
-					\OCP\Util::INFO
1458
-				);
1459
-			}
1460
-		}
1461
-
1462
-		$search = $this->prepareSearchTerm($search);
1463
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1464
-			if ($fallbackAttribute === '') {
1465
-				return '';
1466
-			}
1467
-			$filter[] = $fallbackAttribute . '=' . $search;
1468
-		} else {
1469
-			foreach($searchAttributes as $attribute) {
1470
-				$filter[] = $attribute . '=' . $search;
1471
-			}
1472
-		}
1473
-		if(count($filter) === 1) {
1474
-			return '('.$filter[0].')';
1475
-		}
1476
-		return $this->combineFilterWithOr($filter);
1477
-	}
1478
-
1479
-	/**
1480
-	 * returns the search term depending on whether we are allowed
1481
-	 * list users found by ldap with the current input appended by
1482
-	 * a *
1483
-	 * @return string
1484
-	 */
1485
-	private function prepareSearchTerm($term) {
1486
-		$config = \OC::$server->getConfig();
1487
-
1488
-		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1489
-
1490
-		$result = $term;
1491
-		if ($term === '') {
1492
-			$result = '*';
1493
-		} else if ($allowEnum !== 'no') {
1494
-			$result = $term . '*';
1495
-		}
1496
-		return $result;
1497
-	}
1498
-
1499
-	/**
1500
-	 * returns the filter used for counting users
1501
-	 * @return string
1502
-	 */
1503
-	public function getFilterForUserCount() {
1504
-		$filter = $this->combineFilterWithAnd(array(
1505
-			$this->connection->ldapUserFilter,
1506
-			$this->connection->ldapUserDisplayName . '=*'
1507
-		));
1508
-
1509
-		return $filter;
1510
-	}
1511
-
1512
-	/**
1513
-	 * @param string $name
1514
-	 * @param string $password
1515
-	 * @return bool
1516
-	 */
1517
-	public function areCredentialsValid($name, $password) {
1518
-		$name = $this->helper->DNasBaseParameter($name);
1519
-		$testConnection = clone $this->connection;
1520
-		$credentials = array(
1521
-			'ldapAgentName' => $name,
1522
-			'ldapAgentPassword' => $password
1523
-		);
1524
-		if(!$testConnection->setConfiguration($credentials)) {
1525
-			return false;
1526
-		}
1527
-		return $testConnection->bind();
1528
-	}
1529
-
1530
-	/**
1531
-	 * reverse lookup of a DN given a known UUID
1532
-	 *
1533
-	 * @param string $uuid
1534
-	 * @return string
1535
-	 * @throws \Exception
1536
-	 */
1537
-	public function getUserDnByUuid($uuid) {
1538
-		$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1539
-		$filter       = $this->connection->ldapUserFilter;
1540
-		$base         = $this->connection->ldapBaseUsers;
1541
-
1542
-		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1543
-			// Sacrebleu! The UUID attribute is unknown :( We need first an
1544
-			// existing DN to be able to reliably detect it.
1545
-			$result = $this->search($filter, $base, ['dn'], 1);
1546
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1547
-				throw new \Exception('Cannot determine UUID attribute');
1548
-			}
1549
-			$dn = $result[0]['dn'][0];
1550
-			if(!$this->detectUuidAttribute($dn, true)) {
1551
-				throw new \Exception('Cannot determine UUID attribute');
1552
-			}
1553
-		} else {
1554
-			// The UUID attribute is either known or an override is given.
1555
-			// By calling this method we ensure that $this->connection->$uuidAttr
1556
-			// is definitely set
1557
-			if(!$this->detectUuidAttribute('', true)) {
1558
-				throw new \Exception('Cannot determine UUID attribute');
1559
-			}
1560
-		}
1561
-
1562
-		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1563
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1564
-			$uuid = $this->formatGuid2ForFilterUser($uuid);
1565
-		}
1566
-
1567
-		$filter = $uuidAttr . '=' . $uuid;
1568
-		$result = $this->searchUsers($filter, ['dn'], 2);
1569
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1570
-			// we put the count into account to make sure that this is
1571
-			// really unique
1572
-			return $result[0]['dn'][0];
1573
-		}
1574
-
1575
-		throw new \Exception('Cannot determine UUID attribute');
1576
-	}
1577
-
1578
-	/**
1579
-	 * auto-detects the directory's UUID attribute
1580
-	 *
1581
-	 * @param string $dn a known DN used to check against
1582
-	 * @param bool $isUser
1583
-	 * @param bool $force the detection should be run, even if it is not set to auto
1584
-	 * @param array|null $ldapRecord
1585
-	 * @return bool true on success, false otherwise
1586
-	 */
1587
-	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1588
-		if($isUser) {
1589
-			$uuidAttr     = 'ldapUuidUserAttribute';
1590
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1591
-		} else {
1592
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1593
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1594
-		}
1595
-
1596
-		if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1597
-			return true;
1598
-		}
1599
-
1600
-		if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1601
-			$this->connection->$uuidAttr = $uuidOverride;
1602
-			return true;
1603
-		}
1604
-
1605
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1606
-			if($ldapRecord !== null) {
1607
-				// we have the info from LDAP already, we don't need to talk to the server again
1608
-				if(isset($ldapRecord[$attribute])) {
1609
-					$this->connection->$uuidAttr = $attribute;
1610
-					return true;
1611
-				} else {
1612
-					continue;
1613
-				}
1614
-			}
1615
-
1616
-			$value = $this->readAttribute($dn, $attribute);
1617
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1618
-				\OCP\Util::writeLog('user_ldap',
1619
-									'Setting '.$attribute.' as '.$uuidAttr,
1620
-									\OCP\Util::DEBUG);
1621
-				$this->connection->$uuidAttr = $attribute;
1622
-				return true;
1623
-			}
1624
-		}
1625
-		\OCP\Util::writeLog('user_ldap',
1626
-							'Could not autodetect the UUID attribute',
1627
-							\OCP\Util::ERROR);
1628
-
1629
-		return false;
1630
-	}
1631
-
1632
-	/**
1633
-	 * @param string $dn
1634
-	 * @param bool $isUser
1635
-	 * @param null $ldapRecord
1636
-	 * @return bool|string
1637
-	 */
1638
-	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1639
-		if($isUser) {
1640
-			$uuidAttr     = 'ldapUuidUserAttribute';
1641
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1642
-		} else {
1643
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1644
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1645
-		}
1646
-
1647
-		$uuid = false;
1648
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1649
-			$attr = $this->connection->$uuidAttr;
1650
-			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1651
-			if( !is_array($uuid)
1652
-				&& $uuidOverride !== ''
1653
-				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1654
-			{
1655
-				$uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1656
-					? $ldapRecord[$this->connection->$uuidAttr]
1657
-					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1658
-			}
1659
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1660
-				$uuid = $uuid[0];
1661
-			}
1662
-		}
1663
-
1664
-		return $uuid;
1665
-	}
1666
-
1667
-	/**
1668
-	 * converts a binary ObjectGUID into a string representation
1669
-	 * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1670
-	 * @return string
1671
-	 * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1672
-	 */
1673
-	private function convertObjectGUID2Str($oguid) {
1674
-		$hex_guid = bin2hex($oguid);
1675
-		$hex_guid_to_guid_str = '';
1676
-		for($k = 1; $k <= 4; ++$k) {
1677
-			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1678
-		}
1679
-		$hex_guid_to_guid_str .= '-';
1680
-		for($k = 1; $k <= 2; ++$k) {
1681
-			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1682
-		}
1683
-		$hex_guid_to_guid_str .= '-';
1684
-		for($k = 1; $k <= 2; ++$k) {
1685
-			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1686
-		}
1687
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1688
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1689
-
1690
-		return strtoupper($hex_guid_to_guid_str);
1691
-	}
1692
-
1693
-	/**
1694
-	 * the first three blocks of the string-converted GUID happen to be in
1695
-	 * reverse order. In order to use it in a filter, this needs to be
1696
-	 * corrected. Furthermore the dashes need to be replaced and \\ preprended
1697
-	 * to every two hax figures.
1698
-	 *
1699
-	 * If an invalid string is passed, it will be returned without change.
1700
-	 *
1701
-	 * @param string $guid
1702
-	 * @return string
1703
-	 */
1704
-	public function formatGuid2ForFilterUser($guid) {
1705
-		if(!is_string($guid)) {
1706
-			throw new \InvalidArgumentException('String expected');
1707
-		}
1708
-		$blocks = explode('-', $guid);
1709
-		if(count($blocks) !== 5) {
1710
-			/*
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
+     * @throws \InvalidArgumentException
1308
+     */
1309
+    public function sanitizeUsername($name) {
1310
+        $name = trim($name);
1311
+
1312
+        if($this->connection->ldapIgnoreNamingRules) {
1313
+            return $name;
1314
+        }
1315
+
1316
+        // Transliteration to ASCII
1317
+        $transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1318
+        if($transliterated !== false) {
1319
+            // depending on system config iconv can work or not
1320
+            $name = $transliterated;
1321
+        }
1322
+
1323
+        // Replacements
1324
+        $name = str_replace(' ', '_', $name);
1325
+
1326
+        // Every remaining disallowed characters will be removed
1327
+        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1328
+
1329
+        if($name === '') {
1330
+            throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1331
+        }
1332
+
1333
+        return $name;
1334
+    }
1335
+
1336
+    /**
1337
+     * escapes (user provided) parts for LDAP filter
1338
+     * @param string $input, the provided value
1339
+     * @param bool $allowAsterisk whether in * at the beginning should be preserved
1340
+     * @return string the escaped string
1341
+     */
1342
+    public function escapeFilterPart($input, $allowAsterisk = false) {
1343
+        $asterisk = '';
1344
+        if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1345
+            $asterisk = '*';
1346
+            $input = mb_substr($input, 1, null, 'UTF-8');
1347
+        }
1348
+        $search  = array('*', '\\', '(', ')');
1349
+        $replace = array('\\*', '\\\\', '\\(', '\\)');
1350
+        return $asterisk . str_replace($search, $replace, $input);
1351
+    }
1352
+
1353
+    /**
1354
+     * combines the input filters with AND
1355
+     * @param string[] $filters the filters to connect
1356
+     * @return string the combined filter
1357
+     */
1358
+    public function combineFilterWithAnd($filters) {
1359
+        return $this->combineFilter($filters, '&');
1360
+    }
1361
+
1362
+    /**
1363
+     * combines the input filters with OR
1364
+     * @param string[] $filters the filters to connect
1365
+     * @return string the combined filter
1366
+     * Combines Filter arguments with OR
1367
+     */
1368
+    public function combineFilterWithOr($filters) {
1369
+        return $this->combineFilter($filters, '|');
1370
+    }
1371
+
1372
+    /**
1373
+     * combines the input filters with given operator
1374
+     * @param string[] $filters the filters to connect
1375
+     * @param string $operator either & or |
1376
+     * @return string the combined filter
1377
+     */
1378
+    private function combineFilter($filters, $operator) {
1379
+        $combinedFilter = '('.$operator;
1380
+        foreach($filters as $filter) {
1381
+            if ($filter !== '' && $filter[0] !== '(') {
1382
+                $filter = '('.$filter.')';
1383
+            }
1384
+            $combinedFilter.=$filter;
1385
+        }
1386
+        $combinedFilter.=')';
1387
+        return $combinedFilter;
1388
+    }
1389
+
1390
+    /**
1391
+     * creates a filter part for to perform search for users
1392
+     * @param string $search the search term
1393
+     * @return string the final filter part to use in LDAP searches
1394
+     */
1395
+    public function getFilterPartForUserSearch($search) {
1396
+        return $this->getFilterPartForSearch($search,
1397
+            $this->connection->ldapAttributesForUserSearch,
1398
+            $this->connection->ldapUserDisplayName);
1399
+    }
1400
+
1401
+    /**
1402
+     * creates a filter part for to perform search for groups
1403
+     * @param string $search the search term
1404
+     * @return string the final filter part to use in LDAP searches
1405
+     */
1406
+    public function getFilterPartForGroupSearch($search) {
1407
+        return $this->getFilterPartForSearch($search,
1408
+            $this->connection->ldapAttributesForGroupSearch,
1409
+            $this->connection->ldapGroupDisplayName);
1410
+    }
1411
+
1412
+    /**
1413
+     * creates a filter part for searches by splitting up the given search
1414
+     * string into single words
1415
+     * @param string $search the search term
1416
+     * @param string[] $searchAttributes needs to have at least two attributes,
1417
+     * otherwise it does not make sense :)
1418
+     * @return string the final filter part to use in LDAP searches
1419
+     * @throws \Exception
1420
+     */
1421
+    private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1422
+        if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1423
+            throw new \Exception('searchAttributes must be an array with at least two string');
1424
+        }
1425
+        $searchWords = explode(' ', trim($search));
1426
+        $wordFilters = array();
1427
+        foreach($searchWords as $word) {
1428
+            $word = $this->prepareSearchTerm($word);
1429
+            //every word needs to appear at least once
1430
+            $wordMatchOneAttrFilters = array();
1431
+            foreach($searchAttributes as $attr) {
1432
+                $wordMatchOneAttrFilters[] = $attr . '=' . $word;
1433
+            }
1434
+            $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1435
+        }
1436
+        return $this->combineFilterWithAnd($wordFilters);
1437
+    }
1438
+
1439
+    /**
1440
+     * creates a filter part for searches
1441
+     * @param string $search the search term
1442
+     * @param string[]|null $searchAttributes
1443
+     * @param string $fallbackAttribute a fallback attribute in case the user
1444
+     * did not define search attributes. Typically the display name attribute.
1445
+     * @return string the final filter part to use in LDAP searches
1446
+     */
1447
+    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1448
+        $filter = array();
1449
+        $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1450
+        if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1451
+            try {
1452
+                return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1453
+            } catch(\Exception $e) {
1454
+                \OCP\Util::writeLog(
1455
+                    'user_ldap',
1456
+                    'Creating advanced filter for search failed, falling back to simple method.',
1457
+                    \OCP\Util::INFO
1458
+                );
1459
+            }
1460
+        }
1461
+
1462
+        $search = $this->prepareSearchTerm($search);
1463
+        if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1464
+            if ($fallbackAttribute === '') {
1465
+                return '';
1466
+            }
1467
+            $filter[] = $fallbackAttribute . '=' . $search;
1468
+        } else {
1469
+            foreach($searchAttributes as $attribute) {
1470
+                $filter[] = $attribute . '=' . $search;
1471
+            }
1472
+        }
1473
+        if(count($filter) === 1) {
1474
+            return '('.$filter[0].')';
1475
+        }
1476
+        return $this->combineFilterWithOr($filter);
1477
+    }
1478
+
1479
+    /**
1480
+     * returns the search term depending on whether we are allowed
1481
+     * list users found by ldap with the current input appended by
1482
+     * a *
1483
+     * @return string
1484
+     */
1485
+    private function prepareSearchTerm($term) {
1486
+        $config = \OC::$server->getConfig();
1487
+
1488
+        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1489
+
1490
+        $result = $term;
1491
+        if ($term === '') {
1492
+            $result = '*';
1493
+        } else if ($allowEnum !== 'no') {
1494
+            $result = $term . '*';
1495
+        }
1496
+        return $result;
1497
+    }
1498
+
1499
+    /**
1500
+     * returns the filter used for counting users
1501
+     * @return string
1502
+     */
1503
+    public function getFilterForUserCount() {
1504
+        $filter = $this->combineFilterWithAnd(array(
1505
+            $this->connection->ldapUserFilter,
1506
+            $this->connection->ldapUserDisplayName . '=*'
1507
+        ));
1508
+
1509
+        return $filter;
1510
+    }
1511
+
1512
+    /**
1513
+     * @param string $name
1514
+     * @param string $password
1515
+     * @return bool
1516
+     */
1517
+    public function areCredentialsValid($name, $password) {
1518
+        $name = $this->helper->DNasBaseParameter($name);
1519
+        $testConnection = clone $this->connection;
1520
+        $credentials = array(
1521
+            'ldapAgentName' => $name,
1522
+            'ldapAgentPassword' => $password
1523
+        );
1524
+        if(!$testConnection->setConfiguration($credentials)) {
1525
+            return false;
1526
+        }
1527
+        return $testConnection->bind();
1528
+    }
1529
+
1530
+    /**
1531
+     * reverse lookup of a DN given a known UUID
1532
+     *
1533
+     * @param string $uuid
1534
+     * @return string
1535
+     * @throws \Exception
1536
+     */
1537
+    public function getUserDnByUuid($uuid) {
1538
+        $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1539
+        $filter       = $this->connection->ldapUserFilter;
1540
+        $base         = $this->connection->ldapBaseUsers;
1541
+
1542
+        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1543
+            // Sacrebleu! The UUID attribute is unknown :( We need first an
1544
+            // existing DN to be able to reliably detect it.
1545
+            $result = $this->search($filter, $base, ['dn'], 1);
1546
+            if(!isset($result[0]) || !isset($result[0]['dn'])) {
1547
+                throw new \Exception('Cannot determine UUID attribute');
1548
+            }
1549
+            $dn = $result[0]['dn'][0];
1550
+            if(!$this->detectUuidAttribute($dn, true)) {
1551
+                throw new \Exception('Cannot determine UUID attribute');
1552
+            }
1553
+        } else {
1554
+            // The UUID attribute is either known or an override is given.
1555
+            // By calling this method we ensure that $this->connection->$uuidAttr
1556
+            // is definitely set
1557
+            if(!$this->detectUuidAttribute('', true)) {
1558
+                throw new \Exception('Cannot determine UUID attribute');
1559
+            }
1560
+        }
1561
+
1562
+        $uuidAttr = $this->connection->ldapUuidUserAttribute;
1563
+        if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1564
+            $uuid = $this->formatGuid2ForFilterUser($uuid);
1565
+        }
1566
+
1567
+        $filter = $uuidAttr . '=' . $uuid;
1568
+        $result = $this->searchUsers($filter, ['dn'], 2);
1569
+        if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1570
+            // we put the count into account to make sure that this is
1571
+            // really unique
1572
+            return $result[0]['dn'][0];
1573
+        }
1574
+
1575
+        throw new \Exception('Cannot determine UUID attribute');
1576
+    }
1577
+
1578
+    /**
1579
+     * auto-detects the directory's UUID attribute
1580
+     *
1581
+     * @param string $dn a known DN used to check against
1582
+     * @param bool $isUser
1583
+     * @param bool $force the detection should be run, even if it is not set to auto
1584
+     * @param array|null $ldapRecord
1585
+     * @return bool true on success, false otherwise
1586
+     */
1587
+    private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1588
+        if($isUser) {
1589
+            $uuidAttr     = 'ldapUuidUserAttribute';
1590
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1591
+        } else {
1592
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1593
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1594
+        }
1595
+
1596
+        if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1597
+            return true;
1598
+        }
1599
+
1600
+        if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1601
+            $this->connection->$uuidAttr = $uuidOverride;
1602
+            return true;
1603
+        }
1604
+
1605
+        foreach(self::UUID_ATTRIBUTES as $attribute) {
1606
+            if($ldapRecord !== null) {
1607
+                // we have the info from LDAP already, we don't need to talk to the server again
1608
+                if(isset($ldapRecord[$attribute])) {
1609
+                    $this->connection->$uuidAttr = $attribute;
1610
+                    return true;
1611
+                } else {
1612
+                    continue;
1613
+                }
1614
+            }
1615
+
1616
+            $value = $this->readAttribute($dn, $attribute);
1617
+            if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1618
+                \OCP\Util::writeLog('user_ldap',
1619
+                                    'Setting '.$attribute.' as '.$uuidAttr,
1620
+                                    \OCP\Util::DEBUG);
1621
+                $this->connection->$uuidAttr = $attribute;
1622
+                return true;
1623
+            }
1624
+        }
1625
+        \OCP\Util::writeLog('user_ldap',
1626
+                            'Could not autodetect the UUID attribute',
1627
+                            \OCP\Util::ERROR);
1628
+
1629
+        return false;
1630
+    }
1631
+
1632
+    /**
1633
+     * @param string $dn
1634
+     * @param bool $isUser
1635
+     * @param null $ldapRecord
1636
+     * @return bool|string
1637
+     */
1638
+    public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1639
+        if($isUser) {
1640
+            $uuidAttr     = 'ldapUuidUserAttribute';
1641
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1642
+        } else {
1643
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1644
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1645
+        }
1646
+
1647
+        $uuid = false;
1648
+        if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1649
+            $attr = $this->connection->$uuidAttr;
1650
+            $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1651
+            if( !is_array($uuid)
1652
+                && $uuidOverride !== ''
1653
+                && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1654
+            {
1655
+                $uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1656
+                    ? $ldapRecord[$this->connection->$uuidAttr]
1657
+                    : $this->readAttribute($dn, $this->connection->$uuidAttr);
1658
+            }
1659
+            if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1660
+                $uuid = $uuid[0];
1661
+            }
1662
+        }
1663
+
1664
+        return $uuid;
1665
+    }
1666
+
1667
+    /**
1668
+     * converts a binary ObjectGUID into a string representation
1669
+     * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1670
+     * @return string
1671
+     * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1672
+     */
1673
+    private function convertObjectGUID2Str($oguid) {
1674
+        $hex_guid = bin2hex($oguid);
1675
+        $hex_guid_to_guid_str = '';
1676
+        for($k = 1; $k <= 4; ++$k) {
1677
+            $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1678
+        }
1679
+        $hex_guid_to_guid_str .= '-';
1680
+        for($k = 1; $k <= 2; ++$k) {
1681
+            $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1682
+        }
1683
+        $hex_guid_to_guid_str .= '-';
1684
+        for($k = 1; $k <= 2; ++$k) {
1685
+            $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1686
+        }
1687
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1688
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1689
+
1690
+        return strtoupper($hex_guid_to_guid_str);
1691
+    }
1692
+
1693
+    /**
1694
+     * the first three blocks of the string-converted GUID happen to be in
1695
+     * reverse order. In order to use it in a filter, this needs to be
1696
+     * corrected. Furthermore the dashes need to be replaced and \\ preprended
1697
+     * to every two hax figures.
1698
+     *
1699
+     * If an invalid string is passed, it will be returned without change.
1700
+     *
1701
+     * @param string $guid
1702
+     * @return string
1703
+     */
1704
+    public function formatGuid2ForFilterUser($guid) {
1705
+        if(!is_string($guid)) {
1706
+            throw new \InvalidArgumentException('String expected');
1707
+        }
1708
+        $blocks = explode('-', $guid);
1709
+        if(count($blocks) !== 5) {
1710
+            /*
1711 1711
 			 * Why not throw an Exception instead? This method is a utility
1712 1712
 			 * called only when trying to figure out whether a "missing" known
1713 1713
 			 * LDAP user was or was not renamed on the LDAP server. And this
@@ -1718,270 +1718,270 @@  discard block
 block discarded – undo
1718 1718
 			 * an exception here would kill the experience for a valid, acting
1719 1719
 			 * user. Instead we write a log message.
1720 1720
 			 */
1721
-			\OC::$server->getLogger()->info(
1722
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1723
-				'({uuid}) probably does not match UUID configuration.',
1724
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1725
-			);
1726
-			return $guid;
1727
-		}
1728
-		for($i=0; $i < 3; $i++) {
1729
-			$pairs = str_split($blocks[$i], 2);
1730
-			$pairs = array_reverse($pairs);
1731
-			$blocks[$i] = implode('', $pairs);
1732
-		}
1733
-		for($i=0; $i < 5; $i++) {
1734
-			$pairs = str_split($blocks[$i], 2);
1735
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1736
-		}
1737
-		return implode('', $blocks);
1738
-	}
1739
-
1740
-	/**
1741
-	 * gets a SID of the domain of the given dn
1742
-	 * @param string $dn
1743
-	 * @return string|bool
1744
-	 */
1745
-	public function getSID($dn) {
1746
-		$domainDN = $this->getDomainDNFromDN($dn);
1747
-		$cacheKey = 'getSID-'.$domainDN;
1748
-		$sid = $this->connection->getFromCache($cacheKey);
1749
-		if(!is_null($sid)) {
1750
-			return $sid;
1751
-		}
1752
-
1753
-		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1754
-		if(!is_array($objectSid) || empty($objectSid)) {
1755
-			$this->connection->writeToCache($cacheKey, false);
1756
-			return false;
1757
-		}
1758
-		$domainObjectSid = $this->convertSID2Str($objectSid[0]);
1759
-		$this->connection->writeToCache($cacheKey, $domainObjectSid);
1760
-
1761
-		return $domainObjectSid;
1762
-	}
1763
-
1764
-	/**
1765
-	 * converts a binary SID into a string representation
1766
-	 * @param string $sid
1767
-	 * @return string
1768
-	 */
1769
-	public function convertSID2Str($sid) {
1770
-		// The format of a SID binary string is as follows:
1771
-		// 1 byte for the revision level
1772
-		// 1 byte for the number n of variable sub-ids
1773
-		// 6 bytes for identifier authority value
1774
-		// n*4 bytes for n sub-ids
1775
-		//
1776
-		// Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1777
-		//  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1778
-		$revision = ord($sid[0]);
1779
-		$numberSubID = ord($sid[1]);
1780
-
1781
-		$subIdStart = 8; // 1 + 1 + 6
1782
-		$subIdLength = 4;
1783
-		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1784
-			// Incorrect number of bytes present.
1785
-			return '';
1786
-		}
1787
-
1788
-		// 6 bytes = 48 bits can be represented using floats without loss of
1789
-		// precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1790
-		$iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1791
-
1792
-		$subIDs = array();
1793
-		for ($i = 0; $i < $numberSubID; $i++) {
1794
-			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1795
-			$subIDs[] = sprintf('%u', $subID[1]);
1796
-		}
1797
-
1798
-		// Result for example above: S-1-5-21-249921958-728525901-1594176202
1799
-		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1800
-	}
1801
-
1802
-	/**
1803
-	 * checks if the given DN is part of the given base DN(s)
1804
-	 * @param string $dn the DN
1805
-	 * @param string[] $bases array containing the allowed base DN or DNs
1806
-	 * @return bool
1807
-	 */
1808
-	public function isDNPartOfBase($dn, $bases) {
1809
-		$belongsToBase = false;
1810
-		$bases = $this->helper->sanitizeDN($bases);
1811
-
1812
-		foreach($bases as $base) {
1813
-			$belongsToBase = true;
1814
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1815
-				$belongsToBase = false;
1816
-			}
1817
-			if($belongsToBase) {
1818
-				break;
1819
-			}
1820
-		}
1821
-		return $belongsToBase;
1822
-	}
1823
-
1824
-	/**
1825
-	 * resets a running Paged Search operation
1826
-	 */
1827
-	private function abandonPagedSearch() {
1828
-		if($this->connection->hasPagedResultSupport) {
1829
-			$cr = $this->connection->getConnectionResource();
1830
-			$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1831
-			$this->getPagedSearchResultState();
1832
-			$this->lastCookie = '';
1833
-			$this->cookies = array();
1834
-		}
1835
-	}
1836
-
1837
-	/**
1838
-	 * get a cookie for the next LDAP paged search
1839
-	 * @param string $base a string with the base DN for the search
1840
-	 * @param string $filter the search filter to identify the correct search
1841
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1842
-	 * @param int $offset the offset for the new search to identify the correct search really good
1843
-	 * @return string containing the key or empty if none is cached
1844
-	 */
1845
-	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1846
-		if($offset === 0) {
1847
-			return '';
1848
-		}
1849
-		$offset -= $limit;
1850
-		//we work with cache here
1851
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1852
-		$cookie = '';
1853
-		if(isset($this->cookies[$cacheKey])) {
1854
-			$cookie = $this->cookies[$cacheKey];
1855
-			if(is_null($cookie)) {
1856
-				$cookie = '';
1857
-			}
1858
-		}
1859
-		return $cookie;
1860
-	}
1861
-
1862
-	/**
1863
-	 * checks whether an LDAP paged search operation has more pages that can be
1864
-	 * retrieved, typically when offset and limit are provided.
1865
-	 *
1866
-	 * Be very careful to use it: the last cookie value, which is inspected, can
1867
-	 * be reset by other operations. Best, call it immediately after a search(),
1868
-	 * searchUsers() or searchGroups() call. count-methods are probably safe as
1869
-	 * well. Don't rely on it with any fetchList-method.
1870
-	 * @return bool
1871
-	 */
1872
-	public function hasMoreResults() {
1873
-		if(!$this->connection->hasPagedResultSupport) {
1874
-			return false;
1875
-		}
1876
-
1877
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1878
-			// as in RFC 2696, when all results are returned, the cookie will
1879
-			// be empty.
1880
-			return false;
1881
-		}
1882
-
1883
-		return true;
1884
-	}
1885
-
1886
-	/**
1887
-	 * set a cookie for LDAP paged search run
1888
-	 * @param string $base a string with the base DN for the search
1889
-	 * @param string $filter the search filter to identify the correct search
1890
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1891
-	 * @param int $offset the offset for the run search to identify the correct search really good
1892
-	 * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1893
-	 * @return void
1894
-	 */
1895
-	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1896
-		// allow '0' for 389ds
1897
-		if(!empty($cookie) || $cookie === '0') {
1898
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1899
-			$this->cookies[$cacheKey] = $cookie;
1900
-			$this->lastCookie = $cookie;
1901
-		}
1902
-	}
1903
-
1904
-	/**
1905
-	 * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1906
-	 * @return boolean|null true on success, null or false otherwise
1907
-	 */
1908
-	public function getPagedSearchResultState() {
1909
-		$result = $this->pagedSearchedSuccessful;
1910
-		$this->pagedSearchedSuccessful = null;
1911
-		return $result;
1912
-	}
1913
-
1914
-	/**
1915
-	 * Prepares a paged search, if possible
1916
-	 * @param string $filter the LDAP filter for the search
1917
-	 * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1918
-	 * @param string[] $attr optional, when a certain attribute shall be filtered outside
1919
-	 * @param int $limit
1920
-	 * @param int $offset
1921
-	 * @return bool|true
1922
-	 */
1923
-	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1924
-		$pagedSearchOK = false;
1925
-		if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1926
-			$offset = (int)$offset; //can be null
1927
-			\OCP\Util::writeLog('user_ldap',
1928
-				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1929
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1930
-				\OCP\Util::DEBUG);
1931
-			//get the cookie from the search for the previous search, required by LDAP
1932
-			foreach($bases as $base) {
1933
-
1934
-				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1935
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1936
-					// no cookie known from a potential previous search. We need
1937
-					// to start from 0 to come to the desired page. cookie value
1938
-					// of '0' is valid, because 389ds
1939
-					$reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
1940
-					$this->search($filter, array($base), $attr, $limit, $reOffset, true);
1941
-					$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1942
-					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1943
-					// '0' is valid, because 389ds
1944
-					//TODO: remember this, probably does not change in the next request...
1945
-					if(empty($cookie) && $cookie !== '0') {
1946
-						$cookie = null;
1947
-					}
1948
-				}
1949
-				if(!is_null($cookie)) {
1950
-					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1951
-					$this->abandonPagedSearch();
1952
-					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1953
-						$this->connection->getConnectionResource(), $limit,
1954
-						false, $cookie);
1955
-					if(!$pagedSearchOK) {
1956
-						return false;
1957
-					}
1958
-					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
1959
-				} else {
1960
-					$e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset);
1961
-					\OC::$server->getLogger()->logException($e, ['level' => Util::DEBUG]);
1962
-				}
1963
-
1964
-			}
1965
-		/* ++ Fixing RHDS searches with pages with zero results ++
1721
+            \OC::$server->getLogger()->info(
1722
+                'Passed string does not resemble a valid GUID. Known UUID ' .
1723
+                '({uuid}) probably does not match UUID configuration.',
1724
+                [ 'app' => 'user_ldap', 'uuid' => $guid ]
1725
+            );
1726
+            return $guid;
1727
+        }
1728
+        for($i=0; $i < 3; $i++) {
1729
+            $pairs = str_split($blocks[$i], 2);
1730
+            $pairs = array_reverse($pairs);
1731
+            $blocks[$i] = implode('', $pairs);
1732
+        }
1733
+        for($i=0; $i < 5; $i++) {
1734
+            $pairs = str_split($blocks[$i], 2);
1735
+            $blocks[$i] = '\\' . implode('\\', $pairs);
1736
+        }
1737
+        return implode('', $blocks);
1738
+    }
1739
+
1740
+    /**
1741
+     * gets a SID of the domain of the given dn
1742
+     * @param string $dn
1743
+     * @return string|bool
1744
+     */
1745
+    public function getSID($dn) {
1746
+        $domainDN = $this->getDomainDNFromDN($dn);
1747
+        $cacheKey = 'getSID-'.$domainDN;
1748
+        $sid = $this->connection->getFromCache($cacheKey);
1749
+        if(!is_null($sid)) {
1750
+            return $sid;
1751
+        }
1752
+
1753
+        $objectSid = $this->readAttribute($domainDN, 'objectsid');
1754
+        if(!is_array($objectSid) || empty($objectSid)) {
1755
+            $this->connection->writeToCache($cacheKey, false);
1756
+            return false;
1757
+        }
1758
+        $domainObjectSid = $this->convertSID2Str($objectSid[0]);
1759
+        $this->connection->writeToCache($cacheKey, $domainObjectSid);
1760
+
1761
+        return $domainObjectSid;
1762
+    }
1763
+
1764
+    /**
1765
+     * converts a binary SID into a string representation
1766
+     * @param string $sid
1767
+     * @return string
1768
+     */
1769
+    public function convertSID2Str($sid) {
1770
+        // The format of a SID binary string is as follows:
1771
+        // 1 byte for the revision level
1772
+        // 1 byte for the number n of variable sub-ids
1773
+        // 6 bytes for identifier authority value
1774
+        // n*4 bytes for n sub-ids
1775
+        //
1776
+        // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1777
+        //  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1778
+        $revision = ord($sid[0]);
1779
+        $numberSubID = ord($sid[1]);
1780
+
1781
+        $subIdStart = 8; // 1 + 1 + 6
1782
+        $subIdLength = 4;
1783
+        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1784
+            // Incorrect number of bytes present.
1785
+            return '';
1786
+        }
1787
+
1788
+        // 6 bytes = 48 bits can be represented using floats without loss of
1789
+        // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1790
+        $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1791
+
1792
+        $subIDs = array();
1793
+        for ($i = 0; $i < $numberSubID; $i++) {
1794
+            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1795
+            $subIDs[] = sprintf('%u', $subID[1]);
1796
+        }
1797
+
1798
+        // Result for example above: S-1-5-21-249921958-728525901-1594176202
1799
+        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1800
+    }
1801
+
1802
+    /**
1803
+     * checks if the given DN is part of the given base DN(s)
1804
+     * @param string $dn the DN
1805
+     * @param string[] $bases array containing the allowed base DN or DNs
1806
+     * @return bool
1807
+     */
1808
+    public function isDNPartOfBase($dn, $bases) {
1809
+        $belongsToBase = false;
1810
+        $bases = $this->helper->sanitizeDN($bases);
1811
+
1812
+        foreach($bases as $base) {
1813
+            $belongsToBase = true;
1814
+            if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1815
+                $belongsToBase = false;
1816
+            }
1817
+            if($belongsToBase) {
1818
+                break;
1819
+            }
1820
+        }
1821
+        return $belongsToBase;
1822
+    }
1823
+
1824
+    /**
1825
+     * resets a running Paged Search operation
1826
+     */
1827
+    private function abandonPagedSearch() {
1828
+        if($this->connection->hasPagedResultSupport) {
1829
+            $cr = $this->connection->getConnectionResource();
1830
+            $this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1831
+            $this->getPagedSearchResultState();
1832
+            $this->lastCookie = '';
1833
+            $this->cookies = array();
1834
+        }
1835
+    }
1836
+
1837
+    /**
1838
+     * get a cookie for the next LDAP paged search
1839
+     * @param string $base a string with the base DN for the search
1840
+     * @param string $filter the search filter to identify the correct search
1841
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1842
+     * @param int $offset the offset for the new search to identify the correct search really good
1843
+     * @return string containing the key or empty if none is cached
1844
+     */
1845
+    private function getPagedResultCookie($base, $filter, $limit, $offset) {
1846
+        if($offset === 0) {
1847
+            return '';
1848
+        }
1849
+        $offset -= $limit;
1850
+        //we work with cache here
1851
+        $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1852
+        $cookie = '';
1853
+        if(isset($this->cookies[$cacheKey])) {
1854
+            $cookie = $this->cookies[$cacheKey];
1855
+            if(is_null($cookie)) {
1856
+                $cookie = '';
1857
+            }
1858
+        }
1859
+        return $cookie;
1860
+    }
1861
+
1862
+    /**
1863
+     * checks whether an LDAP paged search operation has more pages that can be
1864
+     * retrieved, typically when offset and limit are provided.
1865
+     *
1866
+     * Be very careful to use it: the last cookie value, which is inspected, can
1867
+     * be reset by other operations. Best, call it immediately after a search(),
1868
+     * searchUsers() or searchGroups() call. count-methods are probably safe as
1869
+     * well. Don't rely on it with any fetchList-method.
1870
+     * @return bool
1871
+     */
1872
+    public function hasMoreResults() {
1873
+        if(!$this->connection->hasPagedResultSupport) {
1874
+            return false;
1875
+        }
1876
+
1877
+        if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1878
+            // as in RFC 2696, when all results are returned, the cookie will
1879
+            // be empty.
1880
+            return false;
1881
+        }
1882
+
1883
+        return true;
1884
+    }
1885
+
1886
+    /**
1887
+     * set a cookie for LDAP paged search run
1888
+     * @param string $base a string with the base DN for the search
1889
+     * @param string $filter the search filter to identify the correct search
1890
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1891
+     * @param int $offset the offset for the run search to identify the correct search really good
1892
+     * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1893
+     * @return void
1894
+     */
1895
+    private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1896
+        // allow '0' for 389ds
1897
+        if(!empty($cookie) || $cookie === '0') {
1898
+            $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1899
+            $this->cookies[$cacheKey] = $cookie;
1900
+            $this->lastCookie = $cookie;
1901
+        }
1902
+    }
1903
+
1904
+    /**
1905
+     * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1906
+     * @return boolean|null true on success, null or false otherwise
1907
+     */
1908
+    public function getPagedSearchResultState() {
1909
+        $result = $this->pagedSearchedSuccessful;
1910
+        $this->pagedSearchedSuccessful = null;
1911
+        return $result;
1912
+    }
1913
+
1914
+    /**
1915
+     * Prepares a paged search, if possible
1916
+     * @param string $filter the LDAP filter for the search
1917
+     * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1918
+     * @param string[] $attr optional, when a certain attribute shall be filtered outside
1919
+     * @param int $limit
1920
+     * @param int $offset
1921
+     * @return bool|true
1922
+     */
1923
+    private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1924
+        $pagedSearchOK = false;
1925
+        if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1926
+            $offset = (int)$offset; //can be null
1927
+            \OCP\Util::writeLog('user_ldap',
1928
+                'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1929
+                .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1930
+                \OCP\Util::DEBUG);
1931
+            //get the cookie from the search for the previous search, required by LDAP
1932
+            foreach($bases as $base) {
1933
+
1934
+                $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1935
+                if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1936
+                    // no cookie known from a potential previous search. We need
1937
+                    // to start from 0 to come to the desired page. cookie value
1938
+                    // of '0' is valid, because 389ds
1939
+                    $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
1940
+                    $this->search($filter, array($base), $attr, $limit, $reOffset, true);
1941
+                    $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1942
+                    //still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1943
+                    // '0' is valid, because 389ds
1944
+                    //TODO: remember this, probably does not change in the next request...
1945
+                    if(empty($cookie) && $cookie !== '0') {
1946
+                        $cookie = null;
1947
+                    }
1948
+                }
1949
+                if(!is_null($cookie)) {
1950
+                    //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1951
+                    $this->abandonPagedSearch();
1952
+                    $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1953
+                        $this->connection->getConnectionResource(), $limit,
1954
+                        false, $cookie);
1955
+                    if(!$pagedSearchOK) {
1956
+                        return false;
1957
+                    }
1958
+                    \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
1959
+                } else {
1960
+                    $e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset);
1961
+                    \OC::$server->getLogger()->logException($e, ['level' => Util::DEBUG]);
1962
+                }
1963
+
1964
+            }
1965
+        /* ++ Fixing RHDS searches with pages with zero results ++
1966 1966
 		 * We coudn't get paged searches working with our RHDS for login ($limit = 0),
1967 1967
 		 * due to pages with zero results.
1968 1968
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
1969 1969
 		 * if we don't have a previous paged search.
1970 1970
 		 */
1971
-		} else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1972
-			// a search without limit was requested. However, if we do use
1973
-			// Paged Search once, we always must do it. This requires us to
1974
-			// initialize it with the configured page size.
1975
-			$this->abandonPagedSearch();
1976
-			// in case someone set it to 0 … use 500, otherwise no results will
1977
-			// be returned.
1978
-			$pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
1979
-			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1980
-				$this->connection->getConnectionResource(),
1981
-				$pageSize, false, '');
1982
-		}
1983
-
1984
-		return $pagedSearchOK;
1985
-	}
1971
+        } else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1972
+            // a search without limit was requested. However, if we do use
1973
+            // Paged Search once, we always must do it. This requires us to
1974
+            // initialize it with the configured page size.
1975
+            $this->abandonPagedSearch();
1976
+            // in case someone set it to 0 … use 500, otherwise no results will
1977
+            // be returned.
1978
+            $pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
1979
+            $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1980
+                $this->connection->getConnectionResource(),
1981
+                $pageSize, false, '');
1982
+        }
1983
+
1984
+        return $pagedSearchOK;
1985
+    }
1986 1986
 
1987 1987
 }
Please login to merge, or discard this patch.