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