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